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