rolldown-require 2.0.6 → 2.0.8

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,1097 +1,845 @@
1
- // src/bundler.ts
2
- import path4 from "path";
3
- import { pathToFileURL as pathToFileURL2 } from "url";
1
+ import { builtinModules, createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { rolldown } from "rolldown";
5
-
6
- // src/collect.ts
5
+ import fs, { readFileSync } from "node:fs";
6
+ import "node:child_process";
7
+ import process from "node:process";
8
+ import { createFilter } from "@rollup/pluginutils";
9
+ import crypto from "node:crypto";
10
+ import fsp from "node:fs/promises";
11
+ import os from "node:os";
12
+ import { promisify } from "node:util";
13
+ import { Buffer as Buffer$1 } from "node:buffer";
14
+ import { getTsconfig } from "get-tsconfig";
15
+ //#region \0rolldown/runtime.js
16
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
17
+ //#endregion
18
+ //#region src/collect.ts
19
+ /**
20
+ * 从 `fileName` 起遍历 chunk 图并收集所有引用的模块 id。
21
+ * Rolldown 在 `inlineDynamicImports` 为 true 时会内联动态导入,
22
+ * 因此只需要遍历已输出的 chunk。
23
+ */
7
24
  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
28
- import fs3 from "fs";
29
- import { createRequire as createRequire3 } from "module";
30
- import path3 from "path";
31
- import { fileURLToPath, pathToFileURL } from "url";
32
-
33
- // src/utils.ts
34
- import { exec } from "child_process";
35
- import fs2 from "fs";
36
- import { builtinModules, createRequire as createRequire2 } from "module";
37
- import path2 from "path";
38
- import process3 from "process";
39
- import { createFilter as _createFilter } from "@rollup/pluginutils";
40
-
41
- // src/constants.ts
42
- import { readFileSync } from "fs";
43
- var { version } = JSON.parse(
44
- readFileSync(new URL("../package.json", import.meta.url)).toString()
45
- );
46
-
47
- // src/packages.ts
48
- import fs from "fs";
49
- import { createRequire } from "module";
50
- import path from "path";
51
- import process from "process";
52
- var pnp;
53
- if (process.versions.pnp) {
54
- try {
55
- pnp = createRequire(import.meta.url)("pnpapi");
56
- } catch {
57
- }
58
- }
25
+ if (analyzedModules.has(fileName)) return;
26
+ analyzedModules.add(fileName);
27
+ const chunk = bundle[fileName];
28
+ if (!chunk) return;
29
+ for (const mod of chunk.moduleIds) allModules.add(mod);
30
+ for (const imported of chunk.imports) collectReferencedModules(bundle, imported, allModules, analyzedModules);
31
+ for (const imported of chunk.dynamicImports) collectReferencedModules(bundle, imported, allModules, analyzedModules);
32
+ }
33
+ //#endregion
34
+ //#region src/constants.ts
35
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url)).toString());
36
+ if (process.versions.pnp) try {
37
+ createRequire(import.meta.url)("pnpapi");
38
+ } catch {}
59
39
  function findNearestPackageData(basedir, packageCache) {
60
- const originalBasedir = basedir;
61
- while (basedir) {
62
- if (packageCache) {
63
- const cached = getFnpdCache(packageCache, basedir, originalBasedir);
64
- if (cached) {
65
- return cached;
66
- }
67
- }
68
- const pkgPath = path.join(basedir, "package.json");
69
- if (tryStatSync(pkgPath)?.isFile()) {
70
- try {
71
- const pkgData = loadPackageData(pkgPath);
72
- if (packageCache) {
73
- setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
74
- }
75
- return pkgData;
76
- } catch {
77
- }
78
- }
79
- const nextBasedir = path.dirname(basedir);
80
- if (nextBasedir === basedir) {
81
- break;
82
- }
83
- basedir = nextBasedir;
84
- }
85
- return null;
40
+ const originalBasedir = basedir;
41
+ while (basedir) {
42
+ if (packageCache) {
43
+ const cached = getFnpdCache(packageCache, basedir, originalBasedir);
44
+ if (cached) return cached;
45
+ }
46
+ const pkgPath = path.join(basedir, "package.json");
47
+ if (tryStatSync(pkgPath)?.isFile()) try {
48
+ const pkgData = loadPackageData(pkgPath);
49
+ if (packageCache) setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
50
+ return pkgData;
51
+ } catch {}
52
+ const nextBasedir = path.dirname(basedir);
53
+ if (nextBasedir === basedir) break;
54
+ basedir = nextBasedir;
55
+ }
56
+ return null;
86
57
  }
87
58
  function loadPackageData(pkgPath) {
88
- const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
89
- const pkgDir = normalizePath(path.dirname(pkgPath));
90
- const { sideEffects } = data;
91
- let hasSideEffects;
92
- if (typeof sideEffects === "boolean") {
93
- hasSideEffects = () => sideEffects;
94
- } else if (Array.isArray(sideEffects)) {
95
- if (sideEffects.length <= 0) {
96
- hasSideEffects = () => false;
97
- } else {
98
- const finalPackageSideEffects = sideEffects.map((sideEffect) => {
99
- if (sideEffect.includes("/")) {
100
- return sideEffect;
101
- }
102
- return `**/${sideEffect}`;
103
- });
104
- hasSideEffects = createFilter(finalPackageSideEffects, null, {
105
- resolve: pkgDir
106
- });
107
- }
108
- } else {
109
- hasSideEffects = () => null;
110
- }
111
- const resolvedCache = {};
112
- const pkg = {
113
- dir: pkgDir,
114
- data,
115
- hasSideEffects,
116
- setResolvedCache(key, entry, options) {
117
- resolvedCache[getResolveCacheKey(key, options)] = entry;
118
- },
119
- getResolvedCache(key, options) {
120
- return resolvedCache[getResolveCacheKey(key, options)];
121
- }
122
- };
123
- return pkg;
59
+ const data = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf-8")));
60
+ const pkgDir = normalizePath(path.dirname(pkgPath));
61
+ const { sideEffects } = data;
62
+ let hasSideEffects;
63
+ if (typeof sideEffects === "boolean") hasSideEffects = () => sideEffects;
64
+ else if (Array.isArray(sideEffects)) if (sideEffects.length <= 0) hasSideEffects = () => false;
65
+ else hasSideEffects = createFilter$1(sideEffects.map((sideEffect) => {
66
+ if (sideEffect.includes("/")) return sideEffect;
67
+ return `**/${sideEffect}`;
68
+ }), null, { resolve: pkgDir });
69
+ else hasSideEffects = () => null;
70
+ const resolvedCache = {};
71
+ return {
72
+ dir: pkgDir,
73
+ data,
74
+ hasSideEffects,
75
+ setResolvedCache(key, entry, options) {
76
+ resolvedCache[getResolveCacheKey(key, options)] = entry;
77
+ },
78
+ getResolvedCache(key, options) {
79
+ return resolvedCache[getResolveCacheKey(key, options)];
80
+ }
81
+ };
124
82
  }
125
83
  function getResolveCacheKey(key, options) {
126
- return [
127
- key,
128
- options.isRequire ? "1" : "0",
129
- options.conditions.join("_"),
130
- options.extensions.join("_"),
131
- options.mainFields.join("_")
132
- ].join("|");
84
+ return [
85
+ key,
86
+ options.isRequire ? "1" : "0",
87
+ options.conditions.join("_"),
88
+ options.extensions.join("_"),
89
+ options.mainFields.join("_")
90
+ ].join("|");
133
91
  }
134
92
  function findNearestNodeModules(basedir) {
135
- while (basedir) {
136
- const pkgPath = path.join(basedir, "node_modules");
137
- if (tryStatSync(pkgPath)?.isDirectory()) {
138
- return pkgPath;
139
- }
140
- const nextBasedir = path.dirname(basedir);
141
- if (nextBasedir === basedir) {
142
- break;
143
- }
144
- basedir = nextBasedir;
145
- }
146
- return null;
147
- }
93
+ while (basedir) {
94
+ const pkgPath = path.join(basedir, "node_modules");
95
+ if (tryStatSync(pkgPath)?.isDirectory()) return pkgPath;
96
+ const nextBasedir = path.dirname(basedir);
97
+ if (nextBasedir === basedir) break;
98
+ basedir = nextBasedir;
99
+ }
100
+ return null;
101
+ }
102
+ /**
103
+ * 根据 `basedir` 获取缓存的 `findNearestPackageData`。
104
+ * 当命中缓存且已遍历 `basedir` 与 `originalBasedir` 之间的路径时,
105
+ * 会把中间目录也写入缓存。
106
+ *
107
+ * 这样共享的 `basedir` 只需要读一次文件系统。
108
+ */
148
109
  function getFnpdCache(packageCache, basedir, originalBasedir) {
149
- const cacheKey = getFnpdCacheKey(basedir);
150
- const pkgData = packageCache.get(cacheKey);
151
- if (pkgData) {
152
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
153
- packageCache.set(getFnpdCacheKey(dir), pkgData);
154
- });
155
- return pkgData;
156
- }
110
+ const cacheKey = getFnpdCacheKey(basedir);
111
+ const pkgData = packageCache.get(cacheKey);
112
+ if (pkgData) {
113
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
114
+ packageCache.set(getFnpdCacheKey(dir), pkgData);
115
+ });
116
+ return pkgData;
117
+ }
157
118
  }
