@voidzero-dev/vite-plus-core 0.0.0-0bfcc90f.20260209-0731

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.
Files changed (114) hide show
  1. package/LICENSE +41 -0
  2. package/dist/pluginutils/filter/composable-filters.d.ts +90 -0
  3. package/dist/pluginutils/filter/composable-filters.js +256 -0
  4. package/dist/pluginutils/filter/filter-vite-plugins.d.ts +28 -0
  5. package/dist/pluginutils/filter/filter-vite-plugins.js +75 -0
  6. package/dist/pluginutils/filter/index.d.ts +3 -0
  7. package/dist/pluginutils/filter/index.js +3 -0
  8. package/dist/pluginutils/filter/simple-filters.d.ts +71 -0
  9. package/dist/pluginutils/filter/simple-filters.js +70 -0
  10. package/dist/pluginutils/index.d.ts +1 -0
  11. package/dist/pluginutils/index.js +1 -0
  12. package/dist/pluginutils/utils.d.ts +2 -0
  13. package/dist/pluginutils/utils.js +17 -0
  14. package/dist/rolldown/cli-setup.d.mts +1 -0
  15. package/dist/rolldown/cli-setup.mjs +17 -0
  16. package/dist/rolldown/cli.d.mts +1 -0
  17. package/dist/rolldown/cli.mjs +608 -0
  18. package/dist/rolldown/config.d.mts +7 -0
  19. package/dist/rolldown/config.mjs +10 -0
  20. package/dist/rolldown/experimental-index.d.mts +194 -0
  21. package/dist/rolldown/experimental-index.mjs +291 -0
  22. package/dist/rolldown/experimental-runtime-types.d.ts +98 -0
  23. package/dist/rolldown/filter-index.d.mts +197 -0
  24. package/dist/rolldown/filter-index.mjs +369 -0
  25. package/dist/rolldown/get-log-filter.d.mts +7 -0
  26. package/dist/rolldown/get-log-filter.mjs +47 -0
  27. package/dist/rolldown/index.d.mts +4 -0
  28. package/dist/rolldown/index.mjs +57 -0
  29. package/dist/rolldown/parallel-plugin-worker.d.mts +1 -0
  30. package/dist/rolldown/parallel-plugin-worker.mjs +32 -0
  31. package/dist/rolldown/parallel-plugin.d.mts +14 -0
  32. package/dist/rolldown/parallel-plugin.mjs +7 -0
  33. package/dist/rolldown/parse-ast-index.d.mts +8 -0
  34. package/dist/rolldown/parse-ast-index.mjs +47 -0
  35. package/dist/rolldown/plugins-index.d.mts +30 -0
  36. package/dist/rolldown/plugins-index.mjs +40 -0
  37. package/dist/rolldown/shared/binding-D-XMzSaG.d.mts +1665 -0
  38. package/dist/rolldown/shared/binding-DuOSzYPt.mjs +587 -0
  39. package/dist/rolldown/shared/bindingify-input-options-Bu6nUTgS.mjs +2257 -0
  40. package/dist/rolldown/shared/constructors-DZVRHTli.mjs +61 -0
  41. package/dist/rolldown/shared/constructors-KD7LvxpN.d.mts +28 -0
  42. package/dist/rolldown/shared/define-config-BVG4QvnP.mjs +7 -0
  43. package/dist/rolldown/shared/define-config-U4pj0ZDn.d.mts +3616 -0
  44. package/dist/rolldown/shared/load-config-O1K_tT_z.mjs +114 -0
  45. package/dist/rolldown/shared/logging-CE90D8JR.d.mts +50 -0
  46. package/dist/rolldown/shared/logs-NH298mHo.mjs +183 -0
  47. package/dist/rolldown/shared/misc-CCZIsXVO.mjs +22 -0
  48. package/dist/rolldown/shared/normalize-string-or-regex-DeZqg15i.mjs +61 -0
  49. package/dist/rolldown/shared/parse-DLraxqjd.mjs +56 -0
  50. package/dist/rolldown/shared/prompt-DeISmFRp.mjs +847 -0
  51. package/dist/rolldown/shared/rolldown-O0UKbTKf.mjs +42 -0
  52. package/dist/rolldown/shared/rolldown-build-BIs7C4B_.mjs +3354 -0
  53. package/dist/rolldown/shared/watch-DQXGaDjx.mjs +379 -0
  54. package/dist/tsdown/build-l5WhXg4M-BBPqZr0m.js +4933 -0
  55. package/dist/tsdown/chunk-CdeBBKNj.js +44 -0
  56. package/dist/tsdown/debug-Cb_Nqpo4-BueIRvg1.js +18 -0
  57. package/dist/tsdown/detect-CCATtVj7-B86m8IqW.js +165 -0
  58. package/dist/tsdown/dist-BUOkzr_P.js +201 -0
  59. package/dist/tsdown/dist-BVMGwPdF.js +32363 -0
  60. package/dist/tsdown/dist-dc0X0G6b.js +742 -0
  61. package/dist/tsdown/filename-7rlgePeo.js +31 -0
  62. package/dist/tsdown/index-node-BjDys8jy--sqPE5mM.js +251 -0
  63. package/dist/tsdown/index-types.d.ts +2163 -0
  64. package/dist/tsdown/index.js +14 -0
  65. package/dist/tsdown/main-d9yZSQqW.js +926 -0
  66. package/dist/tsdown/node-Cb5OsnKg.js +271 -0
  67. package/dist/tsdown/npm_cjs_chunk_chunk.cjs +11 -0
  68. package/dist/tsdown/npm_cjs_chunk_range.cjs +484 -0
  69. package/dist/tsdown/npm_cjs_chunk_semver.cjs +362 -0
  70. package/dist/tsdown/npm_entry_picomatch.cjs +1676 -0
  71. package/dist/tsdown/npm_entry_semver_functions_coerce.cjs +52 -0
  72. package/dist/tsdown/npm_entry_semver_functions_satisfies.cjs +23 -0
  73. package/dist/tsdown/npm_entry_semver_ranges_min-version.cjs +48 -0
  74. package/dist/tsdown/npm_entry_tree-kill.cjs +103 -0
  75. package/dist/tsdown/resolver-j7HY1N36-CIu_7LX6.js +20 -0
  76. package/dist/tsdown/run.js +537 -0
  77. package/dist/tsdown/tsc-context-BNYuT3cE.js +25 -0
  78. package/dist/tsdown/tsc-reo6aLWc.js +423 -0
  79. package/dist/vite/client/client.mjs +1140 -0
  80. package/dist/vite/client/env.mjs +19 -0
  81. package/dist/vite/client.d.ts +279 -0
  82. package/dist/vite/misc/false.d.ts +2 -0
  83. package/dist/vite/misc/false.js +1 -0
  84. package/dist/vite/misc/true.d.ts +2 -0
  85. package/dist/vite/misc/true.js +1 -0
  86. package/dist/vite/node/chunks/build2.js +5538 -0
  87. package/dist/vite/node/chunks/chunk.js +45 -0
  88. package/dist/vite/node/chunks/dist.js +6758 -0
  89. package/dist/vite/node/chunks/dist2.js +6651 -0
  90. package/dist/vite/node/chunks/fetchableEnvironments.js +41395 -0
  91. package/dist/vite/node/chunks/lib.js +377 -0
  92. package/dist/vite/node/chunks/logger.js +332 -0
  93. package/dist/vite/node/chunks/moduleRunnerTransport.d.ts +96 -0
  94. package/dist/vite/node/chunks/postcss-import.js +479 -0
  95. package/dist/vite/node/cli.js +699 -0
  96. package/dist/vite/node/index.d.ts +3807 -0
  97. package/dist/vite/node/index.js +15 -0
  98. package/dist/vite/node/internal.d.ts +2 -0
  99. package/dist/vite/node/internal.js +3 -0
  100. package/dist/vite/node/module-runner.d.ts +311 -0
  101. package/dist/vite/node/module-runner.js +1159 -0
  102. package/dist/vite/types/customEvent.d.ts +52 -0
  103. package/dist/vite/types/hmrPayload.d.ts +80 -0
  104. package/dist/vite/types/hot.d.ts +39 -0
  105. package/dist/vite/types/import-meta.d.ts +5 -0
  106. package/dist/vite/types/importGlob.d.ts +89 -0
  107. package/dist/vite/types/importMeta.d.ts +30 -0
  108. package/dist/vite/types/internal/cssPreprocessorOptions.d.ts +44 -0
  109. package/dist/vite/types/internal/esbuildOptions.d.ts +28 -0
  110. package/dist/vite/types/internal/lightningcssOptions.d.ts +18 -0
  111. package/dist/vite/types/internal/rollupTypeCompat.d.ts +24 -0
  112. package/dist/vite/types/internal/terserOptions.d.ts +11 -0
  113. package/dist/vite/types/metadata.d.ts +47 -0
  114. package/package.json +204 -0
