unrun 0.2.36 → 0.2.38

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/README.md CHANGED
@@ -28,21 +28,21 @@ npx unrun ./path/to/file.ts
28
28
  - Async
29
29
 
30
30
  ```ts
31
- import { unrun } from 'unrun'
31
+ import { unrun } from "unrun";
32
32
 
33
33
  const { module } = await unrun({
34
- path: './path/to/file.ts', // Path to the module to load
35
- })
34
+ path: "./path/to/file.ts", // Path to the module to load
35
+ });
36
36
  ```
37
37
 
38
38
  - Sync
39
39
 
40
40
  ```ts
41
- import { unrunSync } from 'unrun'
41
+ import { unrunSync } from "unrun";
42
42
 
43
43
  const { module } = unrunSync({
44
- path: './path/to/file.ts', // Path to the module to load
45
- })
44
+ path: "./path/to/file.ts", // Path to the module to load
45
+ });
46
46
  ```
47
47
 
48
48
  ## Credits
package/package.json CHANGED
@@ -1,56 +1,45 @@
1
1
  {
2
2
  "name": "unrun",
3
- "type": "module",
4
- "version": "0.2.36",
3
+ "version": "0.2.38",
5
4
  "description": "A tool to load and execute any JavaScript or TypeScript code at runtime.",
6
- "author": "Augustin Mercier <gugustinette@proton.me>",
7
- "license": "MIT",
8
- "funding": "https://github.com/sponsors/Gugustinette",
9
5
  "homepage": "https://gugustinette.github.io/unrun/",
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/Gugustinette/unrun.git"
13
- },
14
6
  "bugs": {
15
7
  "url": "https://github.com/Gugustinette/unrun/issues"
16
8
  },
17
- "exports": {
18
- ".": "./dist/index.mjs",
19
- "./package.json": "./package.json"
9
+ "license": "MIT",
10
+ "author": "Augustin Mercier <gugustinette@proton.me>",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/Gugustinette/unrun.git"
20
14
  },
21
- "main": "./dist/index.mjs",
22
- "module": "./dist/index.mjs",
23
- "types": "./dist/index.d.mts",
15
+ "funding": "https://github.com/sponsors/Gugustinette",
24
16
  "bin": {
25
17
  "unrun": "./dist/cli.mjs"
26
18
  },
27
19
  "files": [
28
20
  "dist"
29
21
  ],