158
119
  function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
159
- packageCache.set(getFnpdCacheKey(basedir), pkgData);
160
- traverseBetweenDirs(originalBasedir, basedir, (dir) => {
161
- packageCache.set(getFnpdCacheKey(dir), pkgData);
162
- });
120
+ packageCache.set(getFnpdCacheKey(basedir), pkgData);
121
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
122
+ packageCache.set(getFnpdCacheKey(dir), pkgData);
123
+ });
163
124
  }
164
125
  function getFnpdCacheKey(basedir) {
165
- return `fnpd_${basedir}`;
126
+ return `fnpd_${basedir}`;
166
127
  }
128
+ /**
129
+ * 在 `longerDir`(含)与 `shorterDir`(不含)之间遍历路径并执行回调。
130
+ * @param longerDir 较长路径,如 `/User/foo/bar/baz`
131
+ * @param shorterDir 较短路径,如 `/User/foo`
132
+ */
167
133
  function traverseBetweenDirs(longerDir, shorterDir, cb) {
168
- while (longerDir !== shorterDir) {
169
- cb(longerDir);
170
- longerDir = path.dirname(longerDir);
171
- }
172
- }
173
-
174
- // src/sharedUtils.ts
175
- import process2 from "process";
176
- var isWindows = typeof process2 !== "undefined" && process2.platform === "win32";
177
- var windowsSlashRE = /\\/g;
134
+ while (longerDir !== shorterDir) {
135
+ cb(longerDir);
136
+ longerDir = path.dirname(longerDir);
137
+ }
138
+ }
139
+ //#endregion
140
+ //#region src/sharedUtils.ts
141
+ const isWindows = typeof process !== "undefined" && process.platform === "win32";
142
+ const windowsSlashRE = /\\/g;
178
143
  function slash(p) {
179
- return p.replace(windowsSlashRE, "/");
180
- }
181
-
182
- // src/utils.ts
183
- var createFilter = _createFilter;
184
- var NODE_BUILTIN_NAMESPACE = "node:";
185
- var NPM_BUILTIN_NAMESPACE = "npm:";
186
- var BUN_BUILTIN_NAMESPACE = "bun:";
187
- var nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
188
- var isBuiltinCache = /* @__PURE__ */ new WeakMap();
144
+ return p.replace(windowsSlashRE, "/");
145
+ }
146
+ //#endregion
147
+ //#region src/utils.ts
148
+ const MJS_MTS_EXT_RE = /\.m[jt]s$/;
149
+ const CJS_CTS_EXT_RE = /\.c[jt]s$/;
150
+ const createFilter$1 = createFilter;
151
+ const NODE_BUILTIN_NAMESPACE = "node:";
152
+ const NPM_BUILTIN_NAMESPACE = "npm:";
153
+ const BUN_BUILTIN_NAMESPACE = "bun:";
154
+ const nodeBuiltins = builtinModules.filter((id) => !id.includes(":"));
155
+ const isBuiltinCache = /* @__PURE__ */ new WeakMap();
189
156
  function isBuiltin(builtins, id) {
190
- let isBuiltin2 = isBuiltinCache.get(builtins);
191
- if (!isBuiltin2) {
192
- isBuiltin2 = createIsBuiltin(builtins);
193
- isBuiltinCache.set(builtins, isBuiltin2);
194
- }
195
- return isBuiltin2(id);
157
+ let isBuiltin = isBuiltinCache.get(builtins);
158
+ if (!isBuiltin) {
159
+ isBuiltin = createIsBuiltin(builtins);
160
+ isBuiltinCache.set(builtins, isBuiltin);
161
+ }
162
+ return isBuiltin(id);
196
163
  }
197
164
  function createIsBuiltin(builtins) {
198
- const plainBuiltinsSet = new Set(
199
- builtins.filter((builtin) => typeof builtin === "string")
200
- );
201
- const regexBuiltins = builtins.filter(
202
- (builtin) => typeof builtin !== "string"
203
- );
204
- return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
205
- }
206
- var nodeLikeBuiltins = [
207
- ...nodeBuiltins,
208
- new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
209
- new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
210
- new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
165
+ const plainBuiltinsSet = new Set(builtins.filter((builtin) => typeof builtin === "string"));
166
+ const regexBuiltins = builtins.filter((builtin) => typeof builtin !== "string");
167
+ return (id) => plainBuiltinsSet.has(id) || regexBuiltins.some((regexp) => regexp.test(id));
168
+ }
169
+ const nodeLikeBuiltins = [
170
+ ...nodeBuiltins,
171
+ new RegExp(`^${NODE_BUILTIN_NAMESPACE}`),
172
+ new RegExp(`^${NPM_BUILTIN_NAMESPACE}`),
173
+ new RegExp(`^${BUN_BUILTIN_NAMESPACE}`)
211
174
  ];
212
175
  function isNodeLikeBuiltin(id) {
213
- return isBuiltin(nodeLikeBuiltins, id);
176
+ return isBuiltin(nodeLikeBuiltins, id);
214
177
  }
215
178
  function isNodeBuiltin(id) {
216
- if (id.startsWith(NODE_BUILTIN_NAMESPACE)) {
217
- return true;
218
- }
219
- return nodeBuiltins.includes(id);
179
+ if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
180
+ return nodeBuiltins.includes(id);
220
181
  }
221
182
  function normalizePath(id) {
222
- return path2.posix.normalize(isWindows ? slash(id) : id);
183
+ return path.posix.normalize(isWindows ? slash(id) : id);
223
184
  }
224
185
  function tryStatSync(file) {
225
- try {
226
- return fs2.statSync(file, { throwIfNoEntry: false });
227
- } catch {
228
- }
186
+ try {
187
+ return fs.statSync(file, { throwIfNoEntry: false });
188
+ } catch {}
229
189
  }
230
190
  function isFilePathESM(filePath, packageCache) {
231
- if (/\.m[jt]s$/.test(filePath)) {
232
- return true;
233
- } else if (/\.c[jt]s$/.test(filePath)) {
234
- return false;
235
- } else {
236
- try {
237
- const pkg = findNearestPackageData(path2.dirname(filePath), packageCache);
238
- return pkg?.data.type === "module";
239
- } catch {
240
- return false;
241
- }
242
- }
243
- }
244
- var currentSafeRealpathSync = isWindows ? windowsSafeRealPathSync : fs2.realpathSync.native;
245
- var windowsNetworkMap = /* @__PURE__ */ new Map();
246
- function windowsMappedRealpathSync(path9) {
247
- const realPath = fs2.realpathSync.native(path9);
248
- if (realPath.startsWith("\\\\")) {
249
- for (const [network, volume] of windowsNetworkMap) {
250
- if (realPath.startsWith(network)) {
251
- return realPath.replace(network, volume);
252
- }
253
- }
254
- }
255
- return realPath;
256
- }
257
- var parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
258
- var firstSafeRealPathSyncRun = false;
259
- function windowsSafeRealPathSync(path9) {
260
- if (!firstSafeRealPathSyncRun) {
261
- optimizeSafeRealPathSync();
262
- firstSafeRealPathSyncRun = true;
263
- }
264
- return fs2.realpathSync(path9);
265
- }
266
- function optimizeSafeRealPathSync() {
267
- const nodeVersion = process3.versions.node.split(".").map(Number);
268
- if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
269
- currentSafeRealpathSync = fs2.realpathSync;
270
- return;
271
- }
272
- try {
273
- fs2.realpathSync.native(path2.resolve("./"));
274
- } catch (error) {
275
- if (error.message.includes("EISDIR: illegal operation on a directory")) {
276
- currentSafeRealpathSync = fs2.realpathSync;
277
- return;
278
- }
279
- }
280
- exec("net use", (error, stdout) => {
281
- if (error) {
282
- return;
283
- }
284
- const lines = stdout.split("\n");
285
- for (const line of lines) {
286
- const m = parseNetUseRE.exec(line);
287
- if (m) {
288
- windowsNetworkMap.set(m[2], m[1]);
289
- }
290
- }
291
- currentSafeRealpathSync = windowsNetworkMap.size === 0 ? fs2.realpathSync.native : windowsMappedRealpathSync;
292
- });
293
- }
191
+ if (MJS_MTS_EXT_RE.test(filePath)) return true;
192
+ else if (CJS_CTS_EXT_RE.test(filePath)) return false;
193
+ else try {
194
+ return findNearestPackageData(path.dirname(filePath), packageCache)?.data.type === "module";
195
+ } catch {
196
+ return false;
197
+ }
198
+ }
199
+ isWindows || fs.realpathSync.native;
294
200
  function stripBomTag(content) {
295
- if (content.charCodeAt(0) === 65279) {
296
- return content.slice(1);
297
- }
298
- return content;
201
+ if (content.charCodeAt(0) === 65279) return content.slice(1);
202
+ return content;
299
203
  }
