rolldown-require 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,34 +5,57 @@
5
5
  throw Error('Dynamic require of "' + x + '" is not supported');
6
6
  });
7
7
 
8
- // ../../node_modules/.pnpm/tsup@8.5.0_@swc+core@1.13.19_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_typescript@5.9.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
9
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
8
+ // ../../node_modules/.pnpm/tsup@8.5.1_@swc+core@1.15.3_jiti@2.6.1_postcss@8.5.6_tsx@4.21.0_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/cjs_shims.js
9
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
10
10
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
11
11
 
12
- // src/index.ts
13
- var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
14
- var _promises = require('fs/promises'); var _promises2 = _interopRequireDefault(_promises);
15
- var _module = require('module');
12
+ // src/bundler.ts
16
13
  var _path = require('path'); var _path2 = _interopRequireDefault(_path);
17
- var _process = require('process'); var _process2 = _interopRequireDefault(_process);
18
14
  var _url = require('url');
19
- var _util = require('util');
20
- var _gettsconfig = require('get-tsconfig');
21
15
  var _rolldown = require('rolldown');
22
16
 
23
- // src/packages.ts
24
-
25
-
17
+ // src/collect.ts
18
+ function collectReferencedModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
19
+ if (analyzedModules.has(fileName)) {
20
+ return;
21
+ }
22
+ analyzedModules.add(fileName);
23
+ const chunk = bundle[fileName];
24
+ if (!chunk) {
25
+ return;
26
+ }
27
+ for (const mod of chunk.moduleIds) {
28
+ allModules.add(mod);
29
+ }
30
+ for (const imported of chunk.imports) {
31
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
32
+ }
33
+ for (const imported of chunk.dynamicImports) {
34
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
35
+ }
36
+ }
26
37
 
38
+ // src/externalize.ts
39
+ var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
40
+ var _module = require('module');
27
41
 
28
42
 
29
- // src/utils.ts
30
- var _child_process = require('child_process');
31
43
 
44
+ // src/config.ts
45
+ var configDefaults = Object.freeze({
46
+ resolve: {
47
+ extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
48
+ }
49
+ });
50
+ var defaultGetOutputFile = (filepath, _format) => {
51
+ return filepath;
52
+ };
32
53
 
54
+ // src/plugins/resolve.ts
33
55
 
34
56
 
35
- var _pluginutils = require('@rollup/pluginutils');
57
+ var _mlly = require('mlly');
58
+ var _resolveexports = require('resolve.exports');
36
59
 
37
60
  // src/constants.ts
38
61
 
@@ -43,6 +66,27 @@ var DEV_PROD_CONDITION = `development|production`;
43
66
  var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
44
67
  var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
45
68
 
69
+ // src/external.ts
70
+
71
+ function canExternalizeFile(filePath) {
72
+ const ext = _path2.default.extname(filePath);
73
+ return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
74
+ }
75
+
76
+ // src/packages.ts
77
+
78
+
79
+
80
+ var _process = require('process'); var _process2 = _interopRequireDefault(_process);
81
+
82
+ // src/utils.ts
83
+ var _child_process = require('child_process');
84
+
85
+
86
+
87
+
88
+ var _pluginutils = require('@rollup/pluginutils');
89
+
46
90
  // src/sharedUtils.ts
47
91
 
48
92
  var isWindows = typeof _process2.default !== "undefined" && _process2.default.platform === "win32";