22
+ "type": "module",
23
+ "main": "./dist/index.mjs",
24
+ "module": "./dist/index.mjs",
25
+ "types": "./dist/index.d.mts",
26
+ "exports": {
27
+ ".": "./dist/index.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
30
  "publishConfig": {
31
31
  "access": "public"
32
32
  },
33
- "engines": {
34
- "node": ">=20.19.0"
35
- },
36
- "peerDependencies": {
37
- "synckit": "^0.11.11"
38
- },
39
- "peerDependenciesMeta": {
40
- "synckit": {
41
- "optional": true
42
- }
43
- },
44
33
  "dependencies": {
45
- "rolldown": "1.0.0-rc.16"
34
+ "rolldown": "^1.0.0"
46
35
  },
47
36
  "devDependencies": {
48
- "@sxzz/eslint-config": "^7.8.4",
37
+ "@sxzz/eslint-config": "^8.0.0",
49
38
  "@sxzz/prettier-config": "^2.3.1",
50
39
  "@types/node": "^25.6.0",
51
- "@typescript/native-preview": "7.0.0-dev.20260416.1",
52
- "@vitest/browser": "4.1.4",
53
- "@vitest/browser-playwright": "4.1.4",
40
+ "@typescript/native-preview": "7.0.0-dev.20260506.1",
41
+ "@vitest/browser": "4.1.5",
42
+ "@vitest/browser-playwright": "4.1.5",
54
43
  "@webcontainer/api": "^1.6.4",
55
44
  "acorn": "^8.16.0",
56
45
  "bumpp": "^11.0.1",
@@ -60,16 +49,18 @@
60
49
  "defu": "^6.1.7",
61
50
  "destr": "^2.0.5",
62
51
  "esbuild": "^0.28.0",
63
- "eslint": "^10.2.0",
52
+ "eslint": "^10.3.0",
64
53
  "estree-walker": "^3.0.3",
65
54
  "etag": "^1.8.1",
66
55
  "fast-glob": "^3.3.3",
67
56
  "giget": "^3.2.0",
68
57
  "is-installed-globally": "^1.0.0",
69
- "jiti": "^2.6.1",
58
+ "jiti": "^2.7.0",
70
59
  "mime": "^4.1.0",
71
- "moment-timezone": "^0.6.1",
60
+ "moment-timezone": "^0.6.2",
72
61
  "nano-jsx": "^0.2.1",
62
+ "oxfmt": "^0.48.0",
63
+ "oxlint": "^1.63.0",
73
64
  "playwright": "^1.59.1",
74
65
  "preact": "^10.29.1",
75
66
  "preact-render-to-string": "^6.6.7",
@@ -79,29 +70,39 @@
79
70
  "reflect-metadata": "^0.2.2",
80
71
  "synckit": "^0.11.12",
81
72
  "test-ecosystem-ci": "^0.0.3",
82
- "tinyexec": "^1.1.1",
83
- "tsdown": "0.21.8",
73
+ "tinyexec": "^1.1.2",
74
+ "tsdown": "0.22.0",
84
75
  "tsx": "^4.21.0",
85
76
  "typedoc": "^0.28.19",
86
77
  "typedoc-plugin-markdown": "^4.11.0",
87
78
  "typedoc-vitepress-theme": "^1.1.2",
88
- "typescript": "^6.0.2",
79
+ "typescript": "^6.0.3",
89
80
  "unconfig": "^7.5.0",
90
- "unplugin-vue": "^7.1.1",
91
- "vite": "^8.0.8",
81
+ "unplugin-vue": "^7.2.0",
82
+ "vite": "^8.0.10",
92
83
  "vitepress": "2.0.0-alpha.12",
93
84
  "vitepress-plugin-group-icons": "^1.7.5",
94
- "vitest": "4.1.4",
95
- "vue": "^3.5.32",
96
- "vue-tsc": "^3.2.6",
97
- "zod": "^4.3.6"
85
+ "vitest": "4.1.5",
86
+ "vue": "^3.5.34",
87
+ "vue-tsc": "^3.2.8",
88
+ "zod": "^4.4.3"
89
+ },
90
+ "peerDependencies": {
91
+ "synckit": "^0.11.11"
92
+ },
93
+ "peerDependenciesMeta": {
94
+ "synckit": {
95
+ "optional": true
96
+ }
98
97
  },
99
98
  "prettier": "@sxzz/prettier-config",
99
+ "engines": {
100
+ "node": "^22.13.0 || >=24.0.0"
101
+ },
100
102
  "scripts": {
101
- "lint": "eslint --no-cache .",
102
- "lint:fix": "pnpm run lint --fix",
103
103
  "build": "tsdown",
104
104
  "dev": "tsdown --watch",
105
+ "playground": "node ./playground/build.mjs",
105
106
  "pretest": "pnpm run build && node ./scripts/manage-pnpm-override.mjs add",
106
107
  "test": "vitest",
107
108
  "pretest:browser": "pnpm run build",
@@ -114,8 +115,11 @@
114
115
  "ecosystem-ci:force": "ecosystem-ci --force",
115
116
  "test:update-fixtures": "node ./dist/cli.mjs ./scripts/update-fixtures.ts",
116
117
  "benchmark": "tsdown -c benchmark/tsdown.config.ts && node ./benchmark/dist/benchmark.mjs",
118
+ "lint": "oxlint",
119
+ "lint:fix": "oxlint --fix",
120
+ "fmt": "oxfmt",
121
+ "fmt:check": "oxfmt --check",
117
122
  "typecheck": "tsgo --noEmit",
118
- "format": "prettier --cache --write .",
119
123
  "release": "bumpp",
120
124
  "docs:dev": "vitepress dev docs",
121
125
  "docs:build": "vitepress build docs",
package/dist/cli.d.mts DELETED
@@ -1 +0,0 @@
1
- export { };
package/dist/cli.mjs DELETED
@@ -1,103 +0,0 @@
1
- #!/usr/bin/env node
2
- import process from "node:process";
3
- //#region src/cli.ts
4
- function parseCLIArguments(argv) {
5
- let debug = false;
6
- let preset;
7
- let filePath;
8
- const beforeArgs = [];
9
- const afterArgs = [];
10
- let expectFilePathAfterDelimiter = false;
11
- for (let index = 0; index < argv.length; index += 1) {
12
- const argument = argv[index];
13
- if (filePath !== void 0) {
14
- if (argument === "--") {
15
- afterArgs.push(...argv.slice(index + 1));
16
- break;
17
- }
18
- afterArgs.push(argument);
19
- continue;
20
- }
21
- if (expectFilePathAfterDelimiter) {
22
- filePath = argument;
23
- expectFilePathAfterDelimiter = false;
24
- continue;
25
- }
26
- if (argument === "--") {
27
- expectFilePathAfterDelimiter = true;
28
- beforeArgs.push(argument);
29
- continue;
30
- }
31
- if (argument === "--debug") {
32
- debug = true;
33
- beforeArgs.push(argument);
34
- continue;
35
- }
36
- if (argument === "--no-debug") {
37
- debug = false;
38
- beforeArgs.push(argument);
39
- continue;
40
- }
41
- if (argument.startsWith("--preset=")) {
42
- preset = argument.slice(9);
43
- beforeArgs.push(argument);
44
- continue;
45
- }
46
- if (argument === "--preset") {
47
- const presetValue = argv[index + 1];
48
- if (!presetValue || presetValue.startsWith("-")) throw new Error("[unrun] Missing preset value after --preset");
49
- preset = presetValue;
50
- beforeArgs.push(argument, presetValue);
51
- index += 1;
52
- continue;
53
- }
54
- if (argument.startsWith("-")) {
55
- beforeArgs.push(argument);
56
- continue;
57
- }
58
- filePath = argument;
59
- }
60
- return {
61
- debug,
62
- preset,
63
- filePath,
64
- beforeArgs,
65
- afterArgs
66
- };
67
- }
68
- async function runCLI() {
69
- let parsedArguments;
70
- try {
71
- parsedArguments = parseCLIArguments(process.argv.slice(2));
72
- } catch (error) {
73
- console.error(error.message);
74
- process.exit(1);
75
- }
76
- if (!parsedArguments.filePath) {
77
- console.error("[unrun] No input files provided");
78
- process.exit(1);
79
- }
80
- process.argv = [
81
- process.argv[0],
82
- parsedArguments.filePath,
83
- ...parsedArguments.afterArgs
84
- ];
85
- try {
86
- const { unrunCli } = await import("./index.mjs");
87
- const cliResult = await unrunCli({
88
- path: parsedArguments.filePath,
89
- debug: parsedArguments.debug,
90
- preset: parsedArguments.preset
91
- }, parsedArguments.afterArgs);
92
- process.exit(cliResult.exitCode);
93
- } catch (error) {
94
- console.error(error.message);
95
- process.exit(1);
96
- }
97
- }
98
- runCLI().catch((error) => {
99
- console.error(error.message);
100
- process.exit(1);
101
- });
102
- //#endregion
103
- export {};
package/dist/index.d.mts DELETED
@@ -1,81 +0,0 @@
1
- import { InputOptions, OutputOptions } from "rolldown";
2
-
3
- //#region src/options.d.ts
4
- interface Options {
5
- /**
6
- * The path to the file to be imported. Supports filesystem paths, file URLs or URL objects.
7
- * @default 'index.ts'
8
- */
9
- path?: string | URL;
10
- /**
11
- * Debug mode.
12
- * Wether or not to keep temporary files to help with debugging.
13
- * Temporary files are stored in `node_modules/.unrun/` if possible,
14
- * otherwise in the OS temporary directory.
15
- * @default false
16
- */
17
- debug?: boolean;
18
- /**
19
- * The preset to use for bundling and output format.
20
- * @default 'none'
21
- */
22
- preset?: "none" | "jiti" | "bundle-require";
23
- /**
24
- * Additional rolldown input options. These options will be merged with the
25
- * defaults provided by unrun, with these options always taking precedence.
26
- */
27
- inputOptions?: InputOptions;
28
- /**
29
- * Additional rolldown output options. These options will be merged with the
30
- * defaults provided by unrun, with these options always taking precedence.
31
- */
32
- outputOptions?: OutputOptions;
33
- }
34
- //#endregion
35
- //#region src/types.d.ts
36
- interface Result<T = unknown> {
37
- /**
38
- * The module that was loaded.
39
- * You can specify the type of the module by providing a type argument when using the `unrun` function.
40
- */
41
- module: T;
42
- /**
43
- * The dependencies involved when loading the targeted module.
44
- * Note: this only includes local file dependencies, npm-resolved dependencies are excluded.
45
- */
46
- dependencies: string[];
47
- }
48
- interface CliResult {
49
- /**
50
- * The exit code of the CLI execution.
51
- */
52
- exitCode: number;
53
- }
54
- //#endregion
55
- //#region src/index.d.ts
56
- /**
57
- * Loads a module with JIT transpilation based on the provided options.
58
- *
59
- * @param options - The options for loading the module.
60
- * @returns A promise that resolves to the loaded module.
61
- */
62
- declare function unrun<T>(options: Options): Promise<Result<T>>;
63
- /**
64
- * Loads a module with JIT transpilation based on the provided options.
65
- * This function runs synchronously using a worker thread.
66
- *
67
- * @param options - The options for loading the module.
68
- * @returns The loaded module.
69
- */
70
- declare function unrunSync<T>(options: Options): Result<T>;
71
- /**
72
- * Runs a given module with JIT transpilation based on the provided options.
73
- * This function does not return the module, as it simply executes it.
74
- * Corresponds to the CLI behavior.
75
- *
76
- * @param options - The options for running the module.
77
- * @param args - Additional command-line arguments to pass to the module.
78
- */
79
- declare function unrunCli(options: Options, args?: string[]): Promise<CliResult>;
80
- //#endregion
81
- export { type CliResult, type Options, type Result, unrun, unrunCli, unrunSync };
package/dist/index.mjs DELETED
@@ -1,2 +0,0 @@
1
- import { n as unrunCli, r as unrunSync, t as unrun } from "./src-GU5PtktT.mjs";
2
- export { unrun, unrunCli, unrunSync };
@@ -1,887 +0,0 @@
1
- import { builtinModules, createRequire } from "node:module";
2
- import path from "node:path";
3
- import fs, { existsSync } from "node:fs";
4
- import process from "node:process";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
6
- import { rolldown } from "rolldown";
7
- import { Buffer as Buffer$1 } from "node:buffer";
8
- import { spawn } from "node:child_process";
9
- import crypto from "node:crypto";
10
- import { tmpdir } from "node:os";
11
- //#region \0rolldown/runtime.js
12
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
13
- //#endregion
14
- //#region src/features/preset.ts
15
- /**
16
- * Applies preset-specific handling to the loaded module.
17
- */
18
- function preset(options, module) {
19
- if (options.preset === "bundle-require") return module;
20
- if (options.preset === "jiti") {
21
- const ext = path.extname(options.path);
22
- if (module && typeof module === "object" && module[Symbol.toStringTag] === "Module" && Object.keys(module).length === 0) return ext === ".mjs" ? module : {};
23
- }
24
- if (module && typeof module === "object" && "default" in module) return module.default;
25
- return module;
26
- }
27
- //#endregion
28
- //#region src/utils/normalize-path.ts
29
- /**
30
- * Normalize a path-like input to a string path.
31
- * @param pathLike The path-like input (string or URL).
32
- * @returns The normalized string path.
33
- */
34
- function normalizePath(pathLike) {
35
- if (!pathLike) return "index.ts";
36
- if (pathLike instanceof URL) {
37
- if (pathLike.protocol === "file:") return fileURLToPath(pathLike);
38
- return pathLike.href;
39
- }
40
- if (typeof pathLike === "string") {
41
- if (!pathLike.startsWith("file:")) return pathLike;
42
- try {
43
- return fileURLToPath(pathLike);
44
- } catch {
45
- try {
46
- return fileURLToPath(new URL(pathLike));
47
- } catch {
48
- return pathLike;
49
- }
50
- }
51
- }
52
- return String(pathLike);
53
- }
54
- //#endregion
55
- //#region src/options.ts
56
- function resolveOptions(options = {}) {
57
- const resolvedOptions = {
58
- path: path.resolve(process.cwd(), normalizePath(options.path)),
59
- debug: options.debug || false,
60
- preset: options.preset || "none",
61
- inputOptions: options.inputOptions,
62
- outputOptions: options.outputOptions
63
- };
64
- if (!fs.existsSync(resolvedOptions.path)) throw new Error(`[unrun] File not found: ${resolvedOptions.path}`);
65
- if (!new Set([
66
- "none",
67
- "jiti",
68
- "bundle-require"
69
- ]).has(resolvedOptions.preset)) throw new Error(`[unrun] Invalid preset "${resolvedOptions.preset}" (expected: none | jiti | bundle-require)`);
70
- return resolvedOptions;
71
- }
72
- //#endregion
73
- //#region src/utils/module-resolution.ts
74
- /**
75
- * Precomputed set of Node.js builtin module specifiers, including both plain and `node:` prefixed forms.
76
- */
77
- const BUILTIN_MODULE_SPECIFIERS = new Set([...builtinModules, ...builtinModules.map((name) => `node:${name}`)]);
78
- /**
79
- * Returns true when `id` refers to a Node.js builtin module, accepting both plain and `node:` specifiers.
80
- */
81
- function isBuiltinModuleSpecifier(id) {
82
- if (!id) return false;
83
- return BUILTIN_MODULE_SPECIFIERS.has(id) || id.startsWith("node:");
84
- }
85
- //#endregion
86
- //#region src/features/external.ts
87
- /**
88
- * Builds the rolldown external resolver used to decide which imports remain external.
89
- * Treat bare imports from the primary node_modules as external, but inline
90
- * nested node_modules so they keep working once executed from .unrun.
91
- */
92
- function createExternalResolver(options) {
93
- const entryDir = path.dirname(options.path);
94
- const canResolveFromEntry = (specifier) => {
95
- const packageName = getPackageName(specifier);
96
- if (!packageName) return false;
97
- let currentDir = entryDir;
98
- while (true) {
99
- if (existsSync(path.join(currentDir, "node_modules", packageName))) return true;
100
- const parentDir = path.dirname(currentDir);
101
- if (parentDir === currentDir) break;
102
- currentDir = parentDir;
103
- }
104
- return false;
105
- };
106
- return function external(id) {
107
- if (!id || id.startsWith("\0")) return false;
108
- if (id.startsWith(".") || id.startsWith("#") || path.isAbsolute(id)) return false;
109
- if (isBuiltinModuleSpecifier(id)) return true;
110
- if (!canResolveFromEntry(id)) return false;
111
- return true;
112
- };
113
- }
114
- function getPackageName(specifier) {
115
- if (!specifier) return void 0;
116
- if (specifier.startsWith("@")) {
117
- const segments = specifier.split("/");
118
- if (segments.length >= 2) return `${segments[0]}/${segments[1]}`;
119
- return;
120
- }
121
- const [name] = specifier.split("/");
122
- return name || void 0;
123
- }
124
- //#endregion
125
- //#region src/plugins/console-output-customizer.ts
126
- const INSPECT_HELPER_SNIPPET = `(function(){
127
- function __unrun__fmt(names, getter, np){
128
- var onlyDefault = names.length === 1 && names[0] === "default";
129
- var o = np ? Object.create(null) : {};
130
- for (var i = 0; i < names.length; i++) {
131
- var n = names[i];
132
- try { o[n] = getter(n) } catch {}
133
- }
134
- if (onlyDefault) {
135
- try {
136
- var s = JSON.stringify(o.default);
137
- if (s !== undefined) {
138
- s = s.replace(/"([^"]+)":/g, "$1: ").replace(/,/g, ", ").replace(/{/g, "{ ").replace(/}/g, " }");
139
- return "[Module: null prototype] { default: " + s + " }";
140
- }
141
- } catch {}
142
- return "[Module: null prototype] { default: " + String(o.default) + " }";
143
- }
144
- return o;
145
- }
146
- function __unrun__setInspect(obj, names, getter, np){
147
- try {
148
- var __insp = Symbol.for('nodejs.util.inspect.custom');
149
- Object.defineProperty(obj, __insp, {
150
- value: function(){ return __unrun__fmt(names, getter, np) },
151
- enumerable: false, configurable: true
152
- });
153
- } catch {}
154
- return obj;
155
- }
156
- try {
157
- Object.defineProperty(globalThis, "__unrun__setInspect", {
158
- value: __unrun__setInspect,
159
- enumerable: false,
160
- });
161
- } catch {}
162
- })();`;
163
- const WRAPPER_SNIPPET = `(function __unrun__wrapRolldownHelpers(){
164
- if (typeof __unrun__setInspect !== "function") return;
165
- if (typeof __export === "function" && !__export.__unrunPatched) {
166
- var __unrun__origExport = __export;
167
- var __unrun__patchedExport = (...__unrun__args) => {
168
- var __unrun__target = __unrun__origExport(...__unrun__args);
169
- if (__unrun__target && typeof __unrun__target === "object") {
170
- try {
171
- var __unrun__map = (__unrun__args[0] && typeof __unrun__args[0] === "object") ? __unrun__args[0] : {};
172
- var __unrun__names = Object.keys(__unrun__map).filter(function(n){ return n !== "__esModule" });
173
- __unrun__setInspect(
174
- __unrun__target,
175
- __unrun__names,
176
- function(n){
177
- var getter = __unrun__map[n];
178
- return typeof getter === "function" ? getter() : getter;
179
- },
180
- false,
181
- );
182
- } catch {}
183
- }
184
- return __unrun__target;
185
- };
186
- __unrun__patchedExport.__unrunPatched = true;
187
- __export = __unrun__patchedExport;
188
- }
189
- if (typeof __exportAll === "function" && !__exportAll.__unrunPatched) {
190
- var __unrun__origExportAll = __exportAll;
191
- var __unrun__patchedExportAll = (...__unrun__args) => {
192
- var __unrun__target = __unrun__origExportAll(...__unrun__args);
193
- if (__unrun__target && typeof __unrun__target === "object") {
194
- try {
195
- var __unrun__map = (__unrun__args[0] && typeof __unrun__args[0] === "object") ? __unrun__args[0] : {};
196
- var __unrun__names = Object.keys(__unrun__map).filter(function(n){ return n !== "__esModule" });
197
- __unrun__setInspect(
198
- __unrun__target,
199
- __unrun__names,
200
- function(n){
201
- var getter = __unrun__map[n];
202
- return typeof getter === "function" ? getter() : getter;
203
- },
204
- false,
205
- );
206
- } catch {}
207
- }
208
- return __unrun__target;
209
- };
210
- __unrun__patchedExportAll.__unrunPatched = true;
211
- __exportAll = __unrun__patchedExportAll;
212
- }
213
- if (typeof __copyProps === "function" && !__copyProps.__unrunPatched) {
214
- var __unrun__origCopyProps = __copyProps;
215
- var __unrun__patchedCopyProps = (...__unrun__args) => {
216
- var __unrun__result = __unrun__origCopyProps(...__unrun__args);
217
- if (__unrun__result && typeof __unrun__result === "object") {
218
- try {
219
- var __unrun__names = Object.keys(__unrun__result).filter(function(n){ return n !== "__esModule" });
220
- __unrun__setInspect(__unrun__result, __unrun__names, function(n){ return __unrun__result[n] }, true);
221
- } catch {}
222
- }
223
- return __unrun__result;
224
- };
225
- __unrun__patchedCopyProps.__unrunPatched = true;
226
- __copyProps = __unrun__patchedCopyProps;
227
- }
228
- })();`;
229
- const HELPER_DECLARATION_PATTERN = /__unrun__setInspect\b/;
230
- const WRAPPER_MARKER = "__unrun__wrapRolldownHelpers";
231
- function createConsoleOutputCustomizer() {
232
- return {
233
- name: "unrun-console-output-customizer",
234
- generateBundle: { handler(_, bundle) {
235
- for (const chunk of Object.values(bundle)) {
236
- if (chunk.type !== "chunk") continue;
237
- injectInspectHelper(chunk);
238
- injectHelperWrappers(chunk);
239
- }
240
- } }
241
- };
242
- }
243
- function injectInspectHelper(chunk) {
244
- if (HELPER_DECLARATION_PATTERN.test(chunk.code)) return;
245
- chunk.code = chunk.code.startsWith("#!") ? insertAfterShebang(chunk.code, `${INSPECT_HELPER_SNIPPET}\n`) : `${INSPECT_HELPER_SNIPPET}\n${chunk.code}`;
246
- }
247
- function injectHelperWrappers(chunk) {
248
- if (chunk.code.includes(WRAPPER_MARKER)) return;
249
- const insertIndex = findRuntimeBoundary(chunk.code);
250
- const snippet = `${WRAPPER_SNIPPET}\n`;
251
- if (insertIndex === -1) {
252
- chunk.code = `${chunk.code}\n${snippet}`;
253
- return;
254
- }
255
- chunk.code = `${chunk.code.slice(0, insertIndex)}${snippet}${chunk.code.slice(insertIndex)}`;
256
- }
257
- function findRuntimeBoundary(code) {
258
- const markerIndex = code.indexOf("//#endregion");
259
- if (markerIndex === -1) return -1;
260
- const newlineIndex = code.indexOf("\n", markerIndex);
261
- return newlineIndex === -1 ? code.length : newlineIndex + 1;
262
- }
263
- function insertAfterShebang(code, insertion) {
264
- const nl = code.indexOf("\n");
265
- if (nl === -1) return `${code}\n${insertion}`;
266
- return `${code.slice(0, nl + 1)}${insertion}${code.slice(nl + 1)}`;
267
- }
268
- //#endregion
269
- //#region src/plugins/json-loader.ts
270
- /**
271
- * Minimal JSON loader to mimic jiti/Node behavior expected by tests:
272
- * - Default export is the parsed JSON object
273
- * - Also add a self-reference `default` property on the object (so obj.default === obj)
274
- * - Provide named exports for top-level properties
275
- */
276
- function createJsonLoader() {
277
- return {
278
- name: "unrun-json-loader",
279
- resolveId: { handler(source, importer) {
280
- if (!source.endsWith(".json")) return null;
281
- const basedir = importer ? path.dirname(importer) : process.cwd();
282
- const resolved = path.resolve(basedir, source);
283
- let isRequire = false;
284
- try {
285
- if (importer) {
286
- const src = fs.readFileSync(importer, "utf8");
287
- const escaped = source.replaceAll(/[.*+?^${}()|[\]\\]/g, (m) => `\\${m}`);
288
- const pattern = String.raw`\brequire\s*\(\s*['"]${escaped}['"]\s*\)`;
289
- isRequire = new RegExp(pattern).test(src);
290
- }
291
- } catch {}
292
- return { id: `${resolved}?unrun-json.${isRequire ? "cjs" : "mjs"}` };
293
- } },
294
- load: {
295
- filter: { id: /\?unrun-json\.(?:mjs|cjs)$/ },
296
- handler(id) {
297
- try {
298
- const realId = id.replace(/\?unrun-json\.(?:mjs|cjs)$/, "");
299
- const src = fs.readFileSync(realId, "utf8");
300
- const data = JSON.parse(src);
301
- const jsonLiteral = JSON.stringify(data);
302
- 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` };
303
- const named = Object.keys(data).filter((k) => /^[$A-Z_]\w*$/i.test(k)).map((k) => `export const ${k} = __data[${JSON.stringify(k)}]`).join("\n");
304
- return { code: [
305
- `const __data = ${jsonLiteral}`,
306
- `try { Object.defineProperty(__data, 'default', { value: __data, enumerable: false, configurable: true }) } catch {}`,
307
- named,
308
- `export default __data`
309
- ].filter(Boolean).join("\n") };
310
- } catch {
311
- return null;
312
- }
313
- }
314
- }
315
- };
316
- }
317
- //#endregion
318
- //#region src/plugins/make-cjs-wrapper-async-friendly.ts
319
- /**
320
- * Transforms code strings containing CommonJS wrappers to be async-friendly.
321
- *
322
- * Rolldown may wrap CommonJS modules in a `__commonJS` function that uses
323
- * arrow functions. If the wrapped code contains top-level `await`, this can lead
324
- * to syntax errors since the callback function won't be marked as `async`.
325
- * This function scans for such patterns and modifies the arrow functions to
326
- * be `async` if they contain `await` expressions.
327
- */
328
- function createMakeCjsWrapperAsyncFriendlyPlugin() {
329
- return {
330
- name: "unrun-make-cjs-wrapper-async-friendly",
331
- generateBundle: { handler(_outputOptions, bundle) {
332
- for (const chunk of Object.values(bundle)) {
333
- if (chunk.type !== "chunk") continue;
334
- let code = chunk.code;
335
- const wrapperMarkers = ["__commonJS({", "__commonJSMin("];
336
- if (!wrapperMarkers.some((marker) => code.includes(marker))) continue;
337
- const arrowToken = "(() => {";
338
- const asyncArrowToken = "(async () => {";
339
- const patchMarker = (marker) => {
340
- let pos = 0;
341
- while (true) {
342
- const markerIdx = code.indexOf(marker, pos);
343
- if (markerIdx === -1) break;
344
- const fnStart = code.indexOf(arrowToken, markerIdx);
345
- if (fnStart === -1) {
346
- pos = markerIdx + marker.length;
347
- continue;
348
- }
349
- const bodyStart = fnStart + 8;
350
- let i = bodyStart;
351
- let depth = 1;
352
- while (i < code.length && depth > 0) {
353
- const ch = code[i++];
354
- if (ch === "{") depth++;
355
- else if (ch === "}") depth--;
356
- }
357
- if (depth !== 0) break;
358
- const bodyEnd = i - 1;
359
- const body = code.slice(bodyStart, bodyEnd);
360
- if (/\bawait\b/.test(body) && code.slice(fnStart, fnStart + 14) !== asyncArrowToken) {
361
- code = `${code.slice(0, fnStart + 1)}async ${code.slice(fnStart + 1)}`;
362
- pos = fnStart + 1 + 6;
363
- continue;
364
- }
365
- pos = bodyEnd;
366
- }
367
- };
368
- for (const marker of wrapperMarkers) patchMarker(marker);
369
- if (code !== chunk.code) chunk.code = code;
370
- }
371
- } }
372
- };
373
- }
374
- //#endregion
375
- //#region src/plugins/require-resolve-fix.ts
376
- /**
377
- * Fix require.resolve calls to use the correct base path.
378
- * Replace __require.resolve("./relative") with proper resolution from original file location.
379
- */
380
- function createRequireResolveFix(options) {
381
- return {
382
- name: "unrun-require-resolve-fix",
383
- generateBundle: { handler(_, bundle) {
384
- for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/__require\.resolve\(["']([^"']+)["']\)/g, (match, id) => {
385
- if (id.startsWith("./") || id.startsWith("../")) try {
386
- const baseDir = path.dirname(options.path);
387
- for (const ext of [
388
- "",
389
- ".ts",
390
- ".js",
391
- ".mts",
392
- ".mjs",
393
- ".cts",
394
- ".cjs"
395
- ]) {
396
- const testPath = path.resolve(baseDir, id + ext);
397
- if (fs.existsSync(testPath)) return JSON.stringify(testPath);
398
- }
399
- const resolvedPath = path.resolve(baseDir, id);
400
- return JSON.stringify(resolvedPath);
401
- } catch {
402
- return match;
403
- }
404
- return match;
405
- });
406
- } }
407
- };
408
- }
409
- //#endregion
410
- //#region src/plugins/require-typeof-fix.ts
411
- /**
412
- * Ensure typeof require in ESM stays undefined to match jiti behavior.
413
- * Replaces typeof __require with typeof require to maintain compatibility.
414
- */
415
- function createRequireTypeofFix() {
416
- return {
417
- name: "unrun-require-typeof-fix",
418
- generateBundle: { handler(_, bundle) {
419
- for (const chunk of Object.values(bundle)) if (chunk.type === "chunk") chunk.code = chunk.code.replaceAll(/\btypeof\s+__require\b/g, "typeof require");
420
- } }
421
- };
422
- }
423
- //#endregion
424
- //#region src/plugins/source-context-shims.ts
425
- /**
426
- * A rolldown plugin that injects source context shims:
427
- * - Replaces import.meta.resolve calls with resolved file URLs
428
- * - Injects per-module __filename/__dirname
429
- * - Replaces import.meta.url with the source file URL
430
- * - Replaces import.meta.dirname/import.meta.filename with source paths
431
- */
432
- function createSourceContextShimsPlugin() {
433
- return {
434
- name: "unrun-source-context-shims",
435
- load: {
436
- filter: { id: /\.(?:m?[jt]s|c?tsx?)(?:$|\?)/ },
437
- handler(id) {
438
- const physicalId = id.split("?")[0].split("#")[0];
439
- const normalizedPhysicalId = path.normalize(physicalId);
440
- let code;
441
- try {
442
- code = fs.readFileSync(normalizedPhysicalId, "utf8");
443
- } catch {
444
- return null;
445
- }
446
- if (normalizedPhysicalId.replaceAll("\\", "/").includes("/node_modules/")) return null;
447
- const file = normalizedPhysicalId;
448
- const dir = path.dirname(normalizedPhysicalId);
449
- const url = pathToFileURL(normalizedPhysicalId).href;
450
- const hasImportMeta = code.includes("import.meta");
451
- const usesFilename = /\b__filename\b/.test(code);
452
- const declaresFilename = /\b(?:const|let|var)\s+__filename\b/.test(code);
453
- const usesDirname = /\b__dirname\b/.test(code);
454
- const declaresDirname = /\b(?:const|let|var)\s+__dirname\b/.test(code);
455
- const needsFilenameShim = usesFilename && !declaresFilename;
456
- const needsDirnameShim = usesDirname && !declaresDirname;
457
- if (needsFilenameShim || needsDirnameShim || hasImportMeta) {
458
- const prologueLines = [];
459
- if (needsFilenameShim) prologueLines.push(`const __filename = ${JSON.stringify(file)}`);
460
- if (needsDirnameShim) prologueLines.push(`const __dirname = ${JSON.stringify(dir)}`);
461
- let transformedCode = code;
462
- let replacedImportMeta = false;
463
- if (hasImportMeta) {
464
- const resolveRe = /import\s*\.\s*meta\s*\.\s*resolve!?\s*\(\s*(["'])([^"']+)\1\s*\)/y;
465
- const urlRe = /import\s*\.\s*meta\s*\.\s*url\b/y;
466
- const dirnameRe = /import\s*\.\s*meta\s*\.\s*dirname\b/y;
467
- const filenameRe = /import\s*\.\s*meta\s*\.\s*filename\b/y;
468
- let out = "";
469
- let mode = "normal";
470
- const modeStack = [];
471
- let templateExprBraceDepth = 0;
472
- const popMode = () => {
473
- mode = modeStack.pop() ?? "normal";
474
- };
475
- for (let i = 0; i < transformedCode.length;) {
476
- const ch = transformedCode[i];
477
- const next = transformedCode[i + 1];
478
- if (mode === "lineComment") {
479
- out += ch;
480
- i += 1;
481
- if (ch === "\n") popMode();
482
- continue;
483
- }
484
- if (mode === "blockComment") {
485
- out += ch;
486
- i += 1;
487
- if (ch === "*" && next === "/") {
488
- out += "/";
489
- i += 1;
490
- popMode();
491
- }
492
- continue;
493
- }
494
- if (mode === "single") {
495
- out += ch;
496
- i += 1;
497
- if (ch === "\\") {
498
- out += transformedCode[i] ?? "";
499
- i += 1;
500
- continue;
501
- }
502
- if (ch === "'") popMode();
503
- continue;
504
- }
505
- if (mode === "double") {
506
- out += ch;
507
- i += 1;
508
- if (ch === "\\") {
509
- out += transformedCode[i] ?? "";
510
- i += 1;
511
- continue;
512
- }
513
- if (ch === "\"") popMode();
514
- continue;
515
- }
516
- if (mode === "template") {
517
- out += ch;
518
- i += 1;
519
- if (ch === "\\") {
520
- out += transformedCode[i] ?? "";
521
- i += 1;
522
- continue;
523
- }
524
- if (ch === "`") {
525
- popMode();
526
- continue;
527
- }
528
- if (ch === "$" && next === "{") {
529
- out += "{";
530
- i += 1;
531
- modeStack.push(mode);
532
- mode = "templateExpr";
533
- templateExprBraceDepth = 1;
534
- }
535
- continue;
536
- }
537
- if (mode === "templateExpr") {
538
- if (ch === "{") templateExprBraceDepth += 1;
539
- else if (ch === "}") {
540
- templateExprBraceDepth -= 1;
541
- if (templateExprBraceDepth === 0) {
542
- out += ch;
543
- i += 1;
544
- popMode();
545
- continue;
546
- }
547
- }
548
- }
549
- if (ch === "/" && next === "/") {
550
- out += "//";
551
- i += 2;
552
- modeStack.push(mode);
553
- mode = "lineComment";
554
- continue;
555
- }
556
- if (ch === "/" && next === "*") {
557
- out += "/*";
558
- i += 2;
559
- modeStack.push(mode);
560
- mode = "blockComment";
561
- continue;
562
- }
563
- if (ch === "'") {
564
- out += ch;
565
- i += 1;
566
- modeStack.push(mode);
567
- mode = "single";
568
- continue;
569
- }
570
- if (ch === "\"") {
571
- out += ch;
572
- i += 1;
573
- modeStack.push(mode);
574
- mode = "double";
575
- continue;
576
- }
577
- if (ch === "`") {
578
- out += ch;
579
- i += 1;
580
- modeStack.push(mode);
581
- mode = "template";
582
- continue;
583
- }
584
- resolveRe.lastIndex = i;
585
- const resolveMatch = resolveRe.exec(transformedCode);
586
- if (resolveMatch) {
587
- const spec = resolveMatch[2];
588
- const resolvedUrl = pathToFileURL(path.resolve(path.dirname(normalizedPhysicalId), spec)).href;
589
- out += JSON.stringify(resolvedUrl);
590
- i = resolveRe.lastIndex;
591
- replacedImportMeta = true;
592
- continue;
593
- }
594
- urlRe.lastIndex = i;
595
- if (urlRe.test(transformedCode)) {
596
- out += JSON.stringify(url);
597
- i = urlRe.lastIndex;
598
- replacedImportMeta = true;
599
- continue;
600
- }
601
- dirnameRe.lastIndex = i;
602
- if (dirnameRe.test(transformedCode)) {
603
- out += JSON.stringify(dir);
604
- i = dirnameRe.lastIndex;
605
- replacedImportMeta = true;
606
- continue;
607
- }
608
- filenameRe.lastIndex = i;
609
- if (filenameRe.test(transformedCode)) {
610
- out += JSON.stringify(file);
611
- i = filenameRe.lastIndex;
612
- replacedImportMeta = true;
613
- continue;
614
- }
615
- out += ch;
616
- i += 1;
617
- }
618
- if (replacedImportMeta) transformedCode = out;
619
- }
620
- if (prologueLines.length > 0) transformedCode = `${prologueLines.join("\n")}\n${transformedCode}`;
621
- if (transformedCode !== code) return { code: transformedCode };
622
- }
623
- return null;
624
- }
625
- }
626
- };
627
- }
628
- //#endregion
629
- //#region src/utils/bundle.ts
630
- async function bundle(options) {
631
- const resolvedTsconfigPath = path.resolve(process.cwd(), "tsconfig.json");
632
- const tsconfig = existsSync(resolvedTsconfigPath) ? resolvedTsconfigPath : void 0;
633
- const inputOptions = {
634
- input: options.path,
635
- platform: "node",
636
- external: createExternalResolver(options),
637
- plugins: [
638
- createMakeCjsWrapperAsyncFriendlyPlugin(),
639
- createRequireResolveFix(options),
640
- createSourceContextShimsPlugin(),
641
- ...options.preset === "jiti" ? [
642
- createConsoleOutputCustomizer(),
643
- createJsonLoader(),
644
- createRequireTypeofFix()
645
- ] : []
646
- ],
647
- transform: { define: {
648
- __dirname: JSON.stringify(path.dirname(options.path)),
649
- __filename: JSON.stringify(options.path),
650
- "import.meta.url": JSON.stringify(pathToFileURL(options.path).href),
651
- "import.meta.filename": JSON.stringify(options.path),
652
- "import.meta.dirname": JSON.stringify(path.dirname(options.path)),
653
- "import.meta.env": "process.env"
654
- } },
655
- logLevel: "silent",
656
- ...options.inputOptions
657
- };
658
- if (tsconfig) inputOptions.tsconfig = tsconfig;
659
- const bundle = await rolldown(inputOptions);
660
- const outputOptions = {
661
- format: "esm",
662
- codeSplitting: false,
663
- keepNames: true,
664
- ...options.preset === "bundle-require" ? { generatedCode: { symbols: false } } : {},
665
- ...options.outputOptions
666
- };
667
- const rolldownOutput = await bundle.generate(outputOptions);
668
- if (!rolldownOutput.output[0]) throw new Error("[unrun] No output chunk found");
669
- const files = await bundle.watchFiles;
670
- return {
671
- chunk: rolldownOutput.output[0],
672
- dependencies: files
673
- };
674
- }
675
- //#endregion
676
- //#region src/utils/module/clean-module.ts
677
- /**
678
- * Clean the module file at the given URL.
679
- * Deletes the file if it exists.
680
- * @param moduleUrl - The URL of the module file to be cleaned.
681
- * @param options - Resolved options.
682
- */
683
- function cleanModule(moduleUrl, options) {
684
- if (options.debug) return;
685
- try {
686
- if (moduleUrl.startsWith("file://")) {
687
- const filePath = new URL(moduleUrl);
688
- fs.unlinkSync(filePath);
689
- }
690
- } catch (error) {
691
- if (error.code !== "ENOENT") throw error;
692
- }
693
- }
694
- //#endregion
695
- //#region src/utils/module/exec-module.ts
696
- /**
697
- * Execute the module at the given URL, in a separate Node.js process.
698
- * @param moduleUrl - The URL of the module to execute.
699
- * @param args - Additional command-line arguments to pass to the Node.js process.
700
- * @returns A promise that resolves when the module execution is complete.
701
- */
702
- function execModule(moduleUrl, args = []) {
703
- return new Promise((resolve, reject) => {
704
- const nodePath = process.execPath;
705
- const spawnArgs = [];
706
- if (moduleUrl.startsWith("data:")) {
707
- const commaIndex = moduleUrl.indexOf(",");
708
- if (commaIndex === -1) {
709
- reject(/* @__PURE__ */ new Error("[unrun]: Invalid data URL for module execution"));
710
- return;
711
- }
712
- const metadata = moduleUrl.slice(5, commaIndex);
713
- const payload = moduleUrl.slice(commaIndex + 1);
714
- const code = metadata.endsWith(";base64") ? Buffer$1.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
715
- spawnArgs.push("--input-type=module", "--eval", code);
716
- } else {
717
- let modulePath = moduleUrl;
718
- if (moduleUrl.startsWith("file://")) try {
719
- modulePath = fileURLToPath(moduleUrl);
720
- } catch (error) {
721
- reject(/* @__PURE__ */ new Error(`[unrun]: Failed to resolve module URL ${moduleUrl}: ${error.message}`));
722
- return;
723
- }
724
- spawnArgs.push(modulePath);
725
- }
726
- const childProcess = spawn(nodePath, [...spawnArgs, ...args], { stdio: [
727
- "inherit",
728
- "inherit",
729
- "inherit"
730
- ] });
731
- const lifecycleSignals = [
732
- "SIGINT",
733
- "SIGTERM",
734
- "SIGQUIT"
735
- ];
736
- const signalListeners = /* @__PURE__ */ new Map();
737
- let exitListener;
738
- const cleanupChildProcess = (signal) => {
739
- if (childProcess.killed || childProcess.exitCode !== null) return;
740
- try {
741
- childProcess.kill(signal);
742
- } catch {}
743
- };
744
- const removeLifecycleListeners = () => {
745
- if (exitListener) {
746
- process.removeListener("exit", exitListener);
747
- exitListener = void 0;
748
- }
749
- for (const [signal, listener] of signalListeners) process.removeListener(signal, listener);
750
- signalListeners.clear();
751
- };
752
- exitListener = () => {
753
- cleanupChildProcess();
754
- };
755
- process.on("exit", exitListener);
756
- for (const signal of lifecycleSignals) {
757
- const listener = () => {
758
- cleanupChildProcess(signal);
759
- removeLifecycleListeners();
760
- process.nextTick(() => {
761
- process.kill(process.pid, signal);
762
- });
763
- };
764
- signalListeners.set(signal, listener);
765
- process.on(signal, listener);
766
- }
767
- childProcess.on("close", (exitCode) => {
768
- removeLifecycleListeners();
769
- resolve({ exitCode: exitCode ?? 0 });
770
- });
771
- childProcess.on("error", (error) => {
772
- removeLifecycleListeners();
773
- reject(/* @__PURE__ */ new Error(`[unrun]: Failed to start child process: ${error.message}`));
774
- });
775
- });
776
- }
777
- //#endregion
778
- //#region src/utils/module/write-module.ts
779
- function sanitize(name) {
780
- return name.replaceAll(/[^\w.-]/g, "_");
781
- }
782
- /**
783
- * Writes a module to the filesystem.
784
- * @param code - The JavaScript code to be written as a module.
785
- * @param options - Resolved options.
786
- * @returns The file URL of the written module.
787
- */
788
- function writeModule(code, options) {
789
- const filenameHint = path.basename(options.path);
790
- let moduleUrl = "";
791
- try {
792
- const randomKey = crypto.randomBytes(16).toString("hex");
793
- const fname = `${filenameHint ? `${sanitize(filenameHint)}.` : ""}${randomKey}.mjs`;
794
- const projectNodeModules = path.join(process.cwd(), "node_modules");
795
- const outDir = path.join(projectNodeModules, ".unrun");
796
- const outFile = path.join(outDir, fname);
797
- if (!fs.existsSync(outFile)) try {
798
- fs.mkdirSync(outDir, { recursive: true });
799
- fs.writeFileSync(outFile, code, "utf8");
800
- } catch {
801
- const fallbackDir = path.join(tmpdir(), "unrun-cache");
802
- const fallbackFile = path.join(fallbackDir, fname);
803
- fs.mkdirSync(fallbackDir, { recursive: true });
804
- fs.writeFileSync(fallbackFile, code, "utf8");
805
- moduleUrl = pathToFileURL(fallbackFile).href;
806
- }
807
- moduleUrl = moduleUrl || pathToFileURL(outFile).href;
808
- } catch {
809
- moduleUrl = `data:text/javascript;base64,${Buffer$1.from(code).toString("base64")}`;
810
- }
811
- return moduleUrl;
812
- }
813
- //#endregion
814
- //#region src/utils/module/load-module.ts
815
- /**
816
- * Import a JS module from code string.
817
- * Write ESM code to a temp file (prefer project-local node_modules/.unrun) and import it.
818
- * @param code - The JavaScript code to be imported as a module.
819
- * @param options - Resolved options.
820
- * @returns The imported module.
821
- */
822
- async function loadModule(code, options) {
823
- const moduleUrl = writeModule(code, options);
824
- let _module;
825
- try {
826
- _module = await import(moduleUrl);
827
- } finally {
828
- cleanModule(moduleUrl, options);
829
- }
830
- return _module;
831
- }
832
- //#endregion
833
- //#region src/index.ts
834
- /**
835
- * Loads a module with JIT transpilation based on the provided options.
836
- *
837
- * @param options - The options for loading the module.
838
- * @returns A promise that resolves to the loaded module.
839
- */
840
- async function unrun(options) {
841
- const resolvedOptions = resolveOptions(options);
842
- const output = await bundle(resolvedOptions);
843
- let module;
844
- try {
845
- module = await loadModule(output.chunk.code, resolvedOptions);
846
- } catch (error) {
847
- throw new Error(`[unrun] Import failed (code length: ${output.chunk.code.length}): ${error.message}`, { cause: error });
848
- }
849
- return {
850
- module: preset(resolvedOptions, module),
851
- dependencies: output.dependencies
852
- };
853
- }
854
- /**
855
- * Loads a module with JIT transpilation based on the provided options.
856
- * This function runs synchronously using a worker thread.
857
- *
858
- * @param options - The options for loading the module.
859
- * @returns The loaded module.
860
- */
861
- function unrunSync(options) {
862
- const { createSyncFn } = __require("synckit");
863
- return createSyncFn(__require.resolve("./sync/worker.mjs"), { tsRunner: "node" })(options);
864
- }
865
- /**
866
- * Runs a given module with JIT transpilation based on the provided options.
867
- * This function does not return the module, as it simply executes it.
868
- * Corresponds to the CLI behavior.
869
- *
870
- * @param options - The options for running the module.
871
- * @param args - Additional command-line arguments to pass to the module.
872
- */
873
- async function unrunCli(options, args = []) {
874
- const resolvedOptions = resolveOptions(options);
875
- const output = await bundle(resolvedOptions);
876
- const moduleUrl = writeModule(output.chunk.code, resolvedOptions);
877
- let cliResult;
878
- try {
879
- cliResult = await execModule(moduleUrl, args);
880
- } catch (error) {
881
- throw new Error(`[unrun] Run failed (code length: ${output.chunk.code.length}): ${error.message}`, { cause: error });
882
- }
883
- cleanModule(moduleUrl, resolvedOptions);
884
- return cliResult;
885
- }
886
- //#endregion
887
- export { unrunCli as n, unrunSync as r, unrun as t };
@@ -1 +0,0 @@
1
- export { };
@@ -1,48 +0,0 @@
1
- import { t as unrun } from "../src-GU5PtktT.mjs";
2
- import { runAsWorker } from "synckit";
3
- //#region src/sync/worker.ts
4
- function cloneForTransfer(value, seen = /* @__PURE__ */ new WeakMap()) {
5
- if (typeof value === "function") throw new TypeError("[unrun] unrunSync cannot return functions");
6
- if (value === null || typeof value !== "object") return value;
7
- const objectValue = value;
8
- if (seen.has(objectValue)) return seen.get(objectValue);
9
- if (Array.isArray(value)) {
10
- const clone = [];
11
- seen.set(objectValue, clone);
12
- for (const item of value) clone.push(cloneForTransfer(item, seen));
13
- return clone;
14
- }
15
- if (isModuleNamespace(value)) {
16
- const clone = Object.create(null);
17
- seen.set(objectValue, clone);
18
- for (const key of Object.keys(value)) {
19
- const nestedValue = value[key];
20
- clone[key] = cloneForTransfer(nestedValue, seen);
21
- }
22
- return clone;
23
- }
24
- if (typeof structuredClone === "function") try {
25
- return structuredClone(value);
26
- } catch (error) {
27
- if (!isDataCloneError(error)) throw error;
28
- }
29
- const clone = {};
30
- seen.set(objectValue, clone);
31
- for (const [key, child] of Object.entries(value)) clone[key] = cloneForTransfer(child, seen);
32
- return clone;
33
- }
34
- function isModuleNamespace(value) {
35
- if (!value || typeof value !== "object") return false;
36
- return Object.prototype.toString.call(value) === "[object Module]";
37
- }
38
- function isDataCloneError(error) {
39
- if (!error || typeof error !== "object") return false;
40
- if (!("name" in error)) return false;
41
- return error.name === "DataCloneError";
42
- }
43
- runAsWorker(async (...args) => {
44
- const options = args[0];
45
- return cloneForTransfer(await unrun(options));
46
- });
47
- //#endregion
48
- export {};