postinstall.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  26. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  27. return new (P || (P = Promise))(function (resolve, reject) {
  28. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  29. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  30. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  31. step((generator = generator.apply(thisArg, _arguments || [])).next());
  32. });
  33. };
  34. Object.defineProperty(exports, "__esModule", { value: true });
  35. /**
  36. * A postinstall script runs after `@swc/core` is installed.
  37. *
  38. * It checks if corresponding optional dependencies for native binary is installed and can be loaded properly.
  39. * If it fails, it'll internally try to install `@swc/wasm` as fallback.
  40. */
  41. const fs_1 = require("fs");
  42. const assert = __importStar(require("assert"));
  43. const path = __importStar(require("path"));
  44. const child_process = __importStar(require("child_process"));
  45. const fs = __importStar(require("fs"));
  46. function removeRecursive(dir) {
  47. for (const entry of fs.readdirSync(dir)) {
  48. const entryPath = path.join(dir, entry);
  49. let stats;
  50. try {
  51. stats = fs.lstatSync(entryPath);
  52. }
  53. catch (_a) {
  54. continue; // Guard against https://github.com/nodejs/node/issues/4760
  55. }
  56. if (stats.isDirectory())
  57. removeRecursive(entryPath);
  58. else
  59. fs.unlinkSync(entryPath);
  60. }
  61. fs.rmdirSync(dir);
  62. }
  63. /**
  64. * Trying to validate @swc/core's native binary installation, then installs if it is not supported.
  65. */
  66. const validateBinary = () => __awaiter(void 0, void 0, void 0, function* () {
  67. var _a;
  68. try {
  69. const { name } = require(path.resolve(process.env.INIT_CWD, 'package.json'));
  70. if (name === '@swc/core') {
  71. return;
  72. }
  73. }
  74. catch (_) {
  75. return;
  76. }
  77. // TODO: We do not take care of the case if user try to install with `--no-optional`.
  78. // For now, it is considered as deliberate decision.
  79. let binding;
  80. try {
  81. binding = require('./binding');
  82. // Check if binding binary actually works.
  83. // For the latest version, checks target triple. If it's old version doesn't have target triple, use parseSync instead.
  84. const triple = binding.getTargetTriple ? binding.getTargetTriple() : binding.parseSync('console.log()', Buffer.from(JSON.stringify({ syntax: "ecmascript" })));
  85. assert.ok(triple, 'Failed to read target triple from native binary.');
  86. }
  87. catch (error) {
  88. // if error is unsupported architecture, ignore to display.
  89. if (!((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Unsupported architecture'))) {
  90. console.warn(error);
  91. }
  92. console.warn(`@swc/core was not able to resolve native bindings installation. It'll try to use @swc/wasm as fallback instead.`);
  93. }
  94. if (!!binding) {
  95. return;
  96. }
  97. // User choose to override the binary installation. Skip remanining validation.
  98. if (!!process.env["SWC_BINARY_PATH"]) {
  99. console.warn(`@swc/core could not resolve native bindings installation, but found manual override config SWC_BINARY_PATH specified. Skipping remaning validation.`);
  100. return;
  101. }
  102. // Check if top-level package.json installs @swc/wasm separately already
  103. let wasmBinding;
  104. try {
  105. wasmBinding = require.resolve(`@swc/wasm`);
  106. }
  107. catch (_) {
  108. }
  109. if (!!wasmBinding && (0, fs_1.existsSync)(wasmBinding)) {
  110. return;
  111. }
  112. const env = Object.assign(Object.assign({}, process.env), { npm_config_global: undefined });
  113. const { version } = require(path.join(path.dirname(require.resolve('@swc/core')), 'package.json'));
  114. // We want to place @swc/wasm next to the @swc/core as if normal installation was done,
  115. // but can't directly set cwd to INIT_CWD as npm seems to acquire lock to the working dir.
  116. // Instead, create a temporary inner and move it out.
  117. const coreDir = path.dirname(require.resolve('@swc/core'));
  118. const installDir = path.join(coreDir, 'npm-install');
  119. try {
  120. fs.mkdirSync(installDir);
  121. fs.writeFileSync(path.join(installDir, 'package.json'), '{}');
  122. // Instead of carrying over own dependencies to download & resolve package which increases installation sizes of `@swc/core`,
  123. // assume & relies on system's npm installation.
  124. child_process.execSync(`npm install --no-save --loglevel=error --prefer-offline --no-audit --progress=false @swc/wasm@${version}`, { cwd: installDir, stdio: 'pipe', env });
  125. const installedBinPath = path.join(installDir, 'node_modules', `@swc/wasm`);
  126. // INIT_CWD is injected via npm. If it doesn't exists, can't proceed.
  127. fs.renameSync(installedBinPath, path.resolve(process.env.INIT_CWD, 'node_modules', `@swc/wasm`));
  128. }
  129. catch (error) {
  130. console.error(error);
  131. console.error(`Failed to install fallback @swc/wasm@${version}. @swc/core will not properly.
  132. Please install @swc/wasm manually, or retry whole installation.
  133. If there are unexpected errors, please report at https://github.com/swc-project/swc/issues`);
  134. }
  135. finally {
  136. try {
  137. removeRecursive(installDir);
  138. }
  139. catch (_) {
  140. // Gracefully ignore any failures. This'll make few leftover files but it shouldn't block installation.
  141. }
  142. }
  143. });
  144. validateBinary().catch((error) => {
  145. // for now just throw the error as-is.
  146. throw error;
  147. });