@@ -54,9 +98,9 @@ var postfixRE = /[?#].*$/;
54
98
  function cleanUrl(url) {
55
99
  return url.replace(postfixRE, "");
56
100
  }
57
- function splitFileAndPostfix(path6) {
58
- const file = cleanUrl(path6);
59
- return { file, postfix: path6.slice(file.length) };
101
+ function splitFileAndPostfix(path11) {
102
+ const file = cleanUrl(path11);
103
+ return { file, postfix: path11.slice(file.length) };
60
104
  }
61
105
 
62
106
  // src/utils.ts
@@ -146,8 +190,8 @@ function safeRealpathSync(filePath) {
146
190
  return currentSafeRealpathSync(filePath);
147
191
  }
148
192
  var windowsNetworkMap = /* @__PURE__ */ new Map();
149
- function windowsMappedRealpathSync(path6) {
150
- const realPath = _fs2.default.realpathSync.native(path6);
193
+ function windowsMappedRealpathSync(path11) {
194
+ const realPath = _fs2.default.realpathSync.native(path11);
151
195
  if (realPath.startsWith("\\\\")) {
152
196
  for (const [network, volume] of windowsNetworkMap) {
153
197
  if (realPath.startsWith(network)) {
@@ -159,12 +203,12 @@ function windowsMappedRealpathSync(path6) {
159
203
  }
160
204
  var parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
161
205
  var firstSafeRealPathSyncRun = false;
162
- function windowsSafeRealPathSync(path6) {
206
+ function windowsSafeRealPathSync(path11) {
163
207
  if (!firstSafeRealPathSyncRun) {
164
208
  optimizeSafeRealPathSync();
165
209
  firstSafeRealPathSyncRun = true;
166
210
  }
167
- return _fs2.default.realpathSync(path6);
211
+ return _fs2.default.realpathSync(path11);
168
212
  }
169
213
  function optimizeSafeRealPathSync() {
170
214
  const nodeVersion = _process2.default.versions.node.split(".").map(Number);
@@ -426,19 +470,6 @@ function traverseBetweenDirs(longerDir, shorterDir, cb) {
426
470
  }
427
471
  }
428
472
 
429
- // src/plugins/resolve.ts
430
-
431
-
432
- var _mlly = require('mlly');
433
- var _resolveexports = require('resolve.exports');
434
-
435
- // src/external.ts
436
-
437
- function canExternalizeFile(filePath) {
438
- const ext = _path2.default.extname(filePath);
439
- return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
440
- }
441
-
442
473
  // src/plugins/resolve.ts
443
474
  var ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
444
475
  var browserExternalId = "__vite-browser-external";
@@ -789,8 +820,8 @@ function mapWithBrowserField(relativePathInPkgDir, map) {
789
820
  }
790
821
  }
791
822
  }
792
- function equalWithoutSuffix(path6, key, suffix) {
793
- return key.endsWith(suffix) && key.slice(0, -suffix.length) === path6;
823
+ function equalWithoutSuffix(path11, key, suffix) {
824
+ return key.endsWith(suffix) && key.slice(0, -suffix.length) === path11;
794
825
  }
795
826
  function tryResolveRealFile(file, preserveSymlinks) {
796
827
  const stat = tryStatSync(file);
@@ -821,214 +852,21 @@ function getRealPath(resolved, preserveSymlinks) {
821
852
  }
822
853
  return normalizePath(resolved);
823
854
  }
824
- function isDirectory(path6) {
825
- const stat = tryStatSync(path6);
855
+ function isDirectory(path11) {
856
+ const stat = tryStatSync(path11);
826
857
  return _nullishCoalesce(_optionalChain([stat, 'optionalAccess', _36 => _36.isDirectory, 'call', _37 => _37()]), () => ( false));
827
858
  }
828
859
 
829
- // src/index.ts
830
- var promisifiedRealpath = _util.promisify.call(void 0, _fs2.default.realpath);
831
- var configDefaults = Object.freeze({
832
- resolve: {
833
- extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
834
- }
835
- });
836
- var defaultGetOutputFile = (filepath, _format) => {
837
- return filepath;
838
- };
839
- var cachedModuleSyncCondition;
840
- var moduleSyncConditionPromise;
841
- async function getModuleSyncConditionEnabled() {
842
- if (cachedModuleSyncCondition !== void 0) {
843
- return cachedModuleSyncCondition;
844
- }
845
- if (!moduleSyncConditionPromise) {
846
- moduleSyncConditionPromise = Promise.resolve().then(() => _interopRequireWildcard(require(
847
- // @ts-ignore
848
- "#module-sync-enabled"
849
- ))).then((mod) => Boolean(_optionalChain([mod, 'optionalAccess', _38 => _38.default]))).catch(() => false).then((result) => {
850
- cachedModuleSyncCondition = result;
851
- return result;
852
- }).finally(() => {
853
- moduleSyncConditionPromise = void 0;
854
- });
855
- }
856
- return moduleSyncConditionPromise;
857
- }
858
- function collectReferencedModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
859
- if (analyzedModules.has(fileName)) {
860
- return;
861
- }
862
- analyzedModules.add(fileName);
863
- const chunk = bundle[fileName];
864
- if (!chunk) {
865
- return;
866
- }
867
- for (const mod of chunk.moduleIds) {
868
- allModules.add(mod);
869
- }
870
- for (const imported of chunk.imports) {
871
- collectReferencedModules(bundle, imported, allModules, analyzedModules);
872
- }
873
- for (const imported of chunk.dynamicImports) {
874
- collectReferencedModules(bundle, imported, allModules, analyzedModules);
875
- }
876
- }
877
- async function bundleFile(fileName, options) {
878
- const { isESM } = options;
879
- const moduleSyncEnabled = await getModuleSyncConditionEnabled();
880
- const dirnameVarName = "__vite_injected_original_dirname";
881
- const filenameVarName = "__vite_injected_original_filename";
882
- const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
883
- const rolldownInputOptions = _optionalChain([options, 'optionalAccess', _39 => _39.rolldownOptions, 'optionalAccess', _40 => _40.input]) || {};
884
- const bundle = await _rolldown.rolldown.call(void 0, {
885
- ...rolldownInputOptions,
886
- input: fileName,
887
- // target: [`node${process.versions.node}`],
888
- platform: "node",
889
- resolve: {
890
- mainFields: ["main"],
891
- tsconfigFilename: options.tsconfig
892
- },
893
- define: {
894
- "__dirname": dirnameVarName,
895
- "__filename": filenameVarName,
896
- "import.meta.url": importMetaUrlVarName,
897
- "import.meta.dirname": dirnameVarName,
898
- "import.meta.filename": filenameVarName
899
- },
900
- // disable treeshake to include files that is not sideeffectful to `moduleIds`
901
- treeshake: false,
902
- plugins: [
903
- createExternalizeDepsPlugin({
904
- entryFile: fileName,
905
- isESM,
906
- moduleSyncEnabled
907
- }),
908
- createFileScopeVariablesPlugin({
909
- dirnameVarName,
910
- filenameVarName,
911
- importMetaUrlVarName
912
- })
913
- ],
914
- external: options.external
915
- // preserveEntrySignatures: 'exports-only'
916
- });
917
- const rolldownOutputOptions = _optionalChain([options, 'optionalAccess', _41 => _41.rolldownOptions, 'optionalAccess', _42 => _42.output]) || {};
918
- const result = await bundle.generate({
919
- ...rolldownOutputOptions,
920
- format: options.format,
921
- sourcemap: false,
922
- // sourcemapPathTransform(relative) {
923
- // return path.resolve(fileName, relative)
924
- // },
925
- // we want to generate a single chunk like esbuild does with `splitting: false`
926
- inlineDynamicImports: true
927
- });
928
- await bundle.close();
929
- const entryChunk = result.output.find(
930
- (chunk) => chunk.type === "chunk" && chunk.isEntry
931
- );
932
- const bundleChunks = Object.fromEntries(
933
- result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : [])
934
- );
935
- const allModules = /* @__PURE__ */ new Set();
936
- collectReferencedModules(bundleChunks, entryChunk.fileName, allModules);
937
- allModules.delete(fileName);
938
- return {
939
- code: entryChunk.code,
940
- dependencies: [...allModules]
941
- };
942
- }
943
- var _require = _module.createRequire.call(void 0, importMetaUrl);
944
- async function loadFromBundledFile(fileName, bundledCode, options) {
945
- const { isESM } = options;
946
- if (isESM) {
947
- let nodeModulesDir = typeof _process2.default.versions.deno === "string" ? void 0 : findNearestNodeModules(_path2.default.dirname(fileName));
948
- if (nodeModulesDir) {
949
- try {
950
- await _promises2.default.mkdir(_path2.default.resolve(nodeModulesDir, ".vite-temp/"), {
951
- recursive: true
952
- });
953
- } catch (e) {
954
- if (e.code === "EACCES") {
955
- nodeModulesDir = void 0;
956
- } else {
957
- throw e;
958
- }
959
- }
960
- }
961
- const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
962
- const tempFileName = nodeModulesDir ? _path2.default.resolve(
963
- nodeModulesDir,
964
- `.vite-temp/${_path2.default.basename(fileName)}.${hash}.${isESM ? "mjs" : "cjs"}`
965
- ) : `${fileName}.${hash}.mjs`;
966
- const getOutputFile = options.getOutputFile || defaultGetOutputFile;
967
- const outfile = getOutputFile(tempFileName, options.format);
968
- await _promises2.default.writeFile(outfile, bundledCode);
969
- let mod;
970
- const req = options.require || dynamicImport;
971
- try {
972
- mod = await req(
973
- options.format === "esm" ? _url.pathToFileURL.call(void 0, outfile).href : outfile,
974
- { format: options.format }
975
- );
976
- return mod;
977
- } finally {
978
- if (!_optionalChain([options, 'optionalAccess', _43 => _43.preserveTemporaryFile])) {
979
- _fs2.default.unlink(outfile, () => {
980
- });
981
- }
982
- }
983
- } else {
984
- const extension = _path2.default.extname(fileName);
985
- const realFileName = await promisifiedRealpath(fileName);
986
- const loaderExt = extension in _require.extensions ? extension : ".js";
987
- const defaultLoader = _require.extensions[loaderExt];
988
- const compileLoader = (module, filename) => {
989
- if (filename === realFileName) {
990
- ;
991
- module._compile(bundledCode, filename);
992
- } else {
993
- defaultLoader(module, filename);
994
- }
995
- };
996
- try {
997
- _require.extensions[loaderExt] = compileLoader;
998
- delete _require.cache[_require.resolve(fileName)];
999
- const raw = _require(fileName);
1000
- return raw.__esModule ? raw.default : raw;
1001
- } finally {
1002
- _require.extensions[loaderExt] = defaultLoader;
1003
- }
1004
- }
1005
- }
1006
- async function bundleRequire(options) {
1007
- const resolvedPath = resolveEntryFilepath(options);
1008
- const isESM = detectModuleType(resolvedPath);
1009
- const internalOptions = createInternalOptions(options, isESM);
1010
- const bundled = await bundleFile(
1011
- resolvedPath,
1012
- internalOptions
1013
- );
1014
- const mod = await loadFromBundledFile(
1015
- resolvedPath,
1016
- bundled.code,
1017
- internalOptions
1018
- );
1019
- return {
1020
- mod,
1021
- dependencies: bundled.dependencies
1022
- };
1023
- }
860
+ // src/externalize.ts
1024
861
  function createExternalizeDepsPlugin({
1025
862
  entryFile,
1026
863
  isESM,
1027
864
  moduleSyncEnabled
1028
865
  }) {
866
+ const entryDir = _path2.default.dirname(entryFile);
1029
867
  const packageCache = /* @__PURE__ */ new Map();
1030
868
  const resolveByViteResolver = (id, importer, isRequire) => {
1031
- return _optionalChain([tryNodeResolve, 'call', _44 => _44(id, importer, {
869
+ return _optionalChain([tryNodeResolve, 'call', _38 => _38(id, importer, {
1032
870
  root: _path2.default.dirname(entryFile),
1033
871
  isBuild: true,
1034
872
  isProduction: true,
@@ -1048,7 +886,7 @@ function createExternalizeDepsPlugin({
1048
886
  packageCache,
1049
887
  isRequire,
1050
888
  builtins: nodeLikeBuiltins
1051
- }), 'optionalAccess', _45 => _45.id]);
889
+ }), 'optionalAccess', _39 => _39.id]);
1052
890
  };
1053
891
  return {
1054
892
  name: "externalize-deps",
@@ -1092,14 +930,212 @@ function createExternalizeDepsPlugin({
1092
930
  if (idFsPath.endsWith(".json")) {
1093
931
  return idFsPath;
1094
932
  }
1095
- if (idFsPath && isImport) {
933
+ const shouldExternalize = shouldExternalizeBareImport(id, importer, entryDir);
934
+ if (idFsPath && isImport && shouldExternalize) {
1096
935
  idFsPath = _url.pathToFileURL.call(void 0, idFsPath).href;
1097
936
  }
1098
- return { id: idFsPath, external: true };
937
+ return { id: idFsPath, external: shouldExternalize };
1099
938
  }
1100
939
  }
1101
940
  };
1102
941
  }
942
+ function shouldExternalizeBareImport(specifier, importer, entryDir) {
943
+ if (!specifier || specifier.startsWith(".") || _path2.default.isAbsolute(specifier)) {
944
+ return false;
945
+ }
946
+ if (isNodeLikeBuiltin(specifier)) {
947
+ return true;
948
+ }
949
+ const importerPath = normalizeImporterPath(importer, entryDir);
950
+ try {
951
+ const containingNodeModules = findContainingNodeModules(
952
+ _module.createRequire.call(void 0, importerPath).resolve(specifier)
953
+ );
954
+ if (containingNodeModules) {
955
+ const ownerDir = _path2.default.dirname(containingNodeModules);
956
+ const ownerInsideEntry = isPathWithinDirectory(entryDir, ownerDir);
957
+ const entryInsideOwner = isPathWithinDirectory(ownerDir, entryDir);
958
+ if (ownerInsideEntry && !entryInsideOwner) {
959
+ return false;
960
+ }
961
+ }
962
+ } catch (e9) {
963
+ }
964
+ if (!canResolveFromEntry(specifier, entryDir)) {
965
+ return false;
966
+ }
967
+ return true;
968
+ }
969
+ function normalizeImporterPath(importer, fallback) {
970
+ if (!importer || importer.startsWith("\0")) {
971
+ return fallback;
972
+ }
973
+ const [withoutQuery] = importer.split("?");
974
+ return withoutQuery || fallback;
975
+ }
976
+ function findContainingNodeModules(filePath) {
977
+ let current = _path2.default.dirname(filePath);
978
+ const { root } = _path2.default.parse(current);
979
+ while (true) {
980
+ if (_path2.default.basename(current) === "node_modules") {
981
+ return current;
982
+ }
983
+ if (current === root) {
984
+ break;
985
+ }
986
+ current = _path2.default.dirname(current);
987
+ }
988
+ }
989
+ function isPathWithinDirectory(parent, child) {
990
+ const relative = _path2.default.relative(parent, child);
991
+ return relative === "" || !relative.startsWith("..") && !_path2.default.isAbsolute(relative);
992
+ }
993
+ function getPackageName(specifier) {
994
+ if (!specifier) {
995
+ return void 0;
996
+ }
997
+ if (specifier.startsWith("@")) {
998
+ const segments = specifier.split("/");
999
+ if (segments.length >= 2) {
1000
+ return `${segments[0]}/${segments[1]}`;
1001
+ }
1002
+ return void 0;
1003
+ }
1004
+ const [name] = specifier.split("/");
1005
+ return name || void 0;
1006
+ }
1007
+ function canResolveFromEntry(specifier, entryDir) {
1008
+ const packageName = getPackageName(specifier);
1009
+ if (!packageName) {
1010
+ return false;
1011
+ }
1012
+ let currentDir = entryDir;
1013
+ while (true) {
1014
+ if (_fs2.default.existsSync(_path2.default.join(currentDir, "node_modules", packageName))) {
1015
+ return true;
1016
+ }
1017
+ const parentDir = _path2.default.dirname(currentDir);
1018
+ if (parentDir === currentDir) {
1019
+ break;
1020
+ }
1021
+ currentDir = parentDir;
1022
+ }
1023
+ return false;
1024
+ }
1025
+
1026
+ // src/module-sync.ts
1027
+ var cachedModuleSyncCondition;
1028
+ var moduleSyncConditionPromise;
1029
+ async function getModuleSyncConditionEnabled() {
1030
+ if (cachedModuleSyncCondition !== void 0) {
1031
+ return cachedModuleSyncCondition;
1032
+ }
1033
+ if (!moduleSyncConditionPromise) {
1034
+ moduleSyncConditionPromise = Promise.resolve().then(() => _interopRequireWildcard(require(
1035
+ // @ts-ignore
1036
+ "#module-sync-enabled"
1037
+ ))).then((mod) => Boolean(_optionalChain([mod, 'optionalAccess', _40 => _40.default]))).catch(() => false).then((result) => {
1038
+ cachedModuleSyncCondition = result;
1039
+ return result;
1040
+ }).finally(() => {
1041
+ moduleSyncConditionPromise = void 0;
1042
+ });
1043
+ }
1044
+ return moduleSyncConditionPromise;
1045
+ }
1046
+
1047
+ // src/bundler.ts
1048
+ async function bundleFile(fileName, options) {
1049
+ const { isESM } = options;
1050
+ const moduleSyncEnabled = await getModuleSyncConditionEnabled();
1051
+ const dirnameVarName = "__vite_injected_original_dirname";
1052
+ const filenameVarName = "__vite_injected_original_filename";
1053
+ const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
1054
+ const rolldownInputOptions = _optionalChain([options, 'optionalAccess', _41 => _41.rolldownOptions, 'optionalAccess', _42 => _42.input]) || {};
1055
+ const {
1056
+ transform: userTransform,
1057
+ resolve: userResolve,
1058
+ ...restRolldownInputOptions
1059
+ } = rolldownInputOptions;
1060
+ const transformDefine = {
1061
+ ..._nullishCoalesce(_optionalChain([userTransform, 'optionalAccess', _43 => _43.define]), () => ( {})),
1062
+ "__dirname": dirnameVarName,
1063
+ "__filename": filenameVarName,
1064
+ "import.meta.url": importMetaUrlVarName,
1065
+ "import.meta.dirname": dirnameVarName,
1066
+ "import.meta.filename": filenameVarName
1067
+ };
1068
+ const transformOptions = {
1069
+ ..._nullishCoalesce(userTransform, () => ( {})),
1070
+ define: transformDefine
1071
+ };
1072
+ const resolveOptions = {
1073
+ ..._nullishCoalesce(userResolve, () => ( {})),
1074
+ mainFields: ["main"],
1075
+ tsconfigFilename: options.tsconfig
1076
+ };
1077
+ const originalConsoleWarn = console.warn;
1078
+ console.warn = (...args) => {
1079
+ const message = typeof args[0] === "string" ? args[0] : "";
1080
+ if (message.includes("resolve.tsconfigFilename") || message.includes("Invalid input options") || message.includes('top-level "define" option is deprecated')) {
1081
+ return;
1082
+ }
1083
+ originalConsoleWarn(...args);
1084
+ };
1085
+ let bundle;
1086
+ try {
1087
+ bundle = await _rolldown.rolldown.call(void 0, {
1088
+ ...restRolldownInputOptions,
1089
+ input: fileName,
1090
+ platform: "node",
1091
+ resolve: resolveOptions,
1092
+ // @ts-ignore
1093
+ define: transformDefine,
1094
+ transform: transformOptions,
1095
+ // disable treeshake to include files that is not sideeffectful to `moduleIds`
1096
+ treeshake: false,
1097
+ plugins: [
1098
+ createExternalizeDepsPlugin({
1099
+ entryFile: fileName,
1100
+ isESM,
1101
+ moduleSyncEnabled
1102
+ }),
1103
+ createFileScopeVariablesPlugin({
1104
+ dirnameVarName,
1105
+ filenameVarName,
1106
+ importMetaUrlVarName
1107
+ })
1108
+ ],
1109
+ external: options.external
1110
+ });
1111
+ } finally {
1112
+ console.warn = originalConsoleWarn;
1113
+ }
1114
+ if (!bundle) {
1115
+ throw new Error("Failed to initialize bundler");
1116
+ }
1117
+ const rolldownOutputOptions = _optionalChain([options, 'optionalAccess', _44 => _44.rolldownOptions, 'optionalAccess', _45 => _45.output]) || {};
1118
+ const result = await bundle.generate({
1119
+ ...rolldownOutputOptions,
1120
+ format: options.format,
1121
+ sourcemap: false,
1122
+ inlineDynamicImports: true
1123
+ });
1124
+ await bundle.close();
1125
+ const entryChunk = result.output.find(
1126
+ (chunk) => chunk.type === "chunk" && chunk.isEntry
1127
+ );
1128
+ const bundleChunks = Object.fromEntries(
1129
+ result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : [])
1130
+ );
1131
+ const allModules = /* @__PURE__ */ new Set();
1132
+ collectReferencedModules(bundleChunks, entryChunk.fileName, allModules);
1133
+ allModules.delete(fileName);
1134
+ return {
1135
+ code: entryChunk.code,
1136
+ dependencies: [...allModules]
1137
+ };
1138
+ }
1103
1139
  function createFileScopeVariablesPlugin({
1104
1140
  dirnameVarName,
1105
1141
  filenameVarName,
@@ -1118,6 +1154,362 @@ function createFileScopeVariablesPlugin({
1118
1154
  }
1119
1155
  };
1120
1156
  }
1157
+
1158
+ // src/loader.ts
1159
+
1160
+
1161
+
1162
+ var _util = require('util');
1163
+
1164
+ // src/cache.ts
1165
+ var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
1166
+
1167
+ var _promises = require('fs/promises'); var _promises2 = _interopRequireDefault(_promises);
1168
+
1169
+ var _os = require('os'); var _os2 = _interopRequireDefault(_os);
1170
+
1171
+
1172
+
1173
+ var _require = _module.createRequire.call(void 0, importMetaUrl);
1174
+ var memoryCache = /* @__PURE__ */ new Map();
1175
+ function resolveCacheOptions(fileName, options) {
1176
+ const cacheOpt = options.cache;
1177
+ const enabled = cacheOpt === true || typeof cacheOpt === "object" && cacheOpt.enabled !== false;
1178
+ if (!enabled) {
1179
+ return {
1180
+ enabled: false,
1181
+ key: "",
1182
+ dir: "",
1183
+ reset: false,
1184
+ entryPath: fileName,
1185
+ memory: false,
1186
+ onEvent: void 0
1187
+ };
1188
+ }
1189
+ const dir = typeof cacheOpt === "object" && cacheOpt.dir ? cacheOpt.dir : resolveDefaultCacheDir(fileName);
1190
+ const reset = typeof cacheOpt === "object" && cacheOpt.reset === true;
1191
+ const onEvent = typeof cacheOpt === "object" ? cacheOpt.onEvent : void 0;
1192
+ const memory = !(typeof cacheOpt === "object" && cacheOpt.memory === false);
1193
+ const stat = tryStatSync(fileName);
1194
+ if (!stat) {
1195
+ _optionalChain([onEvent, 'optionalCall', _46 => _46({ type: "skip-invalid", key: "", reason: "missing-entry" })]);
1196
+ return {
1197
+ enabled: false,
1198
+ key: "",
1199
+ dir,
1200
+ reset,
1201
+ entryPath: fileName,
1202
+ memory,
1203
+ onEvent
1204
+ };
1205
+ }
1206
+ const hash = _crypto2.default.createHash("sha1");
1207
+ hash.update(
1208
+ JSON.stringify({
1209
+ entry: _path2.default.resolve(fileName),
1210
+ mtimeMs: stat.mtimeMs,
1211
+ size: stat.size,
1212
+ format: options.format,
1213
+ isESM: options.isESM,
1214
+ tsconfig: _nullishCoalesce(options.tsconfig, () => ( "auto")),
1215
+ node: _process2.default.versions.node,
1216
+ rolldown: hashRolldownOptions(options.rolldownOptions)
1217
+ })
1218
+ );
1219
+ return {
1220
+ enabled: true,
1221
+ key: hash.digest("hex"),
1222
+ dir,
1223
+ reset,
1224
+ entryPath: _path2.default.resolve(fileName),
1225
+ memory,
1226
+ onEvent
1227
+ };
1228
+ }
1229
+ function resolveDefaultCacheDir(fileName) {
1230
+ if (typeof _process2.default.versions.deno !== "string") {
1231
+ const nearest = findNearestNodeModules(_path2.default.dirname(fileName));
1232
+ if (nearest) {
1233
+ return _path2.default.resolve(nearest, ".rolldown-require-cache");
1234
+ }
1235
+ }
1236
+ return _path2.default.join(_os2.default.tmpdir(), "rolldown-require-cache");
1237
+ }
1238
+ async function maybeReadCache(cache, options) {
1239
+ const metaPath = _path2.default.join(cache.dir, `${cache.key}.meta.json`);
1240
+ const mem = cache.memory ? memoryCache.get(cache.key) : void 0;
1241
+ if (_optionalChain([mem, 'optionalAccess', _47 => _47.meta])) {
1242
+ const valid2 = validateMeta(mem.meta, options);
1243
+ if (valid2 === true) {
1244
+ _optionalChain([cache, 'access', _48 => _48.onEvent, 'optionalCall', _49 => _49({ type: "hit", key: cache.key, reason: "memory" })]);
1245
+ return mem;
1246
+ }
1247
+ memoryCache.delete(cache.key);
1248
+ _optionalChain([cache, 'access', _50 => _50.onEvent, 'optionalCall', _51 => _51({ type: "skip-invalid", key: cache.key, reason: valid2 })]);
1249
+ }
1250
+ const meta = await readCacheMeta(metaPath);
1251
+ if (!meta) {
1252
+ return;
1253
+ }
1254
+ const valid = validateMeta(meta, options);
1255
+ if (valid !== true) {
1256
+ _optionalChain([cache, 'access', _52 => _52.onEvent, 'optionalCall', _53 => _53({ type: "skip-invalid", key: cache.key, reason: valid })]);
1257
+ return;
1258
+ }
1259
+ if (_optionalChain([mem, 'optionalAccess', _54 => _54.mod]) !== void 0 && cache.memory) {
1260
+ const enriched = { mod: mem.mod, codePath: meta.codePath, meta };
1261
+ memoryCache.set(cache.key, enriched);
1262
+ _optionalChain([cache, 'access', _55 => _55.onEvent, 'optionalCall', _56 => _56({ type: "hit", key: cache.key, reason: "memory" })]);
1263
+ return enriched;
1264
+ }
1265
+ return { codePath: meta.codePath, meta };
1266
+ }
1267
+ async function importCachedCode(cached, options) {
1268
+ if (cached.mod !== void 0) {
1269
+ return cached.mod;
1270
+ }
1271
+ const target = options.format === "esm" ? _url.pathToFileURL.call(void 0, cached.codePath).href : cached.codePath;
1272
+ if (options.require) {
1273
+ return options.require(target, { format: options.format });
1274
+ }
1275
+ if (options.format === "esm") {
1276
+ return Promise.resolve().then(() => _interopRequireWildcard(require(target)));
1277
+ }
1278
+ return _require(target);
1279
+ }
1280
+ async function storeCacheOutput(cache, code, options, dependencies) {
1281
+ await _promises2.default.mkdir(cache.dir, { recursive: true });
1282
+ const ext = options.format === "cjs" ? "cjs" : "mjs";
1283
+ const codePath = _path2.default.join(cache.dir, `${cache.key}.code.${ext}`);
1284
+ if (cache.reset) {
1285
+ await Promise.allSettled([
1286
+ _promises2.default.rm(codePath, { force: true }),
1287
+ _promises2.default.rm(_path2.default.join(cache.dir, `${cache.key}.meta.json`), { force: true })
1288
+ ]);
1289
+ }
1290
+ await _promises2.default.writeFile(codePath, code);
1291
+ const trackedFiles = collectFileStats([
1292
+ cache.entryPath,
1293
+ ..._nullishCoalesce(dependencies, () => ( []))
1294
+ ]);
1295
+ return {
1296
+ outfile: options.format === "esm" ? _url.pathToFileURL.call(void 0, codePath).href : codePath,
1297
+ cleanup: async () => {
1298
+ },
1299
+ cacheMeta: {
1300
+ format: options.format,
1301
+ codePath,
1302
+ files: trackedFiles
1303
+ }
1304
+ };
1305
+ }
1306
+ async function writeCacheMeta(cache, meta) {
1307
+ await _promises2.default.mkdir(cache.dir, { recursive: true });
1308
+ await _promises2.default.writeFile(
1309
+ _path2.default.join(cache.dir, `${cache.key}.meta.json`),
1310
+ JSON.stringify(meta)
1311
+ );
1312
+ if (cache.memory) {
1313
+ memoryCache.set(cache.key, { codePath: meta.codePath, meta });
1314
+ }
1315
+ }
1316
+ function collectFileStats(files) {
1317
+ const seen = /* @__PURE__ */ new Set();
1318
+ const stats = [];
1319
+ for (const file of files) {
1320
+ if (!file || seen.has(file)) {
1321
+ continue;
1322
+ }
1323
+ seen.add(file);
1324
+ const stat = tryStatSync(file);
1325
+ if (_optionalChain([stat, 'optionalAccess', _57 => _57.isFile, 'call', _58 => _58()])) {
1326
+ stats.push({
1327
+ path: _path2.default.resolve(file),
1328
+ mtimeMs: stat.mtimeMs,
1329
+ size: stat.size
1330
+ });
1331
+ }
1332
+ }
1333
+ return stats;
1334
+ }
1335
+ function writeMemoryCache(cache, mod, meta) {
1336
+ if (!cache.memory) {
1337
+ return;
1338
+ }
1339
+ memoryCache.set(cache.key, { mod, codePath: meta.codePath, meta });
1340
+ }
1341
+ async function readCacheMeta(metaPath) {
1342
+ try {
1343
+ const raw = await _promises2.default.readFile(metaPath, "utf-8");
1344
+ return JSON.parse(raw);
1345
+ } catch (e10) {
1346
+ }
1347
+ return void 0;
1348
+ }
1349
+ function validateMeta(meta, options) {
1350
+ if (meta.format !== options.format) {
1351
+ return "format-mismatch";
1352
+ }
1353
+ if (!meta.codePath || !_fs2.default.existsSync(meta.codePath)) {
1354
+ return "missing-code";
1355
+ }
1356
+ for (const file of _nullishCoalesce(meta.files, () => ( []))) {
1357
+ const stat = tryStatSync(file.path);
1358
+ if (!stat || stat.mtimeMs !== file.mtimeMs || stat.size !== file.size) {
1359
+ return "stale-deps";
1360
+ }
1361
+ }
1362
+ return true;
1363
+ }
1364
+ function hashRolldownOptions(options) {
1365
+ if (!options) {
1366
+ return "none";
1367
+ }
1368
+ return _crypto2.default.createHash("sha1").update(
1369
+ JSON.stringify(options, (_key, value) => {
1370
+ if (typeof value === "function" || typeof value === "symbol") {
1371
+ return void 0;
1372
+ }
1373
+ return value;
1374
+ })
1375
+ ).digest("hex");
1376
+ }
1377
+
1378
+ // src/temp-output.ts
1379
+ var _buffer = require('buffer');
1380
+
1381
+
1382
+
1383
+
1384
+
1385
+ function sanitizeFilename(name) {
1386
+ return name.replace(/[^\w.-]/g, "_");
1387
+ }
1388
+ async function resolveTempOutputFile(sourceFile, code, options) {
1389
+ const getOutputFile = options.getOutputFile || defaultGetOutputFile;
1390
+ const filenameHint = sanitizeFilename(_path2.default.basename(sourceFile));
1391
+ const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
1392
+ const extension = options.format === "cjs" ? "cjs" : "mjs";
1393
+ const fileName = `${filenameHint}.${hash}.${extension}`;
1394
+ const candidates = [];
1395
+ if (typeof _process2.default.versions.deno !== "string") {
1396
+ const nearest = findNearestNodeModules(_path2.default.dirname(sourceFile));
1397
+ if (nearest) {
1398
+ candidates.push(_path2.default.resolve(nearest, ".rolldown-require"));
1399
+ }
1400
+ }
1401
+ candidates.push(_path2.default.join(_os2.default.tmpdir(), "rolldown-require"));
1402
+ for (const base of candidates) {
1403
+ const target = getOutputFile(_path2.default.join(base, fileName), options.format);
1404
+ try {
1405
+ await _promises2.default.mkdir(_path2.default.dirname(target), { recursive: true });
1406
+ await _promises2.default.writeFile(target, code);
1407
+ const cleanup = async () => {
1408
+ if (options.preserveTemporaryFile) {
1409
+ return;
1410
+ }
1411
+ try {
1412
+ await _promises2.default.unlink(target);
1413
+ } catch (e11) {
1414
+ }
1415
+ };
1416
+ return {
1417
+ outfile: options.format === "esm" ? _url.pathToFileURL.call(void 0, target).href : target,
1418
+ cleanup
1419
+ };
1420
+ } catch (e12) {
1421
+ }
1422
+ }
1423
+ if (options.format === "esm") {
1424
+ const dataUrl = `data:text/javascript;base64,${_buffer.Buffer.from(code).toString("base64")}`;
1425
+ return {
1426
+ outfile: dataUrl,
1427
+ cleanup: async () => {
1428
+ }
1429
+ };
1430
+ }
1431
+ throw new Error("Failed to create temporary output file for bundled code");
1432
+ }
1433
+
1434
+ // src/loader.ts
1435
+ var _require2 = _module.createRequire.call(void 0, importMetaUrl);
1436
+ var promisifiedRealpath = _util.promisify.call(void 0, _fs2.default.realpath);
1437
+ async function loadFromBundledFile(fileName, bundledCode, options, dependencies) {
1438
+ const cacheConfig = resolveCacheOptions(fileName, options);
1439
+ if (cacheConfig.enabled) {
1440
+ const cached = await maybeReadCache(cacheConfig, options);
1441
+ if (cached) {
1442
+ if (!cached.mod) {
1443
+ _optionalChain([cacheConfig, 'access', _59 => _59.onEvent, 'optionalCall', _60 => _60({ type: "hit", key: cacheConfig.key })]);
1444
+ }
1445
+ return importCachedCode(cached, options);
1446
+ }
1447
+ _optionalChain([cacheConfig, 'access', _61 => _61.onEvent, 'optionalCall', _62 => _62({ type: "miss", key: cacheConfig.key })]);
1448
+ }
1449
+ const { isESM } = options;
1450
+ if (isESM) {
1451
+ const tempOutput = cacheConfig.enabled ? await storeCacheOutput(cacheConfig, bundledCode, options, dependencies) : await resolveTempOutputFile(fileName, bundledCode, options);
1452
+ const outfile = _optionalChain([tempOutput, 'optionalAccess', _63 => _63.outfile]);
1453
+ const cleanup = _optionalChain([tempOutput, 'optionalAccess', _64 => _64.cleanup]);
1454
+ let mod;
1455
+ const req = options.require || dynamicImport;
1456
+ try {
1457
+ mod = await req(outfile, { format: options.format });
1458
+ if (cacheConfig.enabled && _optionalChain([tempOutput, 'optionalAccess', _65 => _65.cacheMeta])) {
1459
+ await writeCacheMeta(cacheConfig, tempOutput.cacheMeta);
1460
+ _optionalChain([cacheConfig, 'access', _66 => _66.onEvent, 'optionalCall', _67 => _67({ type: "store", key: cacheConfig.key })]);
1461
+ writeMemoryCache(cacheConfig, mod, tempOutput.cacheMeta);
1462
+ }
1463
+ return mod;
1464
+ } finally {
1465
+ if (!cacheConfig.enabled) {
1466
+ await _optionalChain([cleanup, 'optionalCall', _68 => _68()]);
1467
+ }
1468
+ }
1469
+ } else {
1470
+ const extension = _path2.default.extname(fileName);
1471
+ const realFileName = await promisifiedRealpath(fileName);
1472
+ const loaderExt = extension in _require2.extensions ? extension : ".js";
1473
+ const defaultLoader = _require2.extensions[loaderExt];
1474
+ const compileLoader = (module, filename) => {
1475
+ if (filename === realFileName) {
1476
+ ;
1477
+ module._compile(bundledCode, filename);
1478
+ } else {
1479
+ defaultLoader(module, filename);
1480
+ }
1481
+ };
1482
+ let raw;
1483
+ try {
1484
+ _require2.extensions[loaderExt] = compileLoader;
1485
+ delete _require2.cache[_require2.resolve(fileName)];
1486
+ raw = _require2(fileName);
1487
+ return raw.__esModule ? raw.default : raw;
1488
+ } finally {
1489
+ _require2.extensions[loaderExt] = defaultLoader;
1490
+ if (cacheConfig.enabled && raw !== void 0) {
1491
+ const cachedPath = await storeCacheOutput(
1492
+ cacheConfig,
1493
+ bundledCode,
1494
+ options,
1495
+ dependencies
1496
+ );
1497
+ await writeCacheMeta(cacheConfig, cachedPath.cacheMeta);
1498
+ _optionalChain([cacheConfig, 'access', _69 => _69.onEvent, 'optionalCall', _70 => _70({ type: "store", key: cacheConfig.key })]);
1499
+ writeMemoryCache(
1500
+ cacheConfig,
1501
+ raw.__esModule ? raw.default : raw,
1502
+ cachedPath.cacheMeta
1503
+ );
1504
+ }
1505
+ }
1506
+ }
1507
+ }
1508
+
1509
+ // src/options.ts
1510
+
1511
+
1512
+ var _gettsconfig = require('get-tsconfig');
1121
1513
  function resolveEntryFilepath(options) {
1122
1514
  if (_path2.default.isAbsolute(options.filepath)) {
1123
1515
  return options.filepath;
@@ -1150,7 +1542,28 @@ function resolveTsconfigPath(options) {
1150
1542
  if (typeof options.tsconfig === "string") {
1151
1543
  return options.tsconfig;
1152
1544
  }
1153
- return _nullishCoalesce(_optionalChain([_gettsconfig.getTsconfig.call(void 0, options.cwd, "tsconfig.json"), 'optionalAccess', _46 => _46.path]), () => ( void 0));
1545
+ return _nullishCoalesce(_optionalChain([_gettsconfig.getTsconfig.call(void 0, options.cwd, "tsconfig.json"), 'optionalAccess', _71 => _71.path]), () => ( void 0));
1546
+ }
1547
+
1548
+ // src/index.ts
1549
+ async function bundleRequire(options) {
1550
+ const resolvedPath = resolveEntryFilepath(options);
1551
+ const isESM = detectModuleType(resolvedPath);
1552
+ const internalOptions = createInternalOptions(options, isESM);
1553
+ const bundled = await bundleFile(
1554
+ resolvedPath,
1555
+ internalOptions
1556
+ );
1557
+ const mod = await loadFromBundledFile(
1558
+ resolvedPath,
1559
+ bundled.code,
1560
+ internalOptions,
1561
+ bundled.dependencies
1562
+ );
1563
+ return {
1564
+ mod,
1565
+ dependencies: bundled.dependencies
1566
+ };
1154
1567
  }
1155
1568
 
1156
1569