rolldown-require 1.0.5 → 2.0.0

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.mjs CHANGED
@@ -1,37 +1,81 @@
1
- // src/index.ts
1
+ // src/bundler.ts
2
+ import path6 from "path";
3
+ import { pathToFileURL as pathToFileURL2 } from "url";
4
+ import { rolldown } from "rolldown";
5
+
6
+ // src/collect.ts
7
+ function collectReferencedModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
8
+ if (analyzedModules.has(fileName)) {
9
+ return;
10
+ }
11
+ analyzedModules.add(fileName);
12
+ const chunk = bundle[fileName];
13
+ if (!chunk) {
14
+ return;
15
+ }
16
+ for (const mod of chunk.moduleIds) {
17
+ allModules.add(mod);
18
+ }
19
+ for (const imported of chunk.imports) {
20
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
21
+ }
22
+ for (const imported of chunk.dynamicImports) {
23
+ collectReferencedModules(bundle, imported, allModules, analyzedModules);
24
+ }
25
+ }
26
+
27
+ // src/externalize.ts
2
28
  import fs4 from "fs";
3
- import fsp from "fs/promises";
4
29
  import { createRequire as createRequire3 } from "module";
5
30
  import path5 from "path";
6
- import process4 from "process";
7
31
  import { pathToFileURL } from "url";
8
- import { promisify } from "util";
9
- import { getTsconfig } from "get-tsconfig";
10
- import { rolldown } from "rolldown";
32
+
33
+ // src/config.ts
34
+ var configDefaults = Object.freeze({
35
+ resolve: {
36
+ extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
37
+ }
38
+ });
39
+ var defaultGetOutputFile = (filepath, _format) => {
40
+ return filepath;
41
+ };
42
+
43
+ // src/plugins/resolve.ts
44
+ import fs3 from "fs";
45
+ import path4 from "path";
46
+ import { hasESMSyntax } from "mlly";
47
+ import { exports, imports } from "resolve.exports";
48
+
49
+ // src/constants.ts
50
+ import { readFileSync } from "fs";
51
+ var { version } = JSON.parse(
52
+ readFileSync(new URL("../package.json", import.meta.url)).toString()
53
+ );
54
+ var DEV_PROD_CONDITION = `development|production`;
55
+ var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
56
+ var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
57
+
58
+ // src/external.ts
59
+ import path from "path";
60
+ function canExternalizeFile(filePath) {
61
+ const ext = path.extname(filePath);
62
+ return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
63
+ }
11
64
 
12
65
  // src/packages.ts
13
66
  import fs2 from "fs";
14
67
  import { createRequire as createRequire2 } from "module";
15
- import path2 from "path";
68
+ import path3 from "path";
16
69
  import process3 from "process";
17
70
 
18
71
  // src/utils.ts
19
72
  import { exec } from "child_process";
20
73
  import fs from "fs";
21
74
  import { builtinModules, createRequire } from "module";
22
- import path from "path";
75
+ import path2 from "path";
23
76
  import process2 from "process";
24
77
  import { createFilter as _createFilter } from "@rollup/pluginutils";
25
78
 
26
- // src/constants.ts
27
- import { readFileSync } from "fs";
28
- var { version } = JSON.parse(
29
- readFileSync(new URL("../package.json", import.meta.url)).toString()
30
- );
31
- var DEV_PROD_CONDITION = `development|production`;
32
- var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/;
33
- var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/;
34
-
35
79
  // src/sharedUtils.ts
36
80
  import process from "process";
37
81
  var isWindows = typeof process !== "undefined" && process.platform === "win32";