300
- var dynamicImport = async (id, { format }) => {
301
- const fn = format === "esm" ? (file) => import(file) : true ? createRequire2(import.meta.url) : __require;
302
- return fn(id);
204
+ const dynamicImport = async (id, { format }) => {
205
+ return (format === "esm" ? (file) => import(file) : TSUP_FORMAT === "esm" ? createRequire(import.meta.url) : __require)(id);
303
206
  };
304
-
305
- // src/externalize.ts
306
- function createExternalizeDepsPlugin({
307
- entryFile,
308
- isESM
309
- }) {
310
- const entryDir = path3.dirname(entryFile);
311
- const externalizeCache = /* @__PURE__ */ new Map();
312
- const entryResolveCache = /* @__PURE__ */ new Map();
313
- return {
314
- name: "externalize-deps",
315
- resolveId: {
316
- filter: { id: /^[^.#].*/ },
317
- async handler(id, importer, options) {
318
- const { kind } = options;
319
- if (!importer || path3.isAbsolute(id) || isNodeBuiltin(id)) {
320
- return;
321
- }
322
- if (isNodeLikeBuiltin(id)) {
323
- return { id, external: true };
324
- }
325
- const cacheKey = `${importer}::${kind}::${id}`;
326
- const cached = externalizeCache.get(cacheKey);
327
- if (cached !== void 0) {
328
- return cached ?? void 0;
329
- }
330
- const isImport = isESM || kind === "dynamic-import";
331
- const resolved = await resolveWithRolldown(this, id, importer, kind);
332
- if (!resolved?.id) {
333
- externalizeCache.set(cacheKey, null);
334
- return;
335
- }
336
- if (resolved.external) {
337
- const external = resolved.external === "absolute" ? "absolute" : true;
338
- const result2 = {
339
- id: resolved.id,
340
- external
341
- };
342
- externalizeCache.set(cacheKey, result2);
343
- return result2;
344
- }
345
- const { cleanId, query } = splitIdAndQuery(resolved.id);
346
- const resolvedPath = toFilePath(cleanId);
347
- if (!resolvedPath) {
348
- externalizeCache.set(cacheKey, null);
349
- return;
350
- }
351
- if (!path3.isAbsolute(resolvedPath)) {
352
- externalizeCache.set(cacheKey, null);
353
- return;
354
- }
355
- if (resolvedPath.endsWith(".json")) {
356
- const idWithQuery = resolvedPath + query;
357
- externalizeCache.set(cacheKey, idWithQuery);
358
- return idWithQuery;
359
- }
360
- const shouldExternalize = shouldExternalizeBareImport(
361
- id,
362
- importer,
363
- entryDir,
364
- resolvedPath,
365
- entryResolveCache
366
- );
367
- let idOut = resolvedPath + query;
368
- if (isImport && shouldExternalize) {
369
- idOut = pathToFileURL(resolvedPath).href + query;
370
- }
371
- const result = { id: idOut, external: shouldExternalize };
372
- externalizeCache.set(cacheKey, result);
373
- return result;
374
- }
375
- }
376
- };
207
+ //#endregion
208
+ //#region src/externalize.ts
209
+ const NON_RELATIVE_NON_HASH_RE = /^[^.#].*/;
210
+ function createExternalizeDepsPlugin({ entryFile, isESM }) {
211
+ const entryDir = path.dirname(entryFile);
212
+ const externalizeCache = /* @__PURE__ */ new Map();
213
+ const entryResolveCache = /* @__PURE__ */ new Map();
214
+ return {
215
+ name: "externalize-deps",
216
+ resolveId: {
217
+ filter: { id: NON_RELATIVE_NON_HASH_RE },
218
+ async handler(id, importer, options) {
219
+ const { kind } = options;
220
+ if (!importer || path.isAbsolute(id) || isNodeBuiltin(id)) return;
221
+ if (isNodeLikeBuiltin(id)) return {
222
+ id,
223
+ external: true
224
+ };
225
+ const cacheKey = `${importer}::${kind}::${id}`;
226
+ const cached = externalizeCache.get(cacheKey);
227
+ if (cached !== void 0) return cached ?? void 0;
228
+ const isImport = isESM || kind === "dynamic-import";
229
+ const resolved = await resolveWithRolldown(this, id, importer, kind);
230
+ if (!resolved?.id) {
231
+ externalizeCache.set(cacheKey, null);
232
+ return;
233
+ }
234
+ if (resolved.external) {
235
+ const external = resolved.external === "absolute" ? "absolute" : true;
236
+ const result = {
237
+ id: resolved.id,
238
+ external
239
+ };
240
+ externalizeCache.set(cacheKey, result);
241
+ return result;
242
+ }
243
+ const { cleanId, query } = splitIdAndQuery(resolved.id);
244
+ const resolvedPath = toFilePath(cleanId);
245
+ if (!resolvedPath) {
246
+ externalizeCache.set(cacheKey, null);
247
+ return;
248
+ }
249
+ if (!path.isAbsolute(resolvedPath)) {
250
+ externalizeCache.set(cacheKey, null);
251
+ return;
252
+ }
253
+ if (resolvedPath.endsWith(".json")) {
254
+ const idWithQuery = resolvedPath + query;
255
+ externalizeCache.set(cacheKey, idWithQuery);
256
+ return idWithQuery;
257
+ }
258
+ const shouldExternalize = shouldExternalizeBareImport(id, importer, entryDir, resolvedPath, entryResolveCache);
259
+ let idOut = resolvedPath + query;
260
+ if (isImport && shouldExternalize) idOut = pathToFileURL(resolvedPath).href + query;
261
+ const result = {
262
+ id: idOut,
263
+ external: shouldExternalize
264
+ };
265
+ externalizeCache.set(cacheKey, result);
266
+ return result;
267
+ }
268
+ }
269
+ };
377
270
  }
378
271
  function shouldExternalizeBareImport(specifier, importer, entryDir, resolvedPath, canResolveCache) {
379
- if (!specifier || specifier.startsWith(".") || path3.isAbsolute(specifier)) {
380
- return false;
381
- }
382
- if (isNodeLikeBuiltin(specifier)) {
383
- return true;
384
- }
385
- const importerPath = normalizeImporterPath(importer, entryDir);
386
- const resolvedFromImporter = resolvedPath ?? resolveSpecifierFromImporter(specifier, importerPath);
387
- if (resolvedFromImporter) {
388
- const containingNodeModules = findContainingNodeModules(resolvedFromImporter);
389
- if (containingNodeModules) {
390
- const ownerDir = path3.dirname(containingNodeModules);
391
- const ownerInsideEntry = isPathWithinDirectory(entryDir, ownerDir);
392
- const entryInsideOwner = isPathWithinDirectory(ownerDir, entryDir);
393
- if (ownerInsideEntry && !entryInsideOwner) {
394
- return false;
395
- }
396
- }
397
- }
398
- if (!canResolveFromEntry(specifier, entryDir, canResolveCache)) {
399
- return false;
400
- }
401
- return true;
272
+ if (!specifier || specifier.startsWith(".") || path.isAbsolute(specifier)) return false;
273
+ if (isNodeLikeBuiltin(specifier)) return true;
274
+ const importerPath = normalizeImporterPath(importer, entryDir);
275
+ const resolvedFromImporter = resolvedPath ?? resolveSpecifierFromImporter(specifier, importerPath);
276
+ if (resolvedFromImporter) {
277
+ const containingNodeModules = findContainingNodeModules(resolvedFromImporter);
278
+ if (containingNodeModules) {
279
+ const ownerDir = path.dirname(containingNodeModules);
280
+ const ownerInsideEntry = isPathWithinDirectory(entryDir, ownerDir);
281
+ const entryInsideOwner = isPathWithinDirectory(ownerDir, entryDir);
282
+ if (ownerInsideEntry && !entryInsideOwner) return false;
283
+ }
284
+ }
285
+ if (!canResolveFromEntry(specifier, entryDir, canResolveCache)) return false;
286
+ return true;
402
287
  }
403
288
  function normalizeImporterPath(importer, fallback) {
404
- if (!importer || importer.startsWith("\0")) {
405
- return fallback;
406
- }
407
- const [withoutQuery] = importer.split("?");
408
- return withoutQuery || fallback;
289
+ if (!importer || importer.startsWith("\0")) return fallback;
290
+ const [withoutQuery] = importer.split("?");
291
+ return withoutQuery || fallback;
409
292
  }
410
293
  function findContainingNodeModules(filePath) {
411
- let current = path3.dirname(filePath);
412
- const { root } = path3.parse(current);
413
- while (true) {
414
- if (path3.basename(current) === "node_modules") {
415
- return current;
416
- }
417
- if (current === root) {
418
- break;
419
- }
420
- current = path3.dirname(current);
421
- }
294
+ let current = path.dirname(filePath);
295
+ const { root } = path.parse(current);
296
+ while (true) {
297
+ if (path.basename(current) === "node_modules") return current;
298
+ if (current === root) break;
299
+ current = path.dirname(current);
300
+ }
422
301
  }
423
302
  function isPathWithinDirectory(parent, child) {
424
- const relative = path3.relative(parent, child);
425
- return relative === "" || !relative.startsWith("..") && !path3.isAbsolute(relative);
303
+ const relative = path.relative(parent, child);
304
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
426
305
  }
427
306
  function getPackageName(specifier) {
428
- if (!specifier) {
429
- return void 0;
430
- }
431
- if (specifier.startsWith("@")) {
432
- const segments = specifier.split("/");
433
- if (segments.length >= 2) {
434
- return `${segments[0]}/${segments[1]}`;
435
- }
436
- return void 0;
437
- }
438
- const [name] = specifier.split("/");
439
- return name || void 0;
307
+ if (!specifier) return;
308
+ if (specifier.startsWith("@")) {
309
+ const segments = specifier.split("/");
310
+ if (segments.length >= 2) return `${segments[0]}/${segments[1]}`;
311
+ return;
312
+ }
313
+ const [name] = specifier.split("/");
314
+ return name || void 0;
440
315
  }
441
316
  function canResolveFromEntry(specifier, entryDir, cache) {
442
- const packageName = getPackageName(specifier);
443
- if (!packageName) {
444
- return false;
445
- }
446
- if (cache?.has(packageName)) {
447
- return cache.get(packageName);
448
- }
449
- let currentDir = entryDir;
450
- while (true) {
451
- if (fs3.existsSync(path3.join(currentDir, "node_modules", packageName))) {
452
- cache?.set(packageName, true);
453
- return true;
454
- }
455
- const parentDir = path3.dirname(currentDir);
456
- if (parentDir === currentDir) {
457
- break;
458
- }
459
- currentDir = parentDir;
460
- }
461
- cache?.set(packageName, false);
462
- return false;
317
+ const packageName = getPackageName(specifier);
318
+ if (!packageName) return false;
319
+ if (cache?.has(packageName)) return cache.get(packageName);
320
+ let currentDir = entryDir;
321
+ while (true) {
322
+ if (fs.existsSync(path.join(currentDir, "node_modules", packageName))) {
323
+ cache?.set(packageName, true);
324
+ return true;
325
+ }
326
+ const parentDir = path.dirname(currentDir);
327
+ if (parentDir === currentDir) break;
328
+ currentDir = parentDir;
329
+ }
330
+ cache?.set(packageName, false);
331
+ return false;
463
332
  }
464
333
  function resolveWithRolldown(ctx, id, importer, kind) {
465
- return ctx.resolve(id, importer, { kind, skipSelf: true });
334
+ return ctx.resolve(id, importer, {
335
+ kind,
336
+ skipSelf: true
337
+ });
466
338
  }
467
339
  function splitIdAndQuery(id) {
468
- const [cleanId, rawQuery] = id.split("?");
469
- return { cleanId, query: rawQuery ? `?${rawQuery}` : "" };
340
+ const [cleanId, rawQuery] = id.split("?");
341
+ return {
342
+ cleanId,
343
+ query: rawQuery ? `?${rawQuery}` : ""
344
+ };
470
345
  }
471
346
  function toFilePath(id) {
472
- if (!id) {
473
- return null;
474
- }
475
- if (id.startsWith("file://")) {
476
- return fileURLToPath(id);
477
- }
478
- return id;
347
+ if (!id) return null;
348
+ if (id.startsWith("file://")) return fileURLToPath(id);
349
+ return id;
479
350
  }
480
351
  function resolveSpecifierFromImporter(specifier, importerPath) {
481
- try {
482
- return createRequire3(importerPath).resolve(specifier);
483
- } catch {
484
- return void 0;
485
- }
486
- }
487
-
488
- // src/module-sync.ts
489
- var cachedModuleSyncCondition;
490
- var moduleSyncConditionPromise;
352
+ try {
353
+ return createRequire(importerPath).resolve(specifier);
354
+ } catch {
355
+ return;
356
+ }
357
+ }
358
+ //#endregion
359
+ //#region src/module-sync.ts
360
+ let cachedModuleSyncCondition;
361
+ let moduleSyncConditionPromise;
491
362
  async function getModuleSyncConditionEnabled() {
492
- if (cachedModuleSyncCondition !== void 0) {
493
- return cachedModuleSyncCondition;
494
- }
495
- if (!moduleSyncConditionPromise) {
496
- moduleSyncConditionPromise = import(
497
- // @ts-ignore
498
- "#module-sync-enabled"
499
- ).then((mod) => Boolean(mod?.default)).catch(() => false).then((result) => {
500
- cachedModuleSyncCondition = result;
501
- return result;
502
- }).finally(() => {
503
- moduleSyncConditionPromise = void 0;
504
- });
505
- }
506
- return moduleSyncConditionPromise;
507
- }
508
-
509
- // src/bundler.ts
363
+ if (cachedModuleSyncCondition !== void 0) return cachedModuleSyncCondition;
364
+ if (!moduleSyncConditionPromise) moduleSyncConditionPromise = import("#module-sync-enabled").then((mod) => Boolean(mod?.default)).catch(() => false).then((result) => {
365
+ cachedModuleSyncCondition = result;
366
+ return result;
367
+ }).finally(() => {
368
+ moduleSyncConditionPromise = void 0;
369
+ });
370
+ return moduleSyncConditionPromise;
371
+ }
372
+ //#endregion
373
+ //#region src/bundler.ts
374
+ const JS_TS_EXT_RE = /\.[cm]?[jt]s$/;
510
375
  async function bundleFile(fileName, options) {
511
- const { isESM } = options;
512
- const dirnameVarName = "__vite_injected_original_dirname";
513
- const filenameVarName = "__vite_injected_original_filename";
514
- const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
515
- const rolldownInputOptions = options?.rolldownOptions?.input || {};
516
- const {
517
- transform: userTransform,
518
- resolve: userResolve,
519
- ...restRolldownInputOptions
520
- } = rolldownInputOptions;
521
- const transformDefine = {
522
- ...userTransform?.define ?? {},
523
- "__dirname": dirnameVarName,
524
- "__filename": filenameVarName,
525
- "import.meta.url": importMetaUrlVarName,
526
- "import.meta.dirname": dirnameVarName,
527
- "import.meta.filename": filenameVarName
528
- };
529
- const transformOptions = {
530
- ...userTransform ?? {},
531
- define: transformDefine
532
- };
533
- const moduleSyncEnabled = await getModuleSyncConditionEnabled();
534
- const userConditionNames = userResolve?.conditionNames;
535
- const conditionNames = [...userConditionNames ?? []];
536
- if (moduleSyncEnabled && !conditionNames.includes("module-sync")) {
537
- conditionNames.push("module-sync");
538
- }
539
- const resolveOptions = {
540
- ...userResolve ?? {},
541
- mainFields: ["main"],
542
- ...typeof options.tsconfig === "string" ? { tsconfigFilename: options.tsconfig } : {},
543
- ...conditionNames.length ? { conditionNames } : {}
544
- };
545
- const originalConsoleWarn = console.warn;
546
- console.warn = (...args) => {
547
- const message = typeof args[0] === "string" ? args[0] : "";
548
- if (message.includes("resolve.tsconfigFilename") || message.includes("Invalid input options") || message.includes('top-level "define" option is deprecated')) {
549
- return;
550
- }
551
- originalConsoleWarn(...args);
552
- };
553
- let bundle;
554
- try {
555
- bundle = await rolldown({
556
- ...restRolldownInputOptions,
557
- input: fileName,
558
- platform: "node",
559
- ...options.tsconfig !== void 0 ? { tsconfig: options.tsconfig } : {},
560
- resolve: resolveOptions,
561
- // @ts-ignore
562
- define: transformDefine,
563
- transform: transformOptions,
564
- // disable treeshake to include files that is not sideeffectful to `moduleIds`
565
- treeshake: false,
566
- plugins: [
567
- createExternalizeDepsPlugin({
568
- entryFile: fileName,
569
- isESM
570
- }),
571
- createFileScopeVariablesPlugin({
572
- dirnameVarName,
573
- filenameVarName,
574
- importMetaUrlVarName
575
- })
576
- ],
577
- external: options.external
578
- });
579
- } finally {
580
- console.warn = originalConsoleWarn;
581
- }
582
- if (!bundle) {
583
- throw new Error("Failed to initialize bundler");
584
- }
585
- const rolldownOutputOptions = options?.rolldownOptions?.output || {};
586
- const { codeSplitting: _codeSplitting, ...normalizedOutputOptions } = rolldownOutputOptions;
587
- const result = await bundle.generate({
588
- ...normalizedOutputOptions,
589
- format: options.format,
590
- sourcemap: resolveSourcemapOutput(normalizedOutputOptions.sourcemap, options.sourcemap),
591
- codeSplitting: false
592
- });
593
- await bundle.close();
594
- const entryChunk = result.output.find(
595
- (chunk) => chunk.type === "chunk" && chunk.isEntry
596
- );
597
- const bundleChunks = Object.fromEntries(
598
- result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : [])
599
- );
600
- const allModules = /* @__PURE__ */ new Set();
601
- collectReferencedModules(bundleChunks, entryChunk.fileName, allModules);
602
- allModules.delete(fileName);
603
- return {
604
- code: entryChunk.code,
605
- dependencies: [...allModules]
606
- };
376
+ const { isESM } = options;
377
+ const dirnameVarName = "__vite_injected_original_dirname";
378
+ const filenameVarName = "__vite_injected_original_filename";
379
+ const importMetaUrlVarName = "__vite_injected_original_import_meta_url";
380
+ const { transform: userTransform, resolve: userResolve, ...restRolldownInputOptions } = options?.rolldownOptions?.input || {};
381
+ const transformDefine = {
382
+ ...userTransform?.define ?? {},
383
+ "__dirname": dirnameVarName,
384
+ "__filename": filenameVarName,
385
+ "import.meta.url": importMetaUrlVarName,
386
+ "import.meta.dirname": dirnameVarName,
387
+ "import.meta.filename": filenameVarName
388
+ };
389
+ const transformOptions = {
390
+ ...userTransform ?? {},
391
+ define: transformDefine
392
+ };
393
+ const moduleSyncEnabled = await getModuleSyncConditionEnabled();
394
+ const conditionNames = [...userResolve?.conditionNames ?? []];
395
+ if (moduleSyncEnabled && !conditionNames.includes("module-sync")) conditionNames.push("module-sync");
396
+ const resolveOptions = {
397
+ ...userResolve ?? {},
398
+ mainFields: ["main"],
399
+ ...typeof options.tsconfig === "string" ? { tsconfigFilename: options.tsconfig } : {},
400
+ ...conditionNames.length ? { conditionNames } : {}
401
+ };
402
+ const originalConsoleWarn = console.warn;
403
+ console.warn = (...args) => {
404
+ const message = typeof args[0] === "string" ? args[0] : "";
405
+ if (message.includes("resolve.tsconfigFilename") || message.includes("Invalid input options") || message.includes("top-level \"define\" option is deprecated")) return;
406
+ originalConsoleWarn(...args);
407
+ };
408
+ let bundle;
409
+ try {
410
+ bundle = await rolldown({
411
+ ...restRolldownInputOptions,
412
+ input: fileName,
413
+ platform: "node",
414
+ ...options.tsconfig !== void 0 ? { tsconfig: options.tsconfig } : {},
415
+ resolve: resolveOptions,
416
+ define: transformDefine,
417
+ transform: transformOptions,
418
+ treeshake: false,
419
+ plugins: [createExternalizeDepsPlugin({
420
+ entryFile: fileName,
421
+ isESM
422
+ }), createFileScopeVariablesPlugin({
423
+ dirnameVarName,
424
+ filenameVarName,
425
+ importMetaUrlVarName
426
+ })],
427
+ external: options.external
428
+ });
429
+ } finally {
430
+ console.warn = originalConsoleWarn;
431
+ }
432
+ if (!bundle) throw new Error("Failed to initialize bundler");
433
+ const { codeSplitting: _codeSplitting, ...normalizedOutputOptions } = options?.rolldownOptions?.output || {};
434
+ const result = await bundle.generate({
435
+ ...normalizedOutputOptions,
436
+ format: options.format,
437
+ sourcemap: resolveSourcemapOutput(normalizedOutputOptions.sourcemap, options.sourcemap),
438
+ codeSplitting: false
439
+ });
440
+ await bundle.close();
441
+ const entryChunk = result.output.find((chunk) => chunk.type === "chunk" && chunk.isEntry);
442
+ const bundleChunks = Object.fromEntries(result.output.flatMap((c) => c.type === "chunk" ? [[c.fileName, c]] : []));
443
+ const allModules = /* @__PURE__ */ new Set();
444
+ collectReferencedModules(bundleChunks, entryChunk.fileName, allModules);
445
+ allModules.delete(fileName);
446
+ return {
447
+ code: entryChunk.code,
448
+ dependencies: [...allModules]
449
+ };
607
450
  }
608
451
  function resolveSourcemapOutput(outputSourcemap, requested) {
609
- if (outputSourcemap !== void 0) {
610
- return outputSourcemap;
611
- }
612
- if (requested === true) {
613
- return "inline";
614
- }
615
- return requested ?? false;
616
- }
617
- function createFileScopeVariablesPlugin({
618
- dirnameVarName,
619
- filenameVarName,
620
- importMetaUrlVarName
621
- }) {
622
- return {
623
- name: "inject-file-scope-variables",
624
- transform: {
625
- filter: { id: /\.[cm]?[jt]s$/ },
626
- async handler(code, id) {
627
- const injectValues = `const ${dirnameVarName} = ${JSON.stringify(path4.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(
628
- pathToFileURL2(id).href
629
- )};`;
630
- return { code: injectValues + code, map: null };
631
- }
632
- }
633
- };
634
- }
635
-
636
- // src/cache.ts
637
- import crypto from "crypto";
638
- import fs4 from "fs";
639
- import fsp from "fs/promises";
640
- import { createRequire as createRequire4 } from "module";
641
- import os from "os";
642
- import path5 from "path";
643
- import process4 from "process";
644
- import { pathToFileURL as pathToFileURL3 } from "url";
645
- var _require = createRequire4(import.meta.url);
646
- var memoryCache = /* @__PURE__ */ new Map();
452
+ if (outputSourcemap !== void 0) return outputSourcemap;
453
+ if (requested === true) return "inline";
454
+ return requested ?? false;
455
+ }
456
+ function createFileScopeVariablesPlugin({ dirnameVarName, filenameVarName, importMetaUrlVarName }) {
457
+ return {
458
+ name: "inject-file-scope-variables",
459
+ transform: {
460
+ filter: { id: JS_TS_EXT_RE },
461
+ async handler(code, id) {
462
+ return {
463
+ code: `const ${dirnameVarName} = ${JSON.stringify(path.dirname(id))};const ${filenameVarName} = ${JSON.stringify(id)};const ${importMetaUrlVarName} = ${JSON.stringify(pathToFileURL(id).href)};` + code,
464
+ map: null
465
+ };
466
+ }
467
+ }
468
+ };
469
+ }
470
+ //#endregion
471
+ //#region src/cache.ts
472
+ const _require$1 = createRequire(import.meta.url);
473
+ const memoryCache = /* @__PURE__ */ new Map();
647
474
  function resolveCacheOptions(fileName, options) {
648
- const cacheOpt = options.cache;
649
- const enabled = cacheOpt === true || typeof cacheOpt === "object" && cacheOpt.enabled !== false;
650
- if (!enabled) {
651
- return {
652
- enabled: false,
653
- key: "",
654
- dir: "",
655
- reset: false,
656
- entryPath: fileName,
657
- memory: false,
658
- onEvent: void 0
659
- };
660
- }
661
- const dir = typeof cacheOpt === "object" && cacheOpt.dir ? cacheOpt.dir : resolveDefaultCacheDir(fileName);
662
- const reset = typeof cacheOpt === "object" && cacheOpt.reset === true;
663
- const onEvent = typeof cacheOpt === "object" ? cacheOpt.onEvent : void 0;
664
- const memory = !(typeof cacheOpt === "object" && cacheOpt.memory === false);
665
- const stat = tryStatSync(fileName);
666
- if (!stat) {
667
- onEvent?.({ type: "skip-invalid", key: "", reason: "missing-entry" });
668
- return {
669
- enabled: false,
670
- key: "",
671
- dir,
672
- reset,
673
- entryPath: fileName,
674
- memory,
675
- onEvent
676
- };
677
- }
678
- const hash = crypto.createHash("sha1");
679
- hash.update(
680
- JSON.stringify({
681
- entry: path5.resolve(fileName),
682
- mtimeMs: stat.mtimeMs,
683
- size: stat.size,
684
- format: options.format,
685
- isESM: options.isESM,
686
- tsconfig: options.tsconfig ?? "auto",
687
- node: process4.versions.node,
688
- rolldown: hashRolldownOptions(options.rolldownOptions)
689
- })
690
- );
691
- return {
692
- enabled: true,
693
- key: hash.digest("hex"),
694
- dir,
695
- reset,
696
- entryPath: path5.resolve(fileName),
697
- memory,
698
- onEvent
699
- };
475
+ const cacheOpt = options.cache;
476
+ if (!(cacheOpt === true || typeof cacheOpt === "object" && cacheOpt.enabled !== false)) return {
477
+ enabled: false,
478
+ key: "",
479
+ dir: "",
480
+ reset: false,
481
+ entryPath: fileName,
482
+ memory: false,
483
+ onEvent: void 0
484
+ };
485
+ const dir = typeof cacheOpt === "object" && cacheOpt.dir ? cacheOpt.dir : resolveDefaultCacheDir(fileName);
486
+ const reset = typeof cacheOpt === "object" && cacheOpt.reset === true;
487
+ const onEvent = typeof cacheOpt === "object" ? cacheOpt.onEvent : void 0;
488
+ const memory = !(typeof cacheOpt === "object" && cacheOpt.memory === false);
489
+ const stat = tryStatSync(fileName);
490
+ if (!stat) {
491
+ onEvent?.({
492
+ type: "skip-invalid",
493
+ key: "",
494
+ reason: "missing-entry"
495
+ });
496
+ return {
497
+ enabled: false,
498
+ key: "",
499
+ dir,
500
+ reset,
501
+ entryPath: fileName,
502
+ memory,
503
+ onEvent
504
+ };
505
+ }
506
+ const hash = crypto.createHash("sha1");
507
+ hash.update(JSON.stringify({
508
+ entry: path.resolve(fileName),
509
+ mtimeMs: stat.mtimeMs,
510
+ size: stat.size,
511
+ format: options.format,
512
+ isESM: options.isESM,
513
+ tsconfig: options.tsconfig ?? "auto",
514
+ node: process.versions.node,
515
+ rolldown: hashRolldownOptions(options.rolldownOptions)
516
+ }));
517
+ return {
518
+ enabled: true,
519
+ key: hash.digest("hex"),
520
+ dir,
521
+ reset,
522
+ entryPath: path.resolve(fileName),
523
+ memory,
524
+ onEvent
525
+ };
700
526
  }
701
527
  function resolveDefaultCacheDir(fileName) {
702
- if (typeof process4.versions.deno !== "string") {
703
- const nearest = findNearestNodeModules(path5.dirname(fileName));
704
- if (nearest) {
705
- return path5.resolve(nearest, ".rolldown-require-cache");
706
- }
707
- }
708
- return path5.join(os.tmpdir(), "rolldown-require-cache");
528
+ if (typeof process.versions.deno !== "string") {
529
+ const nearest = findNearestNodeModules(path.dirname(fileName));
530
+ if (nearest) return path.resolve(nearest, ".rolldown-require-cache");
531
+ }
532
+ return path.join(os.tmpdir(), "rolldown-require-cache");
709
533
  }
710
534
  async function maybeReadCache(cache, options) {
711
- const metaPath = path5.join(cache.dir, `${cache.key}.meta.json`);
712
- const mem = cache.memory ? memoryCache.get(cache.key) : void 0;
713
- if (mem?.meta) {
714
- const valid2 = validateMeta(mem.meta, options);
715
- if (valid2 === true) {
716
- cache.onEvent?.({ type: "hit", key: cache.key, reason: "memory" });
717
- return mem;
718
- }
719
- memoryCache.delete(cache.key);
720
- cache.onEvent?.({ type: "skip-invalid", key: cache.key, reason: valid2 });
721
- }
722
- const meta = await readCacheMeta(metaPath);
723
- if (!meta) {
724
- return;
725
- }
726
- const valid = validateMeta(meta, options);
727
- if (valid !== true) {
728
- cache.onEvent?.({ type: "skip-invalid", key: cache.key, reason: valid });
729
- return;
730
- }
731
- if (mem?.mod !== void 0 && cache.memory) {
732
- const enriched = { mod: mem.mod, codePath: meta.codePath, meta };
733
- memoryCache.set(cache.key, enriched);
734
- cache.onEvent?.({ type: "hit", key: cache.key, reason: "memory" });
735
- return enriched;
736
- }
737
- return { codePath: meta.codePath, meta };
535
+ const metaPath = path.join(cache.dir, `${cache.key}.meta.json`);
536
+ const mem = cache.memory ? memoryCache.get(cache.key) : void 0;
537
+ if (mem?.meta) {
538
+ const valid = validateMeta(mem.meta, options);
539
+ if (valid === true) {
540
+ cache.onEvent?.({
541
+ type: "hit",
542
+ key: cache.key,
543
+ reason: "memory"
544
+ });
545
+ return mem;
546
+ }
547
+ memoryCache.delete(cache.key);
548
+ cache.onEvent?.({
549
+ type: "skip-invalid",
550
+ key: cache.key,
551
+ reason: valid
552
+ });
553
+ }
554
+ const meta = await readCacheMeta(metaPath);
555
+ if (!meta) return;
556
+ const valid = validateMeta(meta, options);
557
+ if (valid !== true) {
558
+ cache.onEvent?.({
559
+ type: "skip-invalid",
560
+ key: cache.key,
561
+ reason: valid
562
+ });
563
+ return;
564
+ }
565
+ if (mem?.mod !== void 0 && cache.memory) {
566
+ const enriched = {
567
+ mod: mem.mod,
568
+ codePath: meta.codePath,
569
+ meta
570
+ };
571
+ memoryCache.set(cache.key, enriched);
572
+ cache.onEvent?.({
573
+ type: "hit",
574
+ key: cache.key,
575
+ reason: "memory"
576
+ });
577
+ return enriched;
578
+ }
579
+ return {
580
+ codePath: meta.codePath,
581
+ meta
582
+ };
738
583
  }
739
584
  async function importCachedCode(cached, options) {
740
- if (cached.mod !== void 0) {
741
- return cached.mod;
742
- }
743
- const target = options.format === "esm" ? pathToFileURL3(cached.codePath).href : cached.codePath;
744
- if (options.require) {
745
- return options.require(target, { format: options.format });
746
- }
747
- if (options.format === "esm") {
748
- return import(target);
749
- }
750
- return _require(target);
585
+ if (cached.mod !== void 0) return cached.mod;
586
+ const target = options.format === "esm" ? pathToFileURL(cached.codePath).href : cached.codePath;
587
+ if (options.require) return options.require(target, { format: options.format });
588
+ if (options.format === "esm") return import(target);
589
+ return _require$1(target);
751
590
  }
752
591
  async function storeCacheOutput(cache, code, options, dependencies) {
753
- await fsp.mkdir(cache.dir, { recursive: true });
754
- const ext = options.format === "cjs" ? "cjs" : "mjs";
755
- const codePath = path5.join(cache.dir, `${cache.key}.code.${ext}`);
756
- if (cache.reset) {
757
- await Promise.allSettled([
758
- fsp.rm(codePath, { force: true }),
759
- fsp.rm(path5.join(cache.dir, `${cache.key}.meta.json`), { force: true })
760
- ]);
761
- }
762
- await fsp.writeFile(codePath, code);
763
- const trackedFiles = collectFileStats([
764
- cache.entryPath,
765
- ...dependencies ?? []
766
- ]);
767
- return {
768
- outfile: options.format === "esm" ? pathToFileURL3(codePath).href : codePath,
769
- cleanup: async () => {
770
- },
771
- cacheMeta: {
772
- format: options.format,
773
- codePath,
774
- files: trackedFiles
775
- }
776
- };
592
+ await fsp.mkdir(cache.dir, { recursive: true });
593
+ const ext = options.format === "cjs" ? "cjs" : "mjs";
594
+ const codePath = path.join(cache.dir, `${cache.key}.code.${ext}`);
595
+ if (cache.reset) await Promise.allSettled([fsp.rm(codePath, { force: true }), fsp.rm(path.join(cache.dir, `${cache.key}.meta.json`), { force: true })]);
596
+ await fsp.writeFile(codePath, code);
597
+ const trackedFiles = collectFileStats([cache.entryPath, ...dependencies ?? []]);
598
+ return {
599
+ outfile: options.format === "esm" ? pathToFileURL(codePath).href : codePath,
600
+ cleanup: async () => {},
601
+ cacheMeta: {
602
+ format: options.format,
603
+ codePath,
604
+ files: trackedFiles
605
+ }
606
+ };
777
607
  }
778
608
  async function writeCacheMeta(cache, meta) {
779
- await fsp.mkdir(cache.dir, { recursive: true });
780
- await fsp.writeFile(
781
- path5.join(cache.dir, `${cache.key}.meta.json`),
782
- JSON.stringify(meta)
783
- );
784
- if (cache.memory) {
785
- memoryCache.set(cache.key, { codePath: meta.codePath, meta });
786
- }
609
+ await fsp.mkdir(cache.dir, { recursive: true });
610
+ await fsp.writeFile(path.join(cache.dir, `${cache.key}.meta.json`), JSON.stringify(meta));
611
+ if (cache.memory) memoryCache.set(cache.key, {
612
+ codePath: meta.codePath,
613
+ meta
614
+ });
787
615
  }
788
616
  function collectFileStats(files) {
789
- const seen = /* @__PURE__ */ new Set();
790
- const stats = [];
791
- for (const file of files) {
792
- if (!file || seen.has(file)) {
793
- continue;
794
- }
795
- seen.add(file);
796
- const stat = tryStatSync(file);
797
- if (stat?.isFile()) {
798
- stats.push({
799
- path: path5.resolve(file),
800
- mtimeMs: stat.mtimeMs,
801
- size: stat.size
802
- });
803
- }
804
- }
805
- return stats;
617
+ const seen = /* @__PURE__ */ new Set();
618
+ const stats = [];
619
+ for (const file of files) {
620
+ if (!file || seen.has(file)) continue;
621
+ seen.add(file);
622
+ const stat = tryStatSync(file);
623
+ if (stat?.isFile()) stats.push({
624
+ path: path.resolve(file),
625
+ mtimeMs: stat.mtimeMs,
626
+ size: stat.size
627
+ });
628
+ }
629
+ return stats;
806
630
  }
807
631
  function writeMemoryCache(cache, mod, meta) {
808
- if (!cache.memory) {
809
- return;
810
- }
811
- memoryCache.set(cache.key, { mod, codePath: meta.codePath, meta });
632
+ if (!cache.memory) return;
633
+ memoryCache.set(cache.key, {
634
+ mod,
635
+ codePath: meta.codePath,
636
+ meta
637
+ });
812
638
  }
813
639
  async function readCacheMeta(metaPath) {
814
- try {
815
- const raw = await fsp.readFile(metaPath, "utf-8");
816
- return JSON.parse(raw);
817
- } catch {
818
- }
819
- return void 0;
640
+ try {
641
+ const raw = await fsp.readFile(metaPath, "utf-8");
642
+ return JSON.parse(raw);
643
+ } catch {}
820
644
  }
821
645
  function validateMeta(meta, options) {
822
- if (meta.format !== options.format) {
823
- return "format-mismatch";
824
- }
825
- if (!meta.codePath || !fs4.existsSync(meta.codePath)) {
826
- return "missing-code";
827
- }
828
- for (const file of meta.files ?? []) {
829
- const stat = tryStatSync(file.path);
830
- if (!stat || stat.mtimeMs !== file.mtimeMs || stat.size !== file.size) {
831
- return "stale-deps";
832
- }
833
- }
834
- return true;
646
+ if (meta.format !== options.format) return "format-mismatch";
647
+ if (!meta.codePath || !fs.existsSync(meta.codePath)) return "missing-code";
648
+ for (const file of meta.files ?? []) {
649
+ const stat = tryStatSync(file.path);
650
+ if (!stat || stat.mtimeMs !== file.mtimeMs || stat.size !== file.size) return "stale-deps";
651
+ }
652
+ return true;
835
653
  }
836
654
  function hashRolldownOptions(options) {
837
- if (!options) {
838
- return "none";
839
- }
840
- return crypto.createHash("sha1").update(
841
- JSON.stringify(options, (_key, value) => {
842
- if (typeof value === "function" || typeof value === "symbol") {
843
- return void 0;
844
- }
845
- return value;
846
- })
847
- ).digest("hex");
848
- }
849
-
850
- // src/config.ts
851
- var configDefaults = Object.freeze({
852
- resolve: {
853
- extensions: [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"]
854
- }
855
- });
856
- var defaultGetOutputFile = (filepath, _format) => {
857
- return filepath;
655
+ if (!options) return "none";
656
+ return crypto.createHash("sha1").update(JSON.stringify(options, (_key, value) => {
657
+ if (typeof value === "function" || typeof value === "symbol") return;
658
+ return value;
659
+ })).digest("hex");
660
+ }
661
+ //#endregion
662
+ //#region src/config.ts
663
+ const configDefaults = Object.freeze({ resolve: { extensions: [
664
+ ".mjs",
665
+ ".js",
666
+ ".mts",
667
+ ".ts",
668
+ ".jsx",
669
+ ".tsx",
670
+ ".json"
671
+ ] } });
672
+ const defaultGetOutputFile = (filepath, _format) => {
673
+ return filepath;
858
674
  };
859
-
860
- // src/loader.ts
861
- import fs5 from "fs";
862
- import { createRequire as createRequire5 } from "module";
863
- import path7 from "path";
864
- import { promisify } from "util";
865
-
866
- // src/temp-output.ts
867
- import { Buffer as Buffer2 } from "buffer";
868
- import fsp2 from "fs/promises";
869
- import os2 from "os";
870
- import path6 from "path";
871
- import process5 from "process";
872
- import { pathToFileURL as pathToFileURL4 } from "url";
675
+ //#endregion
676
+ //#region src/temp-output.ts
677
+ const NON_WORD_CHAR_RE = /[^\w.-]/g;
873
678
  function sanitizeFilename(name) {
874
- return name.replace(/[^\w.-]/g, "_");
679
+ return name.replace(NON_WORD_CHAR_RE, "_");
875
680
  }
876
681
  async function resolveTempOutputFile(sourceFile, code, options) {
877
- const getOutputFile = options.getOutputFile || defaultGetOutputFile;
878
- const filenameHint = sanitizeFilename(path6.basename(sourceFile));
879
- const hash = `timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
880
- const extension = options.format === "cjs" ? "cjs" : "mjs";
881
- const fileName = `${filenameHint}.${hash}.${extension}`;
882
- const candidates = [];
883
- if (typeof process5.versions.deno !== "string") {
884
- const nearest = findNearestNodeModules(path6.dirname(sourceFile));
885
- if (nearest) {
886
- candidates.push(path6.resolve(nearest, ".rolldown-require"));
887
- }
888
- }
889
- candidates.push(path6.join(os2.tmpdir(), "rolldown-require"));
890
- for (const base of candidates) {
891
- const target = getOutputFile(path6.join(base, fileName), options.format);
892
- try {
893
- await fsp2.mkdir(path6.dirname(target), { recursive: true });
894
- await fsp2.writeFile(target, code);
895
- const cleanup = async () => {
896
- if (options.preserveTemporaryFile) {
897
- return;
898
- }
899
- try {
900
- await fsp2.unlink(target);
901
- } catch {
902
- }
903
- };
904
- return {
905
- outfile: options.format === "esm" ? pathToFileURL4(target).href : target,
906
- cleanup
907
- };
908
- } catch {
909
- }
910
- }
911
- if (options.format === "esm") {
912
- const dataUrl = `data:text/javascript;base64,${Buffer2.from(code).toString("base64")}`;
913
- return {
914
- outfile: dataUrl,
915
- cleanup: async () => {
916
- }
917
- };
918
- }
919
- throw new Error("Failed to create temporary output file for bundled code");
920
- }
921
-
922
- // src/loader.ts
923
- var _require2 = createRequire5(import.meta.url);
924
- var promisifiedRealpath = promisify(fs5.realpath);
682
+ const getOutputFile = options.getOutputFile || defaultGetOutputFile;
683
+ const fileName = `${sanitizeFilename(path.basename(sourceFile))}.${`timestamp-${Date.now()}-${Math.random().toString(16).slice(2)}`}.${options.format === "cjs" ? "cjs" : "mjs"}`;
684
+ const candidates = [];
685
+ if (typeof process.versions.deno !== "string") {
686
+ const nearest = findNearestNodeModules(path.dirname(sourceFile));
687
+ if (nearest) candidates.push(path.resolve(nearest, ".rolldown-require"));
688
+ }
689
+ candidates.push(path.join(os.tmpdir(), "rolldown-require"));
690
+ for (const base of candidates) {
691
+ const target = getOutputFile(path.join(base, fileName), options.format);
692
+ try {
693
+ await fsp.mkdir(path.dirname(target), { recursive: true });
694
+ await fsp.writeFile(target, code);
695
+ const cleanup = async () => {
696
+ if (options.preserveTemporaryFile) return;
697
+ try {
698
+ await fsp.unlink(target);
699
+ } catch {}
700
+ };
701
+ return {
702
+ outfile: options.format === "esm" ? pathToFileURL(target).href : target,
703
+ cleanup
704
+ };
705
+ } catch {}
706
+ }
707
+ if (options.format === "esm") return {
708
+ outfile: `data:text/javascript;base64,${Buffer$1.from(code).toString("base64")}`,
709
+ cleanup: async () => {}
710
+ };
711
+ throw new Error("Failed to create temporary output file for bundled code");
712
+ }
713
+ //#endregion
714
+ //#region src/loader.ts
715
+ const _require = createRequire(import.meta.url);
716
+ const promisifiedRealpath = promisify(fs.realpath);
925
717
  async function loadFromBundledFile(fileName, bundledCode, options, dependencies) {
926
- const cacheConfig = resolveCacheOptions(fileName, options);
927
- if (cacheConfig.enabled) {
928
- const cached = await maybeReadCache(cacheConfig, options);
929
- if (cached) {
930
- if (!cached.mod) {
931
- cacheConfig.onEvent?.({ type: "hit", key: cacheConfig.key });
932
- }
933
- return importCachedCode(cached, options);
934
- }
935
- cacheConfig.onEvent?.({ type: "miss", key: cacheConfig.key });
936
- }
937
- const { isESM } = options;
938
- if (isESM) {
939
- const tempOutput = cacheConfig.enabled ? await storeCacheOutput(cacheConfig, bundledCode, options, dependencies) : await resolveTempOutputFile(fileName, bundledCode, options);
940
- const outfile = tempOutput?.outfile;
941
- const cleanup = tempOutput?.cleanup;
942
- let mod;
943
- const req = options.require || dynamicImport;
944
- try {
945
- mod = await req(outfile, { format: options.format });
946
- if (cacheConfig.enabled && tempOutput?.cacheMeta) {
947
- await writeCacheMeta(cacheConfig, tempOutput.cacheMeta);
948
- cacheConfig.onEvent?.({ type: "store", key: cacheConfig.key });
949
- writeMemoryCache(cacheConfig, mod, tempOutput.cacheMeta);
950
- }
951
- return mod;
952
- } finally {
953
- if (!cacheConfig.enabled) {
954
- await cleanup?.();
955
- }
956
- }
957
- } else {
958
- const extension = path7.extname(fileName);
959
- const realFileName = await promisifiedRealpath(fileName);
960
- const loaderExt = extension in _require2.extensions ? extension : ".js";
961
- const defaultLoader = _require2.extensions[loaderExt];
962
- const compileLoader = (module, filename) => {
963
- if (filename === realFileName) {
964
- ;
965
- module._compile(bundledCode, filename);
966
- } else {
967
- defaultLoader(module, filename);
968
- }
969
- };
970
- let raw;
971
- try {
972
- _require2.extensions[loaderExt] = compileLoader;
973
- delete _require2.cache[_require2.resolve(fileName)];
974
- raw = _require2(fileName);
975
- return raw.__esModule ? raw.default : raw;
976
- } finally {
977
- _require2.extensions[loaderExt] = defaultLoader;
978
- if (cacheConfig.enabled && raw !== void 0) {
979
- const cachedPath = await storeCacheOutput(
980
- cacheConfig,
981
- bundledCode,
982
- options,
983
- dependencies
984
- );
985
- await writeCacheMeta(cacheConfig, cachedPath.cacheMeta);
986
- cacheConfig.onEvent?.({ type: "store", key: cacheConfig.key });
987
- writeMemoryCache(
988
- cacheConfig,
989
- raw.__esModule ? raw.default : raw,
990
- cachedPath.cacheMeta
991
- );
992
- }
993
- }
994
- }
995
- }
996
-
997
- // src/options.ts
998
- import path8 from "path";
999
- import process6 from "process";
1000
- import { getTsconfig } from "get-tsconfig";
718
+ const cacheConfig = resolveCacheOptions(fileName, options);
719
+ if (cacheConfig.enabled) {
720
+ const cached = await maybeReadCache(cacheConfig, options);
721
+ if (cached) {
722
+ if (!cached.mod) cacheConfig.onEvent?.({
723
+ type: "hit",
724
+ key: cacheConfig.key
725
+ });
726
+ return importCachedCode(cached, options);
727
+ }
728
+ cacheConfig.onEvent?.({
729
+ type: "miss",
730
+ key: cacheConfig.key
731
+ });
732
+ }
733
+ const { isESM } = options;
734
+ if (isESM) {
735
+ const tempOutput = cacheConfig.enabled ? await storeCacheOutput(cacheConfig, bundledCode, options, dependencies) : await resolveTempOutputFile(fileName, bundledCode, options);
736
+ const outfile = tempOutput?.outfile;
737
+ const cleanup = tempOutput?.cleanup;
738
+ let mod;
739
+ const req = options.require || dynamicImport;
740
+ try {
741
+ mod = await req(outfile, { format: options.format });
742
+ if (cacheConfig.enabled && tempOutput?.cacheMeta) {
743
+ await writeCacheMeta(cacheConfig, tempOutput.cacheMeta);
744
+ cacheConfig.onEvent?.({
745
+ type: "store",
746
+ key: cacheConfig.key
747
+ });
748
+ writeMemoryCache(cacheConfig, mod, tempOutput.cacheMeta);
749
+ }
750
+ return mod;
751
+ } finally {
752
+ if (!cacheConfig.enabled) await cleanup?.();
753
+ }
754
+ } else {
755
+ const extension = path.extname(fileName);
756
+ const realFileName = await promisifiedRealpath(fileName);
757
+ const loaderExt = extension in _require.extensions ? extension : ".js";
758
+ const defaultLoader = _require.extensions[loaderExt];
759
+ const compileLoader = (module, filename) => {
760
+ if (filename === realFileName) module._compile(bundledCode, filename);
761
+ else defaultLoader(module, filename);
762
+ };
763
+ let raw;
764
+ try {
765
+ _require.extensions[loaderExt] = compileLoader;
766
+ delete _require.cache[_require.resolve(fileName)];
767
+ raw = _require(fileName);
768
+ return raw.__esModule ? raw.default : raw;
769
+ } finally {
770
+ _require.extensions[loaderExt] = defaultLoader;
771
+ if (cacheConfig.enabled && raw !== void 0) {
772
+ const cachedPath = await storeCacheOutput(cacheConfig, bundledCode, options, dependencies);
773
+ await writeCacheMeta(cacheConfig, cachedPath.cacheMeta);
774
+ cacheConfig.onEvent?.({
775
+ type: "store",
776
+ key: cacheConfig.key
777
+ });
778
+ writeMemoryCache(cacheConfig, raw.__esModule ? raw.default : raw, cachedPath.cacheMeta);
779
+ }
780
+ }
781
+ }
782
+ }
783
+ //#endregion
784
+ //#region src/options.ts
1001
785
  function resolveEntryFilepath(options) {
1002
- if (path8.isAbsolute(options.filepath)) {
1003
- return options.filepath;
1004
- }
1005
- const cwd = options.cwd ? path8.resolve(options.cwd) : process6.cwd();
1006
- return path8.resolve(cwd, options.filepath);
786
+ if (path.isAbsolute(options.filepath)) return options.filepath;
787
+ const cwd = options.cwd ? path.resolve(options.cwd) : process.cwd();
788
+ return path.resolve(cwd, options.filepath);
1007
789
  }
1008
790
  function detectModuleType(resolvedPath) {
1009
- return typeof process6.versions.deno === "string" || isFilePathESM(resolvedPath);
791
+ return typeof process.versions.deno === "string" || isFilePathESM(resolvedPath);
1010
792
  }
1011
793
  function createInternalOptions(userOptions, isESM) {
1012
- const {
1013
- filepath: _filepath,
1014
- cwd: _cwd,
1015
- ...rest
1016
- } = userOptions;
1017
- const tsconfig = userOptions.tsconfig === false ? false : resolveTsconfigPath(userOptions);
1018
- const format = userOptions.format ?? (isESM ? "esm" : "cjs");
1019
- const sourcemap = resolveSourcemapOption(userOptions);
1020
- return {
1021
- ...rest,
1022
- isESM,
1023
- format,
1024
- tsconfig,
1025
- sourcemap
1026
- };
794
+ const { filepath: _filepath, cwd: _cwd, ...rest } = userOptions;
795
+ const tsconfig = userOptions.tsconfig === false ? false : resolveTsconfigPath(userOptions);
796
+ const format = userOptions.format ?? (isESM ? "esm" : "cjs");
797
+ const sourcemap = resolveSourcemapOption(userOptions);
798
+ return {
799
+ ...rest,
800
+ isESM,
801
+ format,
802
+ tsconfig,
803
+ sourcemap
804
+ };
1027
805
  }
1028
806
  function resolveTsconfigPath(options) {
1029
- if (options.tsconfig === false) {
1030
- return void 0;
1031
- }
1032
- if (typeof options.tsconfig === "string") {
1033
- return options.tsconfig;
1034
- }
1035
- return getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
807
+ if (options.tsconfig === false) return;
808
+ if (typeof options.tsconfig === "string") return options.tsconfig;
809
+ return getTsconfig(options.cwd, "tsconfig.json")?.path ?? void 0;
1036
810
  }
1037
811
  function resolveSourcemapOption(options) {
1038
- if (options.sourcemap !== void 0) {
1039
- return options.sourcemap;
1040
- }
1041
- if (shouldEnableSourcemapFromEnv()) {
1042
- return "inline";
1043
- }
1044
- return void 0;
812
+ if (options.sourcemap !== void 0) return options.sourcemap;
813
+ if (shouldEnableSourcemapFromEnv()) return "inline";
1045
814
  }
1046
815
  function shouldEnableSourcemapFromEnv() {
1047
- const nodeOptions = process6.env.NODE_OPTIONS ?? "";
1048
- if (nodeOptions.includes("--inspect")) {
1049
- return true;
1050
- }
1051
- if (process6.env.VSCODE_INSPECTOR_OPTIONS) {
1052
- return true;
1053
- }
1054
- if (process6.env.DEBUG) {
1055
- return true;
1056
- }
1057
- return false;
816
+ if ((process.env.NODE_OPTIONS ?? "").includes("--inspect")) return true;
817
+ if (process.env.VSCODE_INSPECTOR_OPTIONS) return true;
818
+ if (process.env.DEBUG) return true;
819
+ return false;
1058
820
  }
1059
-
1060
- // src/index.ts
821
+ //#endregion
822
+ //#region src/index.ts
1061
823
  async function bundleRequire(options) {
1062
- const resolvedPath = resolveEntryFilepath(options);
1063
- const isESM = detectModuleType(resolvedPath);
1064
- const internalOptions = createInternalOptions(options, isESM);
1065
- const cacheConfig = resolveCacheOptions(resolvedPath, internalOptions);
1066
- if (cacheConfig.enabled) {
1067
- const cached = await maybeReadCache(cacheConfig, internalOptions);
1068
- if (cached) {
1069
- const mod2 = await importCachedCode(cached, internalOptions);
1070
- if (cacheConfig.memory && cached.meta) {
1071
- writeMemoryCache(cacheConfig, mod2, cached.meta);
1072
- }
1073
- const dependencies = cached.meta?.files?.map((file) => file.path).filter((file) => file !== cacheConfig.entryPath) ?? [];
1074
- return { mod: mod2, dependencies };
1075
- }
1076
- }
1077
- const bundled = await bundleFile(
1078
- resolvedPath,
1079
- internalOptions
1080
- );
1081
- const mod = await loadFromBundledFile(
1082
- resolvedPath,
1083
- bundled.code,
1084
- internalOptions,
1085
- bundled.dependencies
1086
- );
1087
- return {
1088
- mod,
1089
- dependencies: bundled.dependencies
1090
- };
1091
- }
1092
- export {
1093
- bundleFile,
1094
- bundleRequire,
1095
- configDefaults,
1096
- loadFromBundledFile
1097
- };
824
+ const resolvedPath = resolveEntryFilepath(options);
825
+ const internalOptions = createInternalOptions(options, detectModuleType(resolvedPath));
826
+ const cacheConfig = resolveCacheOptions(resolvedPath, internalOptions);
827
+ if (cacheConfig.enabled) {
828
+ const cached = await maybeReadCache(cacheConfig, internalOptions);
829
+ if (cached) {
830
+ const mod = await importCachedCode(cached, internalOptions);
831
+ if (cacheConfig.memory && cached.meta) writeMemoryCache(cacheConfig, mod, cached.meta);
832
+ return {
833
+ mod,
834
+ dependencies: cached.meta?.files?.map((file) => file.path).filter((file) => file !== cacheConfig.entryPath) ?? []
835
+ };
836
+ }
837
+ }
838
+ const bundled = await bundleFile(resolvedPath, internalOptions);
839
+ return {
840
+ mod: await loadFromBundledFile(resolvedPath, bundled.code, internalOptions, bundled.dependencies),
841
+ dependencies: bundled.dependencies
842
+ };
843
+ }
844
+ //#endregion
845
+ export { bundleFile, bundleRequire, configDefaults, loadFromBundledFile };