jiti-hooks.mjs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import { dirname, join } from "node:path";
  2. import { fileURLToPath } from "node:url";
  3. import { existsSync } from "node:fs";
  4. import { readFile } from "node:fs/promises";
  5. import { isBuiltin } from "node:module";
  6. import { createJiti } from "./jiti.mjs";
  7. let jiti;
  8. // https://nodejs.org/api/module.html#initialize
  9. export async function initialize() {
  10. jiti = createJiti();
  11. }
  12. // https://nodejs.org/api/module.html#resolvespecifier-context-nextresolve
  13. export async function resolve(specifier, context, nextResolve) {
  14. if (_shouldSkip(specifier)) {
  15. return nextResolve(specifier, context);
  16. }
  17. const resolvedPath = jiti.esmResolve(specifier, {
  18. parentURL: context?.parentURL,
  19. conditions: context?.conditions,
  20. });
  21. return {
  22. url: resolvedPath,
  23. shortCircuit: true,
  24. };
  25. }
  26. // https://nodejs.org/api/module.html#loadurl-context-nextload
  27. export async function load(url, context, nextLoad) {
  28. if (_shouldSkip(url)) {
  29. return nextLoad(url, context);
  30. }
  31. const filename = fileURLToPath(url);
  32. if (url.endsWith(".js")) {
  33. const pkg = await _findClosestPackageJson(dirname(filename));
  34. if (pkg && pkg.type === "module") {
  35. return nextLoad(url, context);
  36. }
  37. }
  38. const rawSource = await readFile(filename, "utf8");
  39. if (url.endsWith(".json")) {
  40. return {
  41. source: `export default ${rawSource}`,
  42. format: "module",
  43. shortCircuit: true,
  44. };
  45. }
  46. const transpiledSource = jiti.transform({
  47. source: rawSource,
  48. filename: filename,
  49. ts: url.endsWith("ts"),
  50. retainLines: true,
  51. async: true,
  52. jsx: jiti.options.jsx,
  53. });
  54. if (url.endsWith(".js") && !transpiledSource.includes("jitiImport")) {
  55. return {
  56. source: transpiledSource,
  57. format: "commonjs",
  58. shortCircuit: true,
  59. };
  60. }
  61. return {
  62. source: _wrapSource(transpiledSource, filename),
  63. format: "module",
  64. shortCircuit: true,
  65. };
  66. }
  67. function _wrapSource(source, filename) {
  68. const _jitiPath = new URL("jiti.mjs", import.meta.url).href;
  69. return /*js*/ `import { createJiti as __createJiti__ } from ${JSON.stringify(_jitiPath)};async function _module(exports, require, module, __filename, __dirname, jitiImport) { ${source}\n};
  70. // GENERATED BY JITI ESM LOADER
  71. const filename = ${JSON.stringify(filename)};
  72. const dirname = ${JSON.stringify(dirname(filename))};
  73. const jiti = __createJiti__(filename);
  74. const module = { exports: Object.create(null) };
  75. await _module(module.exports, jiti, module, filename, dirname, jiti.import);
  76. if (module.exports && module.exports.__JITI_ERROR__) {
  77. const { filename, line, column, code, message } =
  78. module.exports.__JITI_ERROR__;
  79. const loc = [filename, line, column].join(':');
  80. const err = new Error(code + ": " + message + " " + loc);
  81. Error.captureStackTrace(err, _module);
  82. throw err;
  83. }
  84. export default module.exports;
  85. `;
  86. }
  87. function _shouldSkip(url) {
  88. return (
  89. !jiti ||
  90. url.endsWith(".mjs") ||
  91. url.endsWith(".cjs") ||
  92. (!url.startsWith("./") && !url.startsWith("file://")) ||
  93. isBuiltin(url)
  94. );
  95. }
  96. async function _findClosestPackageJson(dir) {
  97. if (dir === "/") return null;
  98. const packageJsonPath = join(dir, "package.json");
  99. if (existsSync(packageJsonPath)) {
  100. return JSON.parse(await readFile(packageJsonPath, "utf8"));
  101. }
  102. return _findClosestPackageJson(dirname(dir));
  103. }