download-wasm-swc.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.downloadWasmSwc = downloadWasmSwc;
  6. var _os = _interopRequireDefault(require("os"));
  7. var _fs = _interopRequireDefault(require("fs"));
  8. var _path = _interopRequireDefault(require("path"));
  9. var Log = _interopRequireWildcard(require("../build/output/log"));
  10. var _childProcess = require("child_process");
  11. var _tar = _interopRequireDefault(require("next/dist/compiled/tar"));
  12. var _nodeFetch = _interopRequireDefault(require("next/dist/compiled/node-fetch"));
  13. var _fileExists = require("./file-exists");
  14. function _interopRequireDefault(obj) {
  15. return obj && obj.__esModule ? obj : {
  16. default: obj
  17. };
  18. }
  19. function _getRequireWildcardCache() {
  20. if (typeof WeakMap !== "function") return null;
  21. var cache = new WeakMap();
  22. _getRequireWildcardCache = function() {
  23. return cache;
  24. };
  25. return cache;
  26. }
  27. function _interopRequireWildcard(obj) {
  28. if (obj && obj.__esModule) {
  29. return obj;
  30. }
  31. if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
  32. return {
  33. default: obj
  34. };
  35. }
  36. var cache = _getRequireWildcardCache();
  37. if (cache && cache.has(obj)) {
  38. return cache.get(obj);
  39. }
  40. var newObj = {};
  41. var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
  42. for(var key in obj){
  43. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  44. var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
  45. if (desc && (desc.get || desc.set)) {
  46. Object.defineProperty(newObj, key, desc);
  47. } else {
  48. newObj[key] = obj[key];
  49. }
  50. }
  51. }
  52. newObj.default = obj;
  53. if (cache) {
  54. cache.set(obj, newObj);
  55. }
  56. return newObj;
  57. }
  58. const MAX_VERSIONS_TO_CACHE = 5;
  59. async function downloadWasmSwc(version, wasmDirectory, variant = "nodejs") {
  60. const pkgName = `@next/swc-wasm-${variant}`;
  61. const tarFileName = `${pkgName.substring(6)}-${version}.tgz`;
  62. const outputDirectory = _path.default.join(wasmDirectory, pkgName);
  63. if (await (0, _fileExists).fileExists(outputDirectory)) {
  64. // if the package is already downloaded a different
  65. // failure occurred than not being present
  66. return;
  67. }
  68. // get platform specific cache directory adapted from playwright's handling
  69. // https://github.com/microsoft/playwright/blob/7d924470d397975a74a19184c136b3573a974e13/packages/playwright-core/src/utils/registry.ts#L141
  70. const cacheDirectory = await (async ()=>{
  71. let result;
  72. const envDefined = process.env["NEXT_SWC_PATH"];
  73. if (envDefined) {
  74. result = envDefined;
  75. } else {
  76. let systemCacheDirectory;
  77. if (process.platform === "linux") {
  78. systemCacheDirectory = process.env.XDG_CACHE_HOME || _path.default.join(_os.default.homedir(), ".cache");
  79. } else if (process.platform === "darwin") {
  80. systemCacheDirectory = _path.default.join(_os.default.homedir(), "Library", "Caches");
  81. } else if (process.platform === "win32") {
  82. systemCacheDirectory = process.env.LOCALAPPDATA || _path.default.join(_os.default.homedir(), "AppData", "Local");
  83. } else {
  84. /// Attempt to use generic tmp location for these platforms
  85. if (process.platform === "freebsd" || process.platform === "android") {
  86. for (const dir of [
  87. _path.default.join(_os.default.homedir(), ".cache"),
  88. _path.default.join(_os.default.tmpdir()),
  89. ]){
  90. if (await (0, _fileExists).fileExists(dir)) {
  91. systemCacheDirectory = dir;
  92. break;
  93. }
  94. }
  95. }
  96. if (!systemCacheDirectory) {
  97. console.error(new Error("Unsupported platform: " + process.platform));
  98. process.exit(0);
  99. }
  100. }
  101. result = _path.default.join(systemCacheDirectory, "next-swc");
  102. }
  103. if (!_path.default.isAbsolute(result)) {
  104. // It is important to resolve to the absolute path:
  105. // - for unzipping to work correctly;
  106. // - so that registry directory matches between installation and execution.
  107. // INIT_CWD points to the root of `npm/yarn install` and is probably what
  108. // the user meant when typing the relative path.
  109. result = _path.default.resolve(process.env["INIT_CWD"] || process.cwd(), result);
  110. }
  111. return result;
  112. })();
  113. await _fs.default.promises.mkdir(outputDirectory, {
  114. recursive: true
  115. });
  116. const extractFromTar = async ()=>{
  117. await _tar.default.x({
  118. file: _path.default.join(cacheDirectory, tarFileName),
  119. cwd: outputDirectory,
  120. strip: 1
  121. });
  122. };
  123. if (!await (0, _fileExists).fileExists(_path.default.join(cacheDirectory, tarFileName))) {
  124. Log.info("Downloading WASM swc package...");
  125. await _fs.default.promises.mkdir(cacheDirectory, {
  126. recursive: true
  127. });
  128. const tempFile = _path.default.join(cacheDirectory, `${tarFileName}.temp-${Date.now()}`);
  129. let registry = `https://registry.npmjs.org/`;
  130. try {
  131. const output = (0, _childProcess).execSync("npm config get registry").toString().trim();
  132. if (output.startsWith("http")) {
  133. registry = output.endsWith("/") ? output : `${output}/`;
  134. }
  135. } catch (_) {}
  136. await (0, _nodeFetch).default(`${registry}${pkgName}/-/${tarFileName}`).then((res)=>{
  137. if (!res.ok) {
  138. throw new Error(`request failed with status ${res.status}`);
  139. }
  140. const cacheWriteStream = _fs.default.createWriteStream(tempFile);
  141. return new Promise((resolve, reject)=>{
  142. res.body.pipe(cacheWriteStream).on("error", (err)=>reject(err)).on("finish", ()=>resolve());
  143. }).finally(()=>cacheWriteStream.close());
  144. });
  145. await _fs.default.promises.rename(tempFile, _path.default.join(cacheDirectory, tarFileName));
  146. }
  147. await extractFromTar();
  148. const cacheFiles = await _fs.default.promises.readdir(cacheDirectory);
  149. if (cacheFiles.length > MAX_VERSIONS_TO_CACHE) {
  150. cacheFiles.sort((a, b)=>{
  151. if (a.length < b.length) return -1;
  152. return a.localeCompare(b);
  153. });
  154. // prune oldest versions in cache
  155. for(let i = 0; i++; i < cacheFiles.length - MAX_VERSIONS_TO_CACHE){
  156. await _fs.default.promises.unlink(_path.default.join(cacheDirectory, cacheFiles[i])).catch(()=>{});
  157. }
  158. }
  159. }
  160. //# sourceMappingURL=download-wasm-swc.js.map