@@ -43,9 +87,9 @@ var postfixRE = /[?#].*$/;
43
87
  function cleanUrl(url) {
44
88
  return url.replace(postfixRE, "");
45
89
  }
46
- function splitFileAndPostfix(path6) {
47
- const file = cleanUrl(path6);
48
- return { file, postfix: path6.slice(file.length) };
90
+ function splitFileAndPostfix(path11) {
91
+ const file = cleanUrl(path11);
92
+ return { file, postfix: path11.slice(file.length) };
49
93
  }
50
94
 
51
95
  // src/utils.ts
@@ -97,7 +141,7 @@ function isOptimizable(id, optimizeDeps) {
97
141
  var bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
98
142
  var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
99
143
  function normalizePath(id) {
100
- return path.posix.normalize(isWindows ? slash(id) : id);
144
+ return path2.posix.normalize(isWindows ? slash(id) : id);
101
145
  }
102
146
  function injectQuery(url, queryToInject) {
103
147
  const { file, postfix } = splitFileAndPostfix(url);
@@ -123,7 +167,7 @@ function isFilePathESM(filePath, packageCache) {
123
167
  return false;
124
168
  } else {
125
169
  try {
126
- const pkg = findNearestPackageData(path.dirname(filePath), packageCache);
170
+ const pkg = findNearestPackageData(path2.dirname(filePath), packageCache);
127
171
  return pkg?.data.type === "module";
128
172
  } catch {
129
173
  return false;
@@ -135,8 +179,8 @@ function safeRealpathSync(filePath) {
135
179
  return currentSafeRealpathSync(filePath);
136
180
  }
137
181
  var windowsNetworkMap = /* @__PURE__ */ new Map();
138
- function windowsMappedRealpathSync(path6) {
139
- const realPath = fs.realpathSync.native(path6);
182
+ function windowsMappedRealpathSync(path11) {
183
+ const realPath = fs.realpathSync.native(path11);
140
184
  if (realPath.startsWith("\\\\")) {
141
185
  for (const [network, volume] of windowsNetworkMap) {
142
186
  if (realPath.startsWith(network)) {
@@ -148,12 +192,12 @@ function windowsMappedRealpathSync(path6) {
148
192
  }
149
193
  var parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
150
194
  var firstSafeRealPathSyncRun = false;
151
- function windowsSafeRealPathSync(path6) {
195
+ function windowsSafeRealPathSync(path11) {
152
196
  if (!firstSafeRealPathSyncRun) {
153
197
  optimizeSafeRealPathSync();
154
198
  firstSafeRealPathSyncRun = true;
155
199
  }
156
- return fs.realpathSync(path6);
200
+ return fs.realpathSync(path11);
157
201
  }
158
202
  function optimizeSafeRealPathSync() {
159
203
  const nodeVersion = process2.versions.node.split(".").map(Number);
@@ -162,7 +206,7 @@ function optimizeSafeRealPathSync() {
162
206
  return;
163
207
  }
164
208
  try {
165
- fs.realpathSync.native(path.resolve("./"));
209
+ fs.realpathSync.native(path2.resolve("./"));
166
210
  } catch (error) {
167
211
  if (error.message.includes("EISDIR: illegal operation on a directory")) {
168
212
  currentSafeRealpathSync = fs.realpathSync;
@@ -226,7 +270,7 @@ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageC
226
270
  if (!pkg) {
227
271
  return null;
228
272
  }
229
- const pkgData = loadPackageData(path2.join(pkg, "package.json"));
273
+ const pkgData = loadPackageData(path3.join(pkg, "package.json"));
230
274
  packageCache?.set(cacheKey, pkgData);
231
275
  return pkgData;
232
276
  } catch {
@@ -247,7 +291,7 @@ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageC
247
291
  return cached;
248
292
  }
249
293
  }
250
- const pkg = path2.join(basedir, "node_modules", pkgName, "package.json");
294
+ const pkg = path3.join(basedir, "node_modules", pkgName, "package.json");
251
295
  try {
252
296
  if (fs2.existsSync(pkg)) {
253
297
  const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
@@ -266,7 +310,7 @@ function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageC
266
310
  }
267
311
  } catch {
268
312
  }
269
- const nextBasedir = path2.dirname(basedir);
313
+ const nextBasedir = path3.dirname(basedir);
270
314
  if (nextBasedir === basedir) {
271
315
  break;
272
316
  }
@@ -283,7 +327,7 @@ function findNearestPackageData(basedir, packageCache) {
283
327
  return cached;
284
328
  }
285
329
  }
286
- const pkgPath = path2.join(basedir, "package.json");
330
+ const pkgPath = path3.join(basedir, "package.json");
287
331
  if (tryStatSync(pkgPath)?.isFile()) {
288
332
  try {
289
333
  const pkgData = loadPackageData(pkgPath);
@@ -294,7 +338,7 @@ function findNearestPackageData(basedir, packageCache) {
294
338
  } catch {
295
339
  }
296
340
  }
297
- const nextBasedir = path2.dirname(basedir);
341
+ const nextBasedir = path3.dirname(basedir);
298
342
  if (nextBasedir === basedir) {
299
343
  break;
300
344
  }
@@ -305,13 +349,13 @@ function findNearestPackageData(basedir, packageCache) {
305
349
  function findNearestMainPackageData(basedir, packageCache) {
306
350
  const nearestPackage = findNearestPackageData(basedir, packageCache);
307
351
  return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(
308
- path2.dirname(nearestPackage.dir),
352
+ path3.dirname(nearestPackage.dir),
309
353
  packageCache
310
354
  ));
311
355
  }
312
356
  function loadPackageData(pkgPath) {
313
357
  const data = JSON.parse(stripBomTag(fs2.readFileSync(pkgPath, "utf-8")));
314
- const pkgDir = normalizePath(path2.dirname(pkgPath));
358
+ const pkgDir = normalizePath(path3.dirname(pkgPath));
315
359
  const { sideEffects } = data;
316
360
  let hasSideEffects;
317
361
  if (typeof sideEffects === "boolean") {
@@ -358,11 +402,11 @@ function getResolveCacheKey(key, options) {
358
402
  }
359
403
  function findNearestNodeModules(basedir) {
360
404
  while (basedir) {
361
- const pkgPath = path2.join(basedir, "node_modules");
405
+ const pkgPath = path3.join(basedir, "node_modules");
362
406
  if (tryStatSync(pkgPath)?.isDirectory()) {
363
407
  return pkgPath;
364
408
  }
365
- const nextBasedir = path2.dirname(basedir);
409
+ const nextBasedir = path3.dirname(basedir);
366
410
  if (nextBasedir === basedir) {
367
411
  break;
368
412
  }
@@ -411,23 +455,10 @@ function getFnpdCacheKey(basedir) {
411
455
  function traverseBetweenDirs(longerDir, shorterDir, cb) {
412
456
  while (longerDir !== shorterDir) {
413
457
  cb(longerDir);
414
- longerDir = path2.dirname(longerDir);
458
+ longerDir = path3.dirname(longerDir);
415
459
  }
416
460
  }
417
461
 
418
- // src/plugins/resolve.ts
419
- import fs3 from "fs";
420
- import path4 from "path";
421
- import { hasESMSyntax } from "mlly";
422
- import { exports, imports } from "resolve.exports";
423
-
424
- // src/external.ts
425
- import path3 from "path";
426
- function canExternalizeFile(filePath) {
427
- const ext = path3.extname(filePath);
428
- return !ext || ext === ".js" || ext === ".mjs" || ext === ".cjs";
429
- }
430
-
431
462
  // src/plugins/resolve.ts
432
463
  var ERR_RESOLVE_PACKAGE_ENTRY_FAIL = "ERR_RESOLVE_PACKAGE_ENTRY_FAIL";
433
464
  var browserExternalId = "__vite-browser-external";
@@ -778,8 +809,8 @@ function mapWithBrowserField(relativePathInPkgDir, map) {
778
809
  }
779
810
  }
780
811
  }
781
- function equalWithoutSuffix(path6, key, suffix) {
782
- return key.endsWith(suffix) && key.slice(0, -suffix.length) === path6;
812
+ function equalWithoutSuffix(path11, key, suffix) {
813
+ return key.endsWith(suffix) && key.slice(0, -suffix.length) === path11;
783
814
  }
784
815
  function tryResolveRealFile(file, preserveSymlinks) {
785
816
  const stat = tryStatSync(file);
@@ -810,21 +841,178 @@ function getRealPath(resolved, preserveSymlinks) {
810
841
  }
811
842
  return normalizePath(resolved);
812
843
  }
813
- function isDirectory(path6) {
814
- const stat = tryStatSync(path6);
844
+ function isDirectory(path11) {
845
+ const stat = tryStatSync(path11);
815
846
  return stat?.isDirectory() ?? false;
816
847
  }
817
848
 
818
- // src/index.ts
819
- var promisifiedRealpath = promisify(fs4.realpath);
820
- var configDefaults = Object.freeze({
821
- resolve: {
822
- extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
849
+ // src/externalize.ts
850
+ function createExternalizeDepsPlugin({
851
+ entryFile,
852
+ isESM,
853
+ moduleSyncEnabled
854
+ }) {
855
+ const entryDir = path5.dirname(entryFile);
856
+ const packageCache = /* @__PURE__ */ new Map();
857
+ const resolveByViteResolver = (id, importer, isRequire) => {
858
+ return tryNodeResolve(id, importer, {
859
+ root: path5.dirname(entryFile),
860
+ isBuild: true,
861
+ isProduction: true,
862
+ preferRelative: false,
863
+ tryIndex: true,
864
+ mainFields: [],
865
+ conditions: [
866
+ "node",
867
+ ...moduleSyncEnabled ? ["module-sync"] : []
868
+ ],
869
+ externalConditions: [],
870
+ external: [],
871
+ noExternal: [],
872
+ dedupe: [],
873
+ extensions: configDefaults.resolve.extensions,
874
+ preserveSymlinks: false,
875
+ packageCache,
876
+ isRequire,
877
+ builtins: nodeLikeBuiltins
878
+ })?.id;
879
+ };
880
+ return {
881
+ name: "externalize-deps",
882
+ resolveId: {
883
+ filter: { id: /^[^.#].*/ },
884
+ async handler(id, importer, { kind }) {
885
+ if (!importer || path5.isAbsolute(id) || isNodeBuiltin(id)) {
886
+ return;
887
+ }
888
+ if (isNodeLikeBuiltin(id)) {
889
+ return { id, external: true };
890
+ }
891
+ const isImport = isESM || kind === "dynamic-import";
892
+ let idFsPath;
893
+ try {
894
+ idFsPath = resolveByViteResolver(id, importer, !isImport);
895
+ } catch (e) {
896
+ if (!isImport) {
897
+ let canResolveWithImport = false;
898
+ try {
899
+ canResolveWithImport = !!resolveByViteResolver(
900
+ id,
901
+ importer,
902
+ false
903
+ );
904
+ } catch {
905
+ }
906
+ if (canResolveWithImport) {
907
+ throw new Error(
908
+ `Failed to resolve ${JSON.stringify(
909
+ id
910
+ )}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`
911
+ );
912
+ }
913
+ }
914
+ throw e;
915
+ }
916
+ if (!idFsPath) {
917
+ return;
918
+ }
919
+ if (idFsPath.endsWith(".json")) {
920
+ return idFsPath;
921
+ }
922
+ const shouldExternalize = shouldExternalizeBareImport(id, importer, entryDir);
923
+ if (idFsPath && isImport && shouldExternalize) {
924
+ idFsPath = pathToFileURL(idFsPath).href;
925
+ }
926
+ return { id: idFsPath, external: shouldExternalize };
927
+ }
928
+ }
929
+ };
930
+ }
931
+ function shouldExternalizeBareImport(specifier, importer, entryDir) {
932
+ if (!specifier || specifier.startsWith(".") || path5.isAbsolute(specifier)) {
933
+ return false;
823
934
  }
824
- });
825
- var defaultGetOutputFile = (filepath, _format) => {
826
- return filepath;
827
- };
935
+ if (isNodeLikeBuiltin(specifier)) {
936
+ return true;
937
+ }
938
+ const importerPath = normalizeImporterPath(importer, entryDir);
939
+ try {
940
+ const containingNodeModules = findContainingNodeModules(
941
+ createRequire3(importerPath).resolve(specifier)
942
+ );
943
+ if (containingNodeModules) {
944
+ const ownerDir = path5.dirname(containingNodeModules);
945
+ const ownerInsideEntry = isPathWithinDirectory(entryDir, ownerDir);
946
+ const entryInsideOwner = isPathWithinDirectory(ownerDir, entryDir);
947
+ if (ownerInsideEntry && !entryInsideOwner) {
948
+ return false;
949
+ }
950
+ }
951
+ } catch {
952
+ }
953
+ if (!canResolveFromEntry(specifier, entryDir)) {
954
+ return false;
955
+ }
956
+ return true;
957
+ }
958
+ function normalizeImporterPath(importer, fallback) {
959
+ if (!importer || importer.startsWith("\0")) {
960
+ return fallback;
961
+ }
962
+ const [withoutQuery] = importer.split("?");
963
+ return withoutQuery || fallback;
964
+ }
965
+ function findContainingNodeModules(filePath) {
966
+ let current = path5.dirname(filePath);
967
+ const { root } = path5.parse(current);
968
+ while (true) {
969
+ if (path5.basename(current) === "node_modules") {
970
+ return current;
971
+ }
972
+ if (current === root) {
973
+ break;
974
+ }
975
+ current = path5.dirname(current);
976
+ }
977
+ }
978
+ function isPathWithinDirectory(parent, child) {
979
+ const relative = path5.relative(parent, child);
980
+ return relative === "" || !relative.startsWith("..") && !path5.isAbsolute(relative);
981
+ }
982
+ function getPackageName(specifier) {
983
+ if (!specifier) {
984
+ return void 0;
985
+ }
986
+ if (specifier.startsWith("@")) {
987
+ const segments = specifier.split("/");
988
+ if (segments.length >= 2) {
989
+ return `${segments[0]}/${segments[1]}`;
990
+ }
991
+ return void 0;
992
+ }
993
+ const [name] = specifier.split("/");
994
+ return name || void 0;
995
+ }
996
+ function canResolveFromEntry(specifier, entryDir) {
997
+ const packageName = getPackageName(specifier);
998
+ if (!packageName) {
999
+ return false;
1000
+ }
1001
+ let currentDir = entryDir;
1002
+ while (true) {
1003
+ if (fs4.existsSync(path5.join(currentDir, "node_modules", packageName))) {
1004
+ return true;
1005
+ }
1006
+ const parentDir = path5.dirname(currentDir);
1007
+ if (parentDir === currentDir) {
1008
+ break;
1009
+ }
1010
+ currentDir = parentDir;
1011
+ }
1012
+ return false;
1013
+ }
1014
+
1015
+ // src/module-sync.ts
828
1016
  var cachedModuleSyncCondition;
829
1017
  var moduleSyncConditionPromise;
830
1018
  async function getModuleSyncConditionEnabled() {
@@ -844,25 +1032,8 @@ async function getModuleSyncConditionEnabled() {
844
1032
  }
845
1033
  return moduleSyncConditionPromise;
846
1034
  }
847
- function collectReferencedModules(bundle, fileName, allModules, analyzedModules = /* @__PURE__ */ new Set()) {
848
- if (analyzedModules.has(fileName)) {
849
- return;
850
- }
851
- analyzedModules.add(fileName);
852
- const chunk = bundle[fileName];
853
- if (!chunk) {
854
- return;
855
- }
856
- for (const mod of chunk.moduleIds) {
857
- allModules.add(mod);
858
- }
859
- for (const imported of chunk.imports) {
860
- collectReferencedModules(bundle, imported, allModules, analyzedModules);
861
- }
862
- for (const imported of chunk.dynamicImports) {
863
- collectReferencedModules(bundle, imported, allModules, analyzedModules);
864
- }
865
- }
1035
+
1036
+ // src/bundler.ts
866
1037
  async function bundleFile(fileName, options) {
867
1038
  const { isESM } = options;
868
1039
  const moduleSyncEnabled = await getModuleSyncConditionEnabled();
@@ -905,9 +1076,9 @@ async function bundleFile(fileName, options) {
905
1076
  bundle = await rolldown({
906
1077
  ...restRolldownInputOptions,
907
1078
  input: fileName,
908
- // target: [`node${process.versions.node}`],
909
1079
  platform: "node",
910
1080
  resolve: resolveOptions,
1081
+ // @ts-ignore
911
1082
  define: transformDefine,
912
1083
  transform: transformOptions,
913
1084
  // disable treeshake to include files that is not sideeffectful to `moduleIds`
@@ -925,7 +1096,6 @@ async function bundleFile(fileName, options) {
925
1096
  })
926
1097
  ],
927
1098
  external: options.external
928
- // preserveEntrySignatures: 'exports-only'
929
1099
  });
930
1100
  } finally {
931
1101
  console.warn = originalConsoleWarn;
@@ -938,10 +1108,6 @@ async function bundleFile(fileName, options) {
938
1108
  ...rolldownOutputOptions,
939
1109
  format: options.format,
940
1110
  sourcemap: false,
941
- // sourcemapPathTransform(relative) {
942
- // return path.resolve(fileName, relative)
943
- // },
944
- // we want to generate a single chunk like esbuild does with `splitting: false`
945
1111
  inlineDynamicImports: true
946
1112
  });
947
1113
  await bundle.close();
@@ -959,51 +1125,341 @@ async function bundleFile(fileName, options) {
959
1125
  dependencies: [...allModules]
960
1126
  };
961
1127
  }
962
- var _require = createRequire3(import.meta.url);
963
- async function loadFromBundledFile(fileName, bundledCode, options) {
964
- const { isESM } = options;
965
- if (isESM) {
966
- let nodeModulesDir = typeof process4.versions.deno === "string" ? void 0 : findNearestNodeModules(path5.dirname(fileName));
967
- if (nodeModulesDir) {
968
- try {
969
- await fsp.mkdir(path5.resolve(nodeModulesDir, ".vite-temp/"), {
970
- recursive: true
971
- });
972
- } catch (e) {
973
- if (e.code === "EACCES") {
974
- nodeModulesDir = void 0;
975
- } else {
976
- throw e;
1128
+ function createFileScopeVariablesPlugin({
1129
+ dirnameVarName,
1130
+ filenameVarName,
1131
+ importMetaUrlVarName
1132
+ }) {
1133
+ return {
1134
+ name: "inject-file-scope-variables",
1135
+ transform: {
1136
+ filter: { id: /\.[cm]?[jt]s$/ },
1137
+ async handler(code, id) {
1138
+ const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path6.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
1139
+ pathToFileURL2(id).href
1140
+ )};`;
1141
+ return { code: injectValues + code, map: null };
1142
+ }
1143
+ }
1144
+ };
1145
+ }
1146
+
1147
+ // src/loader.ts
1148
+ import fs6 from "fs";
1149
+ import { createRequire as createRequire5 } from "module";
1150
+ import path9 from "path";
1151
+ import { promisify } from "util";
1152
+
1153
+ // src/cache.ts
1154
+ import crypto from "crypto";
1155
+ import fs5 from "fs";
1156
+ import fsp from "fs/promises";
1157
+ import { createRequire as createRequire4 } from "module";
1158
+ import os from "os";
1159
+ import path7 from "path";
1160
+ import process4 from "process";
1161
+ import { pathToFileURL as pathToFileURL3 } from "url";
1162
+ var _require = createRequire4(import.meta.url);
1163
+ var memoryCache = /* @__PURE__ */ new Map();
1164
+ function resolveCacheOptions(fileName, options) {
1165
+ const cacheOpt = options.cache;
1166
+ const enabled = cacheOpt === true || typeof cacheOpt === "object" && cacheOpt.enabled !== false;
1167
+ if (!enabled) {
1168
+ return {
1169
+ enabled: false,
1170
+ key: "",
1171
+ dir: "",
1172
+ reset: false,
1173
+ entryPath: fileName,
1174
+ memory: false,
1175
+ onEvent: void 0
1176
+ };
1177
+ }
1178
+ const dir = typeof cacheOpt === "object" && cacheOpt.dir ? cacheOpt.dir : resolveDefaultCacheDir(fileName);
1179
+ const reset = typeof cacheOpt === "object" && cacheOpt.reset === true;
1180
+ const onEvent = typeof cacheOpt === "object" ? cacheOpt.onEvent : void 0;
1181
+ const memory = !(typeof cacheOpt === "object" && cacheOpt.memory === false);
1182
+ const stat = tryStatSync(fileName);
1183
+ if (!stat) {
1184
+ onEvent?.({ type: "skip-invalid", key: "", reason: "missing-entry" });
1185
+ return {
1186
+ enabled: false,
1187
+ key: "",
1188
+ dir,
1189
+ reset,
1190
+ entryPath: fileName,
1191
+ memory,
1192
+ onEvent
1193
+ };
1194
+ }
1195
+ const hash = crypto.createHash("sha1");
1196
+ hash.update(
1197
+ JSON.stringify({
1198
+ entry: path7.resolve(fileName),
1199
+ mtimeMs: stat.mtimeMs,
1200
+ size: stat.size,
1201
+ format: options.format,
1202
+ isESM: options.isESM,
1203
+ tsconfig: options.tsconfig ?? "auto",
1204
+ node: process4.versions.node,
1205
+ rolldown: hashRolldownOptions(options.rolldownOptions)
1206
+ })
1207
+ );
1208
+ return {
1209
+ enabled: true,
1210
+ key: hash.digest("hex"),
1211
+ dir,
1212
+ reset,
1213
+ entryPath: path7.resolve(fileName),
1214
+ memory,
1215
+ onEvent
1216
+ };
1217
+ }
1218
+ function resolveDefaultCacheDir(fileName) {
1219
+ if (typeof process4.versions.deno !== "string") {
1220
+ const nearest = findNearestNodeModules(path7.dirname(fileName));
1221
+ if (nearest) {
1222
+ return path7.resolve(nearest, ".rolldown-require-cache");
1223
+ }
1224
+ }
1225
+ return path7.join(os.tmpdir(), "rolldown-require-cache");
1226
+ }
1227
+ async function maybeReadCache(cache, options) {
1228
+ const metaPath = path7.join(cache.dir, `${cache.key}.meta.json`);
1229
+ const mem = cache.memory ? memoryCache.get(cache.key) : void 0;
1230
+ if (mem?.meta) {
1231
+ const valid2 = validateMeta(mem.meta, options);
1232
+ if (valid2 === true) {
1233
+ cache.onEvent?.({ type: "hit", key: cache.key, reason: "memory" });
1234
+ return mem;
1235
+ }
1236
+ memoryCache.delete(cache.key);
1237
+ cache.onEvent?.({ type: "skip-invalid", key: cache.key, reason: valid2 });
1238
+ }
1239
+ const meta = await readCacheMeta(metaPath);
1240
+ if (!meta) {
1241
+ return;
1242
+ }
1243
+ const valid = validateMeta(meta, options);
1244
+ if (valid !== true) {
1245
+ cache.onEvent?.({ type: "skip-invalid", key: cache.key, reason: valid });
1246
+ return;
1247
+ }
1248
+ if (mem?.mod !== void 0 && cache.memory) {
1249
+ const enriched = { mod: mem.mod, codePath: meta.codePath, meta };
1250
+ memoryCache.set(cache.key, enriched);
1251
+ cache.onEvent?.({ type: "hit", key: cache.key, reason: "memory" });
1252
+ return enriched;
1253
+ }
1254
+ return { codePath: meta.codePath, meta };
1255
+ }
1256
+ async function importCachedCode(cached, options) {
1257
+ if (cached.mod !== void 0) {
1258
+ return cached.mod;
1259
+ }
1260
+ const target = options.format === "esm" ? pathToFileURL3(cached.codePath).href : cached.codePath;
1261
+ if (options.require) {
1262
+ return options.require(target, { format: options.format });
1263
+ }
1264
+ if (options.format === "esm") {
1265
+ return import(target);
1266
+ }
1267
+ return _require(target);
1268
+ }
1269
+ async function storeCacheOutput(cache, code, options, dependencies) {
1270
+ await fsp.mkdir(cache.dir, { recursive: true });
1271
+ const ext = options.format === "cjs" ? "cjs" : "mjs";
1272
+ const codePath = path7.join(cache.dir, `${cache.key}.code.${ext}`);
1273
+ if (cache.reset) {
1274
+ await Promise.allSettled([
1275
+ fsp.rm(codePath, { force: true }),
1276
+ fsp.rm(path7.join(cache.dir, `${cache.key}.meta.json`), { force: true })
1277
+ ]);
1278
+ }
1279
+ await fsp.writeFile(codePath, code);
1280
+ const trackedFiles = collectFileStats([
1281
+ cache.entryPath,
1282
+ ...dependencies ?? []
1283
+ ]);
1284
+ return {
1285
+ outfile: options.format === "esm" ? pathToFileURL3(codePath).href : codePath,
1286
+ cleanup: async () => {
1287
+ },
1288
+ cacheMeta: {
1289
+ format: options.format,
1290
+ codePath,
1291
+ files: trackedFiles
1292
+ }
1293
+ };
1294
+ }
1295
+ async function writeCacheMeta(cache, meta) {
1296
+ await fsp.mkdir(cache.dir, { recursive: true });
1297
+ await fsp.writeFile(
1298
+ path7.join(cache.dir, `${cache.key}.meta.json`),
1299
+ JSON.stringify(meta)
1300
+ );
1301
+ if (cache.memory) {
1302
+ memoryCache.set(cache.key, { codePath: meta.codePath, meta });
1303
+ }
1304
+ }
1305
+ function collectFileStats(files) {
1306
+ const seen = /* @__PURE__ */ new Set();
1307
+ const stats = [];
1308
+ for (const file of files) {
1309
+ if (!file || seen.has(file)) {
1310
+ continue;
1311
+ }
1312
+ seen.add(file);
1313
+ const stat = tryStatSync(file);
1314
+ if (stat?.isFile()) {
1315
+ stats.push({
1316
+ path: path7.resolve(file),
1317
+ mtimeMs: stat.mtimeMs,
1318
+ size: stat.size
1319
+ });
1320
+ }
1321
+ }
1322
+ return stats;
1323
+ }
1324
+ function writeMemoryCache(cache, mod, meta) {
1325
+ if (!cache.memory) {
1326
+ return;
1327
+ }
1328
+ memoryCache.set(cache.key, { mod, codePath: meta.codePath, meta });
1329
+ }
1330
+ async function readCacheMeta(metaPath) {
1331
+ try {
1332
+ const raw = await fsp.readFile(metaPath, "utf-8");
1333
+ return JSON.parse(raw);
1334
+ } catch {
1335
+ }
1336
+ return void 0;
1337
+ }
1338
+ function validateMeta(meta, options) {
1339
+ if (meta.format !== options.format) {
1340
+ return "format-mismatch";
1341
+ }
1342
+ if (!meta.codePath || !fs5.existsSync(meta.codePath)) {
1343
+ return "missing-code";
1344
+ }
1345
+ for (const file of meta.files ?? []) {
1346
+ const stat = tryStatSync(file.path);
1347
+ if (!stat || stat.mtimeMs !== file.mtimeMs || stat.size !== file.size) {
1348
+ return "stale-deps";
1349
+ }
1350
+ }
1351
+ return true;
1352
+ }
1353
+ function hashRolldownOptions(options) {
1354
+ if (!options) {
1355
+ return "none";
1356
+ }
1357
+ return crypto.createHash("sha1").update(
1358
+ JSON.stringify(options, (_key, value) => {
1359
+ if (typeof value === "function" || typeof value === "symbol") {
1360
+ return void 0;
1361
+ }
1362
+ return value;
1363
+ })
1364
+ ).digest("hex");
1365
+ }
1366
+
1367
+ // src/temp-output.ts
1368
+ import { Buffer as Buffer2 } from "buffer";
1369
+ import fsp2 from "fs/promises";
1370
+ import os2 from "os";
1371
+ import path8 from "path";
1372
+ import process5 from "process";
1373
+ import { pathToFileURL as pathToFileURL4 } from "url";
1374
+ function sanitizeFilename(name) {
1375
+ return name.replace(/[^\w.-]/g, "_");
1376
+ }
1377
+ async function resolveTempOutputFile(sourceFile, code, options) {
1378
+ const getOutputFile = options.getOutputFile || defaultGetOutputFile;
1379
+ const filenameHint = sanitizeFilename(path8.basename(sourceFile));
1380
+ const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
1381
+ const extension = options.format === "cjs" ? "cjs" : "mjs";
1382
+ const fileName = `${filenameHint}.${hash}.${extension}`;
1383
+ const candidates = [];
1384
+ if (typeof process5.versions.deno !== "string") {
1385
+ const nearest = findNearestNodeModules(path8.dirname(sourceFile));
1386
+ if (nearest) {
1387
+ candidates.push(path8.resolve(nearest, ".rolldown-require"));
1388
+ }
1389
+ }
1390
+ candidates.push(path8.join(os2.tmpdir(), "rolldown-require"));
1391
+ for (const base of candidates) {
1392
+ const target = getOutputFile(path8.join(base, fileName), options.format);
1393
+ try {
1394
+ await fsp2.mkdir(path8.dirname(target), { recursive: true });
1395
+ await fsp2.writeFile(target, code);
1396
+ const cleanup = async () => {
1397
+ if (options.preserveTemporaryFile) {
1398
+ return;
1399
+ }
1400
+ try {
1401
+ await fsp2.unlink(target);
1402
+ } catch {
977
1403
  }
1404
+ };
1405
+ return {
1406
+ outfile: options.format === "esm" ? pathToFileURL4(target).href : target,
1407
+ cleanup
1408
+ };
1409
+ } catch {
1410
+ }
1411
+ }
1412
+ if (options.format === "esm") {
1413
+ const dataUrl = `data:text/javascript;base64,${Buffer2.from(code).toString("base64")}`;
1414
+ return {
1415
+ outfile: dataUrl,
1416
+ cleanup: async () => {
978
1417
  }
1418
+ };
1419
+ }
1420
+ throw new Error("Failed to create temporary output file for bundled code");
1421
+ }
1422
+
1423
+ // src/loader.ts
1424
+ var _require2 = createRequire5(import.meta.url);
1425
+ var promisifiedRealpath = promisify(fs6.realpath);
1426
+ async function loadFromBundledFile(fileName, bundledCode, options, dependencies) {
1427
+ const cacheConfig = resolveCacheOptions(fileName, options);
1428
+ if (cacheConfig.enabled) {
1429
+ const cached = await maybeReadCache(cacheConfig, options);
1430
+ if (cached) {
1431
+ if (!cached.mod) {
1432
+ cacheConfig.onEvent?.({ type: "hit", key: cacheConfig.key });
1433
+ }
1434
+ return importCachedCode(cached, options);
979
1435
  }
980
- const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
981
- const tempFileName = nodeModulesDir ? path5.resolve(
982
- nodeModulesDir,
983
- `.vite-temp/${path5.basename(fileName)}.${hash}.${isESM ? "mjs" : "cjs"}`
984
- ) : `${fileName}.${hash}.mjs`;
985
- const getOutputFile = options.getOutputFile || defaultGetOutputFile;
986
- const outfile = getOutputFile(tempFileName, options.format);
987
- await fsp.writeFile(outfile, bundledCode);
1436
+ cacheConfig.onEvent?.({ type: "miss", key: cacheConfig.key });
1437
+ }
1438
+ const { isESM } = options;
1439
+ if (isESM) {
1440
+ const tempOutput = cacheConfig.enabled ? await storeCacheOutput(cacheConfig, bundledCode, options, dependencies) : await resolveTempOutputFile(fileName, bundledCode, options);
1441
+ const outfile = tempOutput?.outfile;
1442
+ const cleanup = tempOutput?.cleanup;
988
1443
  let mod;
989
1444
  const req = options.require || dynamicImport;
990
1445
  try {
991
- mod = await req(
992
- options.format === "esm" ? pathToFileURL(outfile).href : outfile,
993
- { format: options.format }
994
- );
1446
+ mod = await req(outfile, { format: options.format });
1447
+ if (cacheConfig.enabled && tempOutput?.cacheMeta) {
1448
+ await writeCacheMeta(cacheConfig, tempOutput.cacheMeta);
1449
+ cacheConfig.onEvent?.({ type: "store", key: cacheConfig.key });
1450
+ writeMemoryCache(cacheConfig, mod, tempOutput.cacheMeta);
1451
+ }
995
1452
  return mod;
996
1453
  } finally {
997
- if (!options?.preserveTemporaryFile) {
998
- fs4.unlink(outfile, () => {
999
- });
1454
+ if (!cacheConfig.enabled) {
1455
+ await cleanup?.();
1000
1456
  }
1001
1457
  }
1002
1458
  } else {
1003
- const extension = path5.extname(fileName);
1459
+ const extension = path9.extname(fileName);
1004
1460
  const realFileName = await promisifiedRealpath(fileName);
1005
- const loaderExt = extension in _require.extensions ? extension : ".js";
1006
- const defaultLoader = _require.extensions[loaderExt];
1461
+ const loaderExt = extension in _require2.extensions ? extension : ".js";
1462
+ const defaultLoader = _require2.extensions[loaderExt];
1007
1463
  const compileLoader = (module, filename) => {
1008
1464
  if (filename === realFileName) {
1009
1465
  ;
@@ -1012,140 +1468,46 @@ async function loadFromBundledFile(fileName, bundledCode, options) {
1012
1468
  defaultLoader(module, filename);
1013
1469
  }
1014
1470
  };
1471
+ let raw;
1015
1472
  try {
1016
- _require.extensions[loaderExt] = compileLoader;
1017
- delete _require.cache[_require.resolve(fileName)];
1018
- const raw = _require(fileName);
1473
+ _require2.extensions[loaderExt] = compileLoader;
1474
+ delete _require2.cache[_require2.resolve(fileName)];
1475
+ raw = _require2(fileName);
1019
1476
  return raw.__esModule ? raw.default : raw;
1020
1477
  } finally {
1021
- _require.extensions[loaderExt] = defaultLoader;
1022
- }
1023
- }
1024
- }
1025
- async function bundleRequire(options) {
1026
- const resolvedPath = resolveEntryFilepath(options);
1027
- const isESM = detectModuleType(resolvedPath);
1028
- const internalOptions = createInternalOptions(options, isESM);
1029
- const bundled = await bundleFile(
1030
- resolvedPath,
1031
- internalOptions
1032
- );
1033
- const mod = await loadFromBundledFile(
1034
- resolvedPath,
1035
- bundled.code,
1036
- internalOptions
1037
- );
1038
- return {
1039
- mod,
1040
- dependencies: bundled.dependencies
1041
- };
1042
- }
1043
- function createExternalizeDepsPlugin({
1044
- entryFile,
1045
- isESM,
1046
- moduleSyncEnabled
1047
- }) {
1048
- const packageCache = /* @__PURE__ */ new Map();
1049
- const resolveByViteResolver = (id, importer, isRequire) => {
1050
- return tryNodeResolve(id, importer, {
1051
- root: path5.dirname(entryFile),
1052
- isBuild: true,
1053
- isProduction: true,
1054
- preferRelative: false,
1055
- tryIndex: true,
1056
- mainFields: [],
1057
- conditions: [
1058
- "node",
1059
- ...moduleSyncEnabled ? ["module-sync"] : []
1060
- ],
1061
- externalConditions: [],
1062
- external: [],
1063
- noExternal: [],
1064
- dedupe: [],
1065
- extensions: configDefaults.resolve.extensions,
1066
- preserveSymlinks: false,
1067
- packageCache,
1068
- isRequire,
1069
- builtins: nodeLikeBuiltins
1070
- })?.id;
1071
- };
1072
- return {
1073
- name: "externalize-deps",
1074
- resolveId: {
1075
- filter: { id: /^[^.#].*/ },
1076
- async handler(id, importer, { kind }) {
1077
- if (!importer || path5.isAbsolute(id) || isNodeBuiltin(id)) {
1078
- return;
1079
- }
1080
- if (isNodeLikeBuiltin(id)) {
1081
- return { id, external: true };
1082
- }
1083
- const isImport = isESM || kind === "dynamic-import";
1084
- let idFsPath;
1085
- try {
1086
- idFsPath = resolveByViteResolver(id, importer, !isImport);
1087
- } catch (e) {
1088
- if (!isImport) {
1089
- let canResolveWithImport = false;
1090
- try {
1091
- canResolveWithImport = !!resolveByViteResolver(
1092
- id,
1093
- importer,
1094
- false
1095
- );
1096
- } catch {
1097
- }
1098
- if (canResolveWithImport) {
1099
- throw new Error(
1100
- `Failed to resolve ${JSON.stringify(
1101
- id
1102
- )}. This package is ESM only but it was tried to load by \`require\`. See https://vite.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.`
1103
- );
1104
- }
1105
- }
1106
- throw e;
1107
- }
1108
- if (!idFsPath) {
1109
- return;
1110
- }
1111
- if (idFsPath.endsWith(".json")) {
1112
- return idFsPath;
1113
- }
1114
- if (idFsPath && isImport) {
1115
- idFsPath = pathToFileURL(idFsPath).href;
1116
- }
1117
- return { id: idFsPath, external: true };
1478
+ _require2.extensions[loaderExt] = defaultLoader;
1479
+ if (cacheConfig.enabled && raw !== void 0) {
1480
+ const cachedPath = await storeCacheOutput(
1481
+ cacheConfig,
1482
+ bundledCode,
1483
+ options,
1484
+ dependencies
1485
+ );
1486
+ await writeCacheMeta(cacheConfig, cachedPath.cacheMeta);
1487
+ cacheConfig.onEvent?.({ type: "store", key: cacheConfig.key });
1488
+ writeMemoryCache(
1489
+ cacheConfig,
1490
+ raw.__esModule ? raw.default : raw,
1491
+ cachedPath.cacheMeta
1492
+ );
1118
1493
  }
1119
1494
  }
1120
- };
1121
- }
1122
- function createFileScopeVariablesPlugin({
1123
- dirnameVarName,
1124
- filenameVarName,
1125
- importMetaUrlVarName
1126
- }) {
1127
- return {
1128
- name: "inject-file-scope-variables",
1129
- transform: {
1130
- filter: { id: /\.[cm]?[jt]s$/ },
1131
- async handler(code, id) {
1132
- const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path5.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
1133
- pathToFileURL(id).href
1134
- )};`;
1135
- return { code: injectValues + code, map: null };
1136
- }
1137
- }
1138
- };
1495
+ }
1139
1496
  }
1497
+
1498
+ // src/options.ts
1499
+ import path10 from "path";
1500
+ import process6 from "process";
1501
+ import { getTsconfig } from "get-tsconfig";
1140
1502
  function resolveEntryFilepath(options) {
1141
- if (path5.isAbsolute(options.filepath)) {
1503
+ if (path10.isAbsolute(options.filepath)) {
1142
1504
  return options.filepath;
1143
1505
  }
1144
- const cwd = options.cwd ? path5.resolve(options.cwd) : process4.cwd();
1145
- return path5.resolve(cwd, options.filepath);
1506
+ const cwd = options.cwd ? path10.resolve(options.cwd) : process6.cwd();
1507
+ return path10.resolve(cwd, options.filepath);
1146
1508
  }
1147
1509
  function detectModuleType(resolvedPath) {
1148
- return typeof process4.versions.deno === "string" || isFilePathESM(resolvedPath);
1510
+ return typeof process6.versions.deno === "string" || isFilePathESM(resolvedPath);
1149
1511
  }
1150
1512
  function createInternalOptions(userOptions, isESM) {
1151
1513
  const {
@@ -1171,6 +1533,27 @@ function resolveTsconfigPath(options) {
1171
1533
  }
1172
1534
  return getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
1173
1535
  }
1536
+
1537
+ // src/index.ts
1538
+ async function bundleRequire(options) {
1539
+ const resolvedPath = resolveEntryFilepath(options);
1540
+ const isESM = detectModuleType(resolvedPath);
1541
+ const internalOptions = createInternalOptions(options, isESM);
1542
+ const bundled = await bundleFile(
1543
+ resolvedPath,
1544
+ internalOptions
1545
+ );
1546
+ const mod = await loadFromBundledFile(
1547
+ resolvedPath,
1548
+ bundled.code,
1549
+ internalOptions,
1550
+ bundled.dependencies
1551
+ );
1552
+ return {
1553
+ mod,
1554
+ dependencies: bundled.dependencies
1555
+ };
1556
+ }
1174
1557
  export {
1175
1558
  bundleFile,
1176
1559
  bundleRequire,