@@ -0,0 +1,742 @@
1
+ import { builtinModules, createRequire } from "node:module";
2
+ import process from "node:process";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { rolldown } from "@voidzero-dev/vite-plus-core/rolldown";
5
+ import { spawn } from "node:child_process";
6
+ import path from "node:path";
7
+ import fs, { existsSync } from "node:fs";
8
+ import { Buffer } from "node:buffer";
9
+ import { tmpdir } from "node:os";
10
+ import crypto from "node:crypto";
11
+
12
+ //#region ../../node_modules/.pnpm/unrun@0.2.27/node_modules/unrun/dist/src-CS8hJStK.mjs
13
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
14
+ /**
15
+ * Applies preset-specific handling to the loaded module.
16
+ */
17
+ function preset(options, module) {
18
+ if (options.preset === "bundle-require") return module;
19
+ if (options.preset === "jiti") {
20
+ const ext = path.extname(options.path);
21
+ if (module && typeof module === "object" && module[Symbol.toStringTag] === "Module" && Object.keys(module).length === 0) return ext === ".mjs" ? module : {};
22
+ }
23
+ if (module && typeof module === "object" && "default" in module) return module.default;
24
+ return module;
25
+ }
26
+ /**
27
+ * Normalize a path-like input to a string path.
28
+ * @param pathLike The path-like input (string or URL).
29
+ * @returns The normalized string path.
30
+ */
31
+ function normalizePath(pathLike) {
32
+ if (!pathLike) return "index.ts";
33
+ if (pathLike instanceof URL) {
34
+ if (pathLike.protocol === "file:") return fileURLToPath(pathLike);
35
+ return pathLike.href;
36
+ }
37
+ if (typeof pathLike === "string") {
38
+ if (!pathLike.startsWith("file:")) return pathLike;
39
+ try {
40
+ return fileURLToPath(pathLike);
41
+ } catch {
42
+ try {
43
+ return fileURLToPath(new URL(pathLike));
44
+ } catch {
45
+ return pathLike;
46
+ }
47
+ }
48
+ }
49
+ return String(pathLike);
50
+ }
51
+ function resolveOptions(options = {}) {
52
+ const resolvedOptions = {
53
+ path: path.resolve(process.cwd(), normalizePath(options.path)),
54
+ debug: options.debug || false,
55
+ preset: options.preset || "none",
56
+ inputOptions: options.inputOptions,
57
+ outputOptions: options.outputOptions
58
+ };
59
+ if (!fs.existsSync(resolvedOptions.path)) throw new Error(`[unrun] File not found: ${resolvedOptions.path}`);
60
+ if (!new Set([
61
+ "none",
62
+ "jiti",
63
+ "bundle-require"
64
+ ]).has(resolvedOptions.preset)) throw new Error(`[unrun] Invalid preset "${resolvedOptions.preset}" (expected: none | jiti | bundle-require)`);
65
+ return resolvedOptions;
66
+ }
67
+ /**
68
+ * Precomputed set of Node.js builtin module specifiers, including both plain and `node:` prefixed forms.
69
+ */
70
+ const BUILTIN_MODULE_SPECIFIERS = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
71
+ /**
72
+ * Returns true when `id` refers to a Node.js builtin module, accepting both plain and `node:` specifiers.
73
+ */
74
+ function isBuiltinModuleSpecifier(id) {
75
+ if (!id) return false;
76
+ return BUILTIN_MODULE_SPECIFIERS.has(id) || id.startsWith("node:");
77
+ }
78
+ /**
79
+ * Builds the rolldown external resolver used to decide which imports remain external.
80
+ * Treat bare imports from the primary node_modules as external, but inline
81
+ * nested node_modules so they keep working once executed from .unrun.
82
+ */
83
+ function createExternalResolver(options) {
84
+ const entryDir = path.dirname(options.path);
85
+ const canResolveFromEntry = (specifier) => {
86
+ const packageName = getPackageName(specifier);
87
+ if (!packageName) return false;
88
+ let currentDir = entryDir;
89
+ while (true) {
90
+ if (existsSync(path.join(currentDir, "node_modules", packageName))) return true;
91
+ const parentDir = path.dirname(currentDir);
92
+ if (parentDir === currentDir) break;
93
+ currentDir = parentDir;
94
+ }
95
+ return false;
96
+ };
97
+ return function external(id) {
98
+ if (!id || id.startsWith("\0")) return false;
99
+ if (id.startsWith(".") || id.startsWith("#") || path.isAbsolute(id)) return false;
100
+ if (isBuiltinModuleSpecifier(id)) return true;
101
+ if (!canResolveFromEntry(id)) return false;
102
+ return true;
103
+ };
104
+ }
105
+ function getPackageName(specifier) {
106
+ if (!specifier) return void 0;
107
+ if (specifier.startsWith("@")) {
108
+ const segments = specifier.split("/");
109
+ if (segments.length >= 2) return `${segments[0]}/${segments[1]}`;
110
+ return;
111
+ }
112
+ const [name] = specifier.split("/");
113
+ return name || void 0;
114
+ }
115
+ const INSPECT_HELPER_SNIPPET = `(function(){
116
+ function __unrun__fmt(names, getter, np){
117
+ var onlyDefault = names.length === 1 && names[0] === "default";
118
+ var o = np ? Object.create(null) : {};
119
+ for (var i = 0; i < names.length; i++) {
120
+ var n = names[i];
121
+ try { o[n] = getter(n) } catch {}
122
+ }
123
+ if (onlyDefault) {
124
+ try {
125
+ var s = JSON.stringify(o.default);
126
+ if (s !== undefined) {
127
+ s = s.replace(/"([^"]+)":/g, "$1: ").replace(/,/g, ", ").replace(/{/g, "{ ").replace(/}/g, " }");
128
+ return "[Module: null prototype] { default: " + s + " }";
129
+ }
130
+ } catch {}
131
+ return "[Module: null prototype] { default: " + String(o.default) + " }";
132
+ }
133
+ return o;
134
+ }
135
+ function __unrun__setInspect(obj, names, getter, np){
136
+ try {
137
+ var __insp = Symbol.for('nodejs.util.inspect.custom');
138
+ Object.defineProperty(obj, __insp, {
139
+ value: function(){ return __unrun__fmt(names, getter, np) },
140
+ enumerable: false, configurable: true
141
+ });
142
+ } catch {}
143
+ return obj;
144
+ }
145
+ try {
146
+ Object.defineProperty(globalThis, "__unrun__setInspect", {
147
+ value: __unrun__setInspect,
148
+ enumerable: false,
149
+ });
150
+ } catch {}
151
+ })();`;
152
+ const WRAPPER_SNIPPET = `(function __unrun__wrapRolldownHelpers(){
153
+ if (typeof __unrun__setInspect !== "function") return;
154
+ if (typeof __export === "function" && !__export.__unrunPatched) {
155
+ var __unrun__origExport = __export;
156
+ var __unrun__patchedExport = (...__unrun__args) => {
157
+ var __unrun__target = __unrun__origExport(...__unrun__args);
158
+ if (__unrun__target && typeof __unrun__target === "object") {
159
+ try {
160
+ var __unrun__map = (__unrun__args[0] && typeof __unrun__args[0] === "object") ? __unrun__args[0] : {};
161
+ var __unrun__names = Object.keys(__unrun__map).filter(function(n){ return n !== "__esModule" });
162
+ __unrun__setInspect(
163
+ __unrun__target,
164
+ __unrun__names,
165
+ function(n){
166
+ var getter = __unrun__map[n];
167
+ return typeof getter === "function" ? getter() : getter;
168
+ },
169
+ false,
170
+ );
171
+ } catch {}
172
+ }
173
+ return __unrun__target;
174
+ };
175
+ __unrun__patchedExport.__unrunPatched = true;
176
+ __export = __unrun__patchedExport;
177
+ }
178
+ if (typeof __exportAll === "function" && !__exportAll.__unrunPatched) {
179
+ var __unrun__origExportAll = __exportAll;
180
+ var __unrun__patchedExportAll = (...__unrun__args) => {
181
+ var __unrun__target = __unrun__origExportAll(...__unrun__args);
182
+ if (__unrun__target && typeof __unrun__target === "object") {
183
+ try {
184
+ var __unrun__map = (__unrun__args[0] && typeof __unrun__args[0] === "object") ? __unrun__args[0] : {};
185
+ var __unrun__names = Object.keys(__unrun__map).filter(function(n){ return n !== "__esModule" });
186
+ __unrun__setInspect(
187
+ __unrun__target,
188
+ __unrun__names,
189
+ function(n){
190
+ var getter = __unrun__map[n];
191
+ return typeof getter === "function" ? getter() : getter;
192
+ },
193
+ false,
194
+ );
195
+ } catch {}
196
+ }
197
+ return __unrun__target;
198
+ };
199
+ __unrun__patchedExportAll.__unrunPatched = true;
200
+ __exportAll = __unrun__patchedExportAll;
201
+ }
202
+ if (typeof __copyProps === "function" && !__copyProps.__unrunPatched) {
203
+ var __unrun__origCopyProps = __copyProps;
204
+ var __unrun__patchedCopyProps = (...__unrun__args) => {
205
+ var __unrun__result = __unrun__origCopyProps(...__unrun__args);
206
+ if (__unrun__result && typeof __unrun__result === "object") {
207
+ try {
208
+ var __unrun__names = Object.keys(__unrun__result).filter(function(n){ return n !== "__esModule" });
209
+ __unrun__setInspect(__unrun__result, __unrun__names, function(n){ return __unrun__result[n] }, true);
210
+ } catch {}
211
+ }
212
+ return __unrun__result;
213
+ };
214
+ __unrun__patchedCopyProps.__unrunPatched = true;
215
+ __copyProps = __unrun__patchedCopyProps;
216
+ }
217
+ })();`;
218
+ const HELPER_DECLARATION_PATTERN = /__unrun__setInspect\b/;
219
+ const WRAPPER_MARKER = "__unrun__wrapRolldownHelpers";
220
+ function createConsoleOutputCustomizer() {
221
+ return {
222
+ name: "unrun-console-output-customizer",
223
+ generateBundle: { handler(_, bundle) {
224
+ for (const chunk of Object.values(bundle)) {
225
+ if (chunk.type !== "chunk") continue;
226
+ injectInspectHelper(chunk);
227
+ injectHelperWrappers(chunk);
228
+ }
229
+ } }
230
+ };
231
+ }
232
+ function injectInspectHelper(chunk) {
233
+ if (HELPER_DECLARATION_PATTERN.test(chunk.code)) return;
234
+ chunk.code = chunk.code.startsWith("#!") ? insertAfterShebang(chunk.code, `${INSPECT_HELPER_SNIPPET}\n`) : `${INSPECT_HELPER_SNIPPET}\n${chunk.code}`;
235
+ }
236
+ function injectHelperWrappers(chunk) {
237
+ if (chunk.code.includes(WRAPPER_MARKER)) return;
238
+ const insertIndex = findRuntimeBoundary(chunk.code);
239
+ const snippet = `${WRAPPER_SNIPPET}\n`;
240
+ if (insertIndex === -1) {
241
+ chunk.code = `${chunk.code}\n${snippet}`;
242
+ return;
243
+ }
244
+ chunk.code = `${chunk.code.slice(0, insertIndex)}${snippet}${chunk.code.slice(insertIndex)}`;
245
+ }
246
+ function findRuntimeBoundary(code) {
247
+ const markerIndex = code.indexOf("//#endregion");
248
+ if (markerIndex === -1) return -1;
249
+ const newlineIndex = code.indexOf("\n", markerIndex);
250
+ return newlineIndex === -1 ? code.length : newlineIndex + 1;
251
+ }
252
+ function insertAfterShebang(code, insertion) {
253
+ const nl = code.indexOf("\n");
254
+ if (nl === -1) return `${code}\n${insertion}`;
255
+ return `${code.slice(0, nl + 1)}${insertion}${code.slice(nl + 1)}`;
256
+ }
257
+ /**
258
+ * Minimal JSON loader to mimic jiti/Node behavior expected by tests:
259
+ * - Default export is the parsed JSON object
260
+ * - Also add a self-reference `default` property on the object (so obj.default === obj)
261
+ * - Provide named exports for top-level properties
262
+ */
263
+ function createJsonLoader() {
264
+ return {
265
+ name: "unrun-json-loader",
266
+ resolveId: { handler(source, importer) {
267
+ if (!source.endsWith(".json")) return null;
268
+ const basedir = importer ? path.dirname(importer) : process.cwd();
269
+ const resolved = path.resolve(basedir, source);
270
+ let isRequire = false;
271
+ try {
272
+ if (importer) {
273
+ const src = fs.readFileSync(importer, "utf8");
274
+ const escaped = source.replaceAll(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
275
+ const pattern = String.raw`\brequire\s*\(\s*['"]${escaped}['"]\s*\)`;
276
+ isRequire = new RegExp(pattern).test(src);
277
+ }
278
+ } catch {}
279
+ return { id: `${resolved}?unrun-json.${isRequire ? "cjs" : "mjs"}` };
280
+ } },
281
+ load: {
282
+ filter: { id: /\?unrun-json\.(?:mjs|cjs)$/ },
283
+ handler(id) {
284
+ try {
285
+ const realId = id.replace(/\?unrun-json\.(?:mjs|cjs)$/, "");
286
+ const src = fs.readFileSync(realId, "utf8");
287
+ const data = JSON.parse(src);
288
+ const jsonLiteral = JSON.stringify(data);
289
+ if (id.endsWith("?unrun-json.cjs")) return { code: `const __data = ${jsonLiteral}\ntry { Object.defineProperty(__data, 'default', { value: __data, enumerable: false, configurable: true }) } catch {}\nmodule.exports = __data\n` };
290
+ const named = Object.keys(data).filter((k) => /^[$A-Z_]\w*$/i.test(k)).map((k) => `export const ${k} = __data[${JSON.stringify(k)}]`).join("\n");
291
+ return { code: [
292
+ `const __data = ${jsonLiteral}`,
293
+ `try { Object.defineProperty(__data, 'default', { value: __data, enumerable: false, configurable: true }) } catch {}`,
294
+ named,
295
+ `export default __data`
296
+ ].filter(Boolean).join("\n") };
297
+ } catch {
298
+ return null;
299
+ }
300
+ }
301
+ }
302
+ };
303
+ }
304
+ /**
305
+ * Transforms code strings containing CommonJS wrappers to be async-friendly.
306
+ *
307
+ * Rolldown may wrap CommonJS modules in a `__commonJS` function that uses
308
+ * arrow functions. If the wrapped code contains top-level `await`, this can lead
309
+ * to syntax errors since the callback function won't be marked as `async`.
310
+ * This function scans for such patterns and modifies the arrow functions to
311
+ * be `async` if they contain `await` expressions.
312
+ */
313
+ function createMakeCjsWrapperAsyncFriendlyPlugin() {
314
+ return {
315
+ name: "unrun-make-cjs-wrapper-async-friendly",
316
+ generateBundle: { handler(_outputOptions, bundle) {
317
+ for (const chunk of Object.values(bundle)) {
318
+ if (chunk.type !== "chunk") continue;
319
+ let code = chunk.code;
320
+ const wrapperMarkers = ["__commonJS({", "__commonJSMin("];
321
+ if (!wrapperMarkers.some((marker) => code.includes(marker))) continue;
322
+ const arrowToken = "(() => {";
323
+ const asyncArrowToken = "(async () => {";
324
+ const patchMarker = (marker) => {
325
+ let pos = 0;
326
+ while (true) {
327
+ const markerIdx = code.indexOf(marker, pos);
328
+ if (markerIdx === -1) break;
329
+ const fnStart = code.indexOf(arrowToken, markerIdx);
330
+ if (fnStart === -1) {
331
+ pos = markerIdx + marker.length;
332
+ continue;
333
+ }
334
+ const bodyStart = fnStart + 8;
335
+ let i = bodyStart;
336
+ let depth = 1;
337
+ while (i < code.length && depth > 0) {
338
+ const ch = code[i++];
339
+ if (ch === "{") depth++;
340
+ else if (ch === "}") depth--;
341
+ }
342
+ if (depth !== 0) break;
343
+ const bodyEnd = i - 1;
344
+ const body = code.slice(bodyStart, bodyEnd);
345
+ if (/\bawait\b/.test(body) && code.slice(fnStart, fnStart + 14) !== asyncArrowToken) {
346
+ code = `${code.slice(0, fnStart + 1)}async ${code.slice(fnStart + 1)}`;
347
+ pos = fnStart + 1 + 6;
348
+ continue;
349
+ }
350
+ pos = bodyEnd;
351
+ }
352
+ };
353
+ for (const marker of wrapperMarkers) patchMarker(marker);
354
+ if (code !== chunk.code) chunk.code = code;
355
+ }
356
+ } }
357
+ };
358
+ }
359
+ /**
360
+ * Fix require.resolve calls to use the correct base path.
361
+ * Replace __require.resolve("./relative") with proper resolution from original file location.
362
+ */
363
+ function createRequireResolveFix(options) {
364
+ return {
365
+ name: "unrun-require-resolve-fix",
366
+ generateBundle: { handler(_, bundle) {
367
+ for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/__require\.resolve\(["']([^"']+)["']\)/g, (match, id) => {
368
+ if (id.startsWith("./") || id.startsWith("../")) try {
369
+ const baseDir = path.dirname(options.path);
370
+ for (const ext of [
371
+ "",
372
+ ".ts",
373
+ ".js",
374
+ ".mts",
375
+ ".mjs",
376
+ ".cts",
377
+ ".cjs"
378
+ ]) {
379
+ const testPath = path.resolve(baseDir, id + ext);
380
+ if (fs.existsSync(testPath)) return JSON.stringify(testPath);
381
+ }
382
+ const resolvedPath = path.resolve(baseDir, id);
383
+ return JSON.stringify(resolvedPath);
384
+ } catch {
385
+ return match;
386
+ }
387
+ return match;
388
+ });
389
+ } }
390
+ };
391
+ }
392
+ /**
393
+ * Ensure typeof require in ESM stays undefined to match jiti behavior.
394
+ * Replaces typeof __require with typeof require to maintain compatibility.
395
+ */
396
+ function createRequireTypeofFix() {
397
+ return {
398
+ name: "unrun-require-typeof-fix",
399
+ generateBundle: { handler(_, bundle) {
400
+ for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/\btypeof\s+__require\b/g, "typeof require");
401
+ } }
402
+ };
403
+ }
404
+ /**
405
+ * A rolldown plugin that injects source context shims:
406
+ * - Replaces import.meta.resolve calls with resolved file URLs
407
+ * - Injects per-module __filename/__dirname
408
+ * - Replaces import.meta.url with the source file URL
409
+ * - Replaces import.meta.dirname/import.meta.filename with source paths
410
+ */
411
+ function createSourceContextShimsPlugin() {
412
+ return {
413
+ name: "unrun-source-context-shims",
414
+ load: {
415
+ filter: { id: /\.(?:m?[jt]s|c?tsx?)(?:$|\?)/ },
416
+ handler(id) {
417
+ const physicalId = id.split("?")[0].split("#")[0];
418
+ const normalizedPhysicalId = path.normalize(physicalId);
419
+ let code;
420
+ try {
421
+ code = fs.readFileSync(normalizedPhysicalId, "utf8");
422
+ } catch {
423
+ return null;
424
+ }
425
+ if (normalizedPhysicalId.replaceAll("\\", "/").includes("/node_modules/")) return null;
426
+ const file = normalizedPhysicalId;
427
+ const dir = path.dirname(normalizedPhysicalId);
428
+ const url = pathToFileURL(normalizedPhysicalId).href;
429
+ const hasImportMeta = code.includes("import.meta");
430
+ const usesFilename = /\b__filename\b/.test(code);
431
+ const declaresFilename = /\b(?:const|let|var)\s+__filename\b/.test(code);
432
+ const usesDirname = /\b__dirname\b/.test(code);
433
+ const declaresDirname = /\b(?:const|let|var)\s+__dirname\b/.test(code);
434
+ const needsFilenameShim = usesFilename && !declaresFilename;
435
+ const needsDirnameShim = usesDirname && !declaresDirname;
436
+ if (needsFilenameShim || needsDirnameShim || hasImportMeta) {
437
+ const prologueLines = [];
438
+ if (needsFilenameShim) prologueLines.push(`const __filename = ${JSON.stringify(file)}`);
439
+ if (needsDirnameShim) prologueLines.push(`const __dirname = ${JSON.stringify(dir)}`);
440
+ let transformedCode = code;
441
+ let replacedImportMeta = false;
442
+ if (hasImportMeta) {
443
+ const resolveRe = /import\s*\.\s*meta\s*\.\s*resolve!?\s*\(\s*(["'])([^"']+)\1\s*\)/y;
444
+ const urlRe = /import\s*\.\s*meta\s*\.\s*url\b/y;
445
+ const dirnameRe = /import\s*\.\s*meta\s*\.\s*dirname\b/y;
446
+ const filenameRe = /import\s*\.\s*meta\s*\.\s*filename\b/y;
447
+ let out = "";
448
+ let mode = "normal";
449
+ const modeStack = [];
450
+ let templateExprBraceDepth = 0;
451
+ const popMode = () => {
452
+ mode = modeStack.pop() ?? "normal";
453
+ };
454
+ for (let i = 0; i < transformedCode.length;) {
455
+ const ch = transformedCode[i];
456
+ const next = transformedCode[i + 1];
457
+ if (mode === "lineComment") {
458
+ out += ch;
459
+ i += 1;
460
+ if (ch === "\n") popMode();
461
+ continue;
462
+ }
463
+ if (mode === "blockComment") {
464
+ out += ch;
465
+ i += 1;
466
+ if (ch === "*" && next === "/") {
467
+ out += "/";
468
+ i += 1;
469
+ popMode();
470
+ }
471
+ continue;
472
+ }
473
+ if (mode === "single") {
474
+ out += ch;
475
+ i += 1;
476
+ if (ch === "\\") {
477
+ out += transformedCode[i] ?? "";
478
+ i += 1;
479
+ continue;
480
+ }
481
+ if (ch === "'") popMode();
482
+ continue;
483
+ }
484
+ if (mode === "double") {
485
+ out += ch;
486
+ i += 1;
487
+ if (ch === "\\") {
488
+ out += transformedCode[i] ?? "";
489
+ i += 1;
490
+ continue;
491
+ }
492
+ if (ch === "\"") popMode();
493
+ continue;
494
+ }
495
+ if (mode === "template") {
496
+ out += ch;
497
+ i += 1;
498
+ if (ch === "\\") {
499
+ out += transformedCode[i] ?? "";
500
+ i += 1;
501
+ continue;
502
+ }
503
+ if (ch === "`") {
504
+ popMode();
505
+ continue;
506
+ }
507
+ if (ch === "$" && next === "{") {
508
+ out += "{";
509
+ i += 1;
510
+ modeStack.push(mode);
511
+ mode = "templateExpr";
512
+ templateExprBraceDepth = 1;
513
+ }
514
+ continue;
515
+ }
516
+ if (mode === "templateExpr") {
517
+ if (ch === "{") templateExprBraceDepth += 1;
518
+ else if (ch === "}") {
519
+ templateExprBraceDepth -= 1;
520
+ if (templateExprBraceDepth === 0) {
521
+ out += ch;
522
+ i += 1;
523
+ popMode();
524
+ continue;
525
+ }
526
+ }
527
+ }
528
+ if (ch === "/" && next === "/") {
529
+ out += "//";
530
+ i += 2;
531
+ modeStack.push(mode);
532
+ mode = "lineComment";
533
+ continue;
534
+ }
535
+ if (ch === "/" && next === "*") {
536
+ out += "/*";
537
+ i += 2;
538
+ modeStack.push(mode);
539
+ mode = "blockComment";
540
+ continue;
541
+ }
542
+ if (ch === "'") {
543
+ out += ch;
544
+ i += 1;
545
+ modeStack.push(mode);
546
+ mode = "single";
547
+ continue;
548
+ }
549
+ if (ch === "\"") {
550
+ out += ch;
551
+ i += 1;
552
+ modeStack.push(mode);
553
+ mode = "double";
554
+ continue;
555
+ }
556
+ if (ch === "`") {
557
+ out += ch;
558
+ i += 1;
559
+ modeStack.push(mode);
560
+ mode = "template";
561
+ continue;
562
+ }
563
+ resolveRe.lastIndex = i;
564
+ const resolveMatch = resolveRe.exec(transformedCode);
565
+ if (resolveMatch) {
566
+ const spec = resolveMatch[2];
567
+ const resolvedUrl = pathToFileURL(path.resolve(path.dirname(normalizedPhysicalId), spec)).href;
568
+ out += JSON.stringify(resolvedUrl);
569
+ i = resolveRe.lastIndex;
570
+ replacedImportMeta = true;
571
+ continue;
572
+ }
573
+ urlRe.lastIndex = i;
574
+ if (urlRe.test(transformedCode)) {
575
+ out += JSON.stringify(url);
576
+ i = urlRe.lastIndex;
577
+ replacedImportMeta = true;
578
+ continue;
579
+ }
580
+ dirnameRe.lastIndex = i;
581
+ if (dirnameRe.test(transformedCode)) {
582
+ out += JSON.stringify(dir);
583
+ i = dirnameRe.lastIndex;
584
+ replacedImportMeta = true;
585
+ continue;
586
+ }
587
+ filenameRe.lastIndex = i;
588
+ if (filenameRe.test(transformedCode)) {
589
+ out += JSON.stringify(file);
590
+ i = filenameRe.lastIndex;
591
+ replacedImportMeta = true;
592
+ continue;
593
+ }
594
+ out += ch;
595
+ i += 1;
596
+ }
597
+ if (replacedImportMeta) transformedCode = out;
598
+ }
599
+ if (prologueLines.length > 0) transformedCode = `${prologueLines.join("\n")}\n${transformedCode}`;
600
+ if (transformedCode !== code) return { code: transformedCode };
601
+ }
602
+ return null;
603
+ }
604
+ }
605
+ };
606
+ }
607
+ async function bundle(options) {
608
+ const resolvedTsconfigPath = path.resolve(process.cwd(), "tsconfig.json");
609
+ const tsconfig = existsSync(resolvedTsconfigPath) ? resolvedTsconfigPath : void 0;
610
+ const inputOptions = {
611
+ input: options.path,
612
+ platform: "node",
613
+ external: createExternalResolver(options),
614
+ plugins: [
615
+ createMakeCjsWrapperAsyncFriendlyPlugin(),
616
+ createRequireResolveFix(options),
617
+ createSourceContextShimsPlugin(),
618
+ ...options.preset === "jiti" ? [
619
+ createConsoleOutputCustomizer(),
620
+ createJsonLoader(),
621
+ createRequireTypeofFix()
622
+ ] : []
623
+ ],
624
+ transform: { define: {
625
+ __dirname: JSON.stringify(path.dirname(options.path)),
626
+ __filename: JSON.stringify(options.path),
627
+ "import.meta.url": JSON.stringify(pathToFileURL(options.path).href),
628
+ "import.meta.filename": JSON.stringify(options.path),
629
+ "import.meta.dirname": JSON.stringify(path.dirname(options.path)),
630
+ "import.meta.env": "process.env"
631
+ } },
632
+ logLevel: "silent",
633
+ ...options.inputOptions
634
+ };
635
+ if (tsconfig) inputOptions.tsconfig = tsconfig;
636
+ const bundle = await rolldown(inputOptions);
637
+ const outputOptions = {
638
+ format: "esm",
639
+ codeSplitting: false,
640
+ keepNames: true,
641
+ ...options.preset === "bundle-require" ? { generatedCode: { symbols: false } } : {},
642
+ ...options.outputOptions
643
+ };
644
+ const rolldownOutput = await bundle.generate(outputOptions);
645
+ if (!rolldownOutput.output[0]) throw new Error("[unrun] No output chunk found");
646
+ const files = await bundle.watchFiles;
647
+ return {
648
+ chunk: rolldownOutput.output[0],
649
+ dependencies: files
650
+ };
651
+ }
652
+ /**
653
+ * Clean the module file at the given URL.
654
+ * Deletes the file if it exists.
655
+ * @param moduleUrl - The URL of the module file to be cleaned.
656
+ * @param options - Resolved options.
657
+ */
658
+ function cleanModule(moduleUrl, options) {
659
+ if (options.debug) return;
660
+ try {
661
+ if (moduleUrl.startsWith("file://")) {
662
+ const filePath = new URL(moduleUrl);
663
+ fs.unlinkSync(filePath);
664
+ }
665
+ } catch (error) {
666
+ if (error.code !== "ENOENT") throw error;
667
+ }
668
+ }
669
+ function sanitize(name) {
670
+ return name.replaceAll(/[^\w.-]/g, "_");
671
+ }
672
+ /**
673
+ * Writes a module to the filesystem.
674
+ * @param code - The JavaScript code to be written as a module.
675
+ * @param options - Resolved options.
676
+ * @returns The file URL of the written module.
677
+ */
678
+ function writeModule(code, options) {
679
+ const filenameHint = path.basename(options.path);
680
+ let moduleUrl = "";
681
+ try {
682
+ const randomKey = crypto.randomBytes(16).toString("hex");
683
+ const fname = `${filenameHint ? `${sanitize(filenameHint)}.` : ""}${randomKey}.mjs`;
684
+ const projectNodeModules = path.join(process.cwd(), "node_modules");
685
+ const outDir = path.join(projectNodeModules, ".unrun");
686
+ const outFile = path.join(outDir, fname);
687
+ if (!fs.existsSync(outFile)) try {
688
+ fs.mkdirSync(outDir, { recursive: true });
689
+ fs.writeFileSync(outFile, code, "utf8");
690
+ } catch {
691
+ const fallbackDir = path.join(tmpdir(), "unrun-cache");
692
+ const fallbackFile = path.join(fallbackDir, fname);
693
+ fs.mkdirSync(fallbackDir, { recursive: true });
694
+ fs.writeFileSync(fallbackFile, code, "utf8");
695
+ moduleUrl = pathToFileURL(fallbackFile).href;
696
+ }
697
+ moduleUrl = moduleUrl || pathToFileURL(outFile).href;
698
+ } catch {
699
+ moduleUrl = `data:text/javascript;base64,${Buffer.from(code).toString("base64")}`;
700
+ }
701
+ return moduleUrl;
702
+ }
703
+ /**
704
+ * Import a JS module from code string.
705
+ * Write ESM code to a temp file (prefer project-local node_modules/.unrun) and import it.
706
+ * @param code - The JavaScript code to be imported as a module.
707
+ * @param options - Resolved options.
708
+ * @returns The imported module.
709
+ */
710
+ async function loadModule(code, options) {
711
+ const moduleUrl = writeModule(code, options);
712
+ let _module;
713
+ try {
714
+ _module = await import(moduleUrl);
715
+ } finally {
716
+ cleanModule(moduleUrl, options);
717
+ }
718
+ return _module;
719
+ }
720
+ /**
721
+ * Loads a module with JIT transpilation based on the provided options.
722
+ *
723
+ * @param options - The options for loading the module.
724
+ * @returns A promise that resolves to the loaded module.
725
+ */
726
+ async function unrun(options) {
727
+ const resolvedOptions = resolveOptions(options);
728
+ const output = await bundle(resolvedOptions);
729
+ let module;
730
+ try {
731
+ module = await loadModule(output.chunk.code, resolvedOptions);
732
+ } catch (error) {
733
+ throw new Error(`[unrun] Import failed (code length: ${output.chunk.code.length}): ${error.message}`);
734
+ }
735
+ return {
736
+ module: preset(resolvedOptions, module),
737
+ dependencies: output.dependencies
738
+ };
739
+ }
740
+
741
+ //#endregion
742
+ export { unrun };