synckit 0.11.4 → 0.11.6

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/lib/index.cjs CHANGED
@@ -1,69 +1,71 @@
1
- 'use strict';
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
2
23
 
3
- var module$1 = require('node:module');
4
- var path = require('node:path');
5
- var node_url = require('node:url');
6
- var node_worker_threads = require('node:worker_threads');
7
- var node_crypto = require('node:crypto');
8
- var fs = require('node:fs');
9
- var core = require('@pkgr/core');
24
+ //#endregion
25
+ const node_module = __toESM(require("node:module"));
26
+ const node_path = __toESM(require("node:path"));
27
+ const node_url = __toESM(require("node:url"));
28
+ const node_worker_threads = __toESM(require("node:worker_threads"));
29
+ const node_crypto = __toESM(require("node:crypto"));
30
+ const node_fs = __toESM(require("node:fs"));
31
+ const __pkgr_core = __toESM(require("@pkgr/core"));
10
32
 
11
- var _a;
12
- const NODE_OPTIONS$1 = (_a = process.env.NODE_OPTIONS) == null ? void 0 : _a.split(/\s+/);
13
- const hasFlag = (flag) => (NODE_OPTIONS$1 == null ? void 0 : NODE_OPTIONS$1.includes(flag)) || process.argv.includes(flag);
33
+ //#region src/common.ts
34
+ var _process$env$NODE_OPT;
35
+ const NODE_OPTIONS$1 = (_process$env$NODE_OPT = process.env.NODE_OPTIONS) === null || _process$env$NODE_OPT === void 0 ? void 0 : _process$env$NODE_OPT.split(/\s+/);
36
+ const hasFlag = (flag) => (NODE_OPTIONS$1 === null || NODE_OPTIONS$1 === void 0 ? void 0 : NODE_OPTIONS$1.includes(flag)) || process.argv.includes(flag);
14
37
  const parseVersion = (version) => version.split(".").map(Number.parseFloat);
15
38
  const compareVersion = (version1, version2) => {
16
- const versions1 = parseVersion(version1);
17
- const versions2 = parseVersion(version2);
18
- const length = Math.max(versions1.length, versions2.length);
19
- for (let i = 0; i < length; i++) {
20
- const v1 = versions1[i] || 0;
21
- const v2 = versions2[i] || 0;
22
- if (v1 > v2) {
23
- return 1;
24
- }
25
- if (v1 < v2) {
26
- return -1;
27
- }
28
- }
29
- return 0;
39
+ const versions1 = parseVersion(version1);
40
+ const versions2 = parseVersion(version2);
41
+ const length = Math.max(versions1.length, versions2.length);
42
+ for (let i = 0; i < length; i++) {
43
+ const v1 = versions1[i] || 0;
44
+ const v2 = versions2[i] || 0;
45
+ if (v1 > v2) return 1;
46
+ if (v1 < v2) return -1;
47
+ }
48
+ return 0;
30
49
  };
31
50
  const NODE_VERSION = process.versions.node;
32
51
  const compareNodeVersion = (version) => compareVersion(NODE_VERSION, version);
33
52
 
53
+ //#endregion
54
+ //#region src/constants.ts
34
55
  const TsRunner = {
35
- // https://nodejs.org/docs/latest/api/typescript.html#type-stripping
36
- Node: "node",
37
- // https://bun.sh/docs/typescript
38
- Bun: "bun",
39
- // https://github.com/TypeStrong/ts-node
40
- TsNode: "ts-node",
41
- // https://github.com/egoist/esbuild-register
42
- EsbuildRegister: "esbuild-register",
43
- // https://github.com/folke/esbuild-runner
44
- EsbuildRunner: "esbuild-runner",
45
- // https://github.com/oxc-project/oxc-node
46
- OXC: "oxc",
47
- // https://github.com/swc-project/swc-node/tree/master/packages/register
48
- SWC: "swc",
49
- // https://github.com/esbuild-kit/tsx
50
- TSX: "tsx"
56
+ Node: "node",
57
+ Bun: "bun",
58
+ TsNode: "ts-node",
59
+ EsbuildRegister: "esbuild-register",
60
+ EsbuildRunner: "esbuild-runner",
61
+ OXC: "oxc",
62
+ SWC: "swc",
63
+ TSX: "tsx"
51
64
  };
52
- const {
53
- NODE_OPTIONS: NODE_OPTIONS_ = "",
54
- SYNCKIT_EXEC_ARGV = "",
55
- SYNCKIT_GLOBAL_SHIMS,
56
- SYNCKIT_TIMEOUT,
57
- SYNCKIT_TS_RUNNER
58
- } = process.env;
59
- const TS_ESM_PARTIAL_SUPPORTED = (
60
- // >=
61
- compareNodeVersion("16") >= 0 && // <
62
- compareNodeVersion("18.19") < 0
63
- );
65
+ const { NODE_OPTIONS: NODE_OPTIONS_ = "", SYNCKIT_EXEC_ARGV = "", SYNCKIT_GLOBAL_SHIMS, SYNCKIT_TIMEOUT, SYNCKIT_TS_RUNNER } = process.env;
66
+ const TS_ESM_PARTIAL_SUPPORTED = compareNodeVersion("16") >= 0 && compareNodeVersion("18.19") < 0;
64
67
  const MTS_SUPPORTED = compareNodeVersion("20.8") >= 0;
65
- const MODULE_REGISTER_SUPPORTED = MTS_SUPPORTED || // >=
66
- compareNodeVersion("18.19") >= 0;
68
+ const MODULE_REGISTER_SUPPORTED = MTS_SUPPORTED || compareNodeVersion("18.19") >= 0;
67
69
  const STRIP_TYPES_NODE_VERSION = "22.6";
68
70
  const TRANSFORM_TYPES_NODE_VERSION = "22.7";
69
71
  const FEATURE_TYPESCRIPT_NODE_VERSION = "22.10";
@@ -72,581 +74,477 @@ const STRIP_TYPES_FLAG = "--experimental-strip-types";
72
74
  const TRANSFORM_TYPES_FLAG = "--experimental-transform-types";
73
75
  const NO_STRIP_TYPES_FLAG = "--no-experimental-strip-types";
74
76
  const NODE_OPTIONS = NODE_OPTIONS_.split(/\s+/);
75
- const NO_STRIP_TYPES = (
76
- // only consider `process.features.typescript` when `--no-experimental-strip-types` flag enabled
77
- hasFlag(NO_STRIP_TYPES_FLAG) && // >=
78
- (compareNodeVersion(FEATURE_TYPESCRIPT_NODE_VERSION) >= 0 ? process.features.typescript === false : !hasFlag(STRIP_TYPES_FLAG) && !hasFlag(TRANSFORM_TYPES_FLAG))
79
- );
77
+ const NO_STRIP_TYPES = hasFlag(NO_STRIP_TYPES_FLAG) && (compareNodeVersion(FEATURE_TYPESCRIPT_NODE_VERSION) >= 0 ? process.features.typescript === false : !hasFlag(STRIP_TYPES_FLAG) && !hasFlag(TRANSFORM_TYPES_FLAG));
80
78
  const DEFAULT_TIMEOUT = SYNCKIT_TIMEOUT ? +SYNCKIT_TIMEOUT : void 0;
81
79
  const DEFAULT_EXEC_ARGV = SYNCKIT_EXEC_ARGV.split(",");
82
80
  const DEFAULT_TS_RUNNER = SYNCKIT_TS_RUNNER;
83
- const DEFAULT_GLOBAL_SHIMS = ["1", "true"].includes(
84
- SYNCKIT_GLOBAL_SHIMS
85
- );
86
- const DEFAULT_GLOBAL_SHIMS_PRESET = [
87
- {
88
- moduleName: "node-fetch",
89
- globalName: "fetch"
90
- },
91
- {
92
- moduleName: "node:perf_hooks",
93
- globalName: "performance",
94
- named: "performance"
95
- }
96
- ];
81
+ const DEFAULT_GLOBAL_SHIMS = ["1", "true"].includes(SYNCKIT_GLOBAL_SHIMS);
82
+ const DEFAULT_GLOBAL_SHIMS_PRESET = [{
83
+ moduleName: "node-fetch",
84
+ globalName: "fetch"
85
+ }, {
86
+ moduleName: "node:perf_hooks",
87
+ globalName: "performance",
88
+ named: "performance"
89
+ }];
97
90
  const IMPORT_FLAG = "--import";
98
91
  const REQUIRE_FLAG = "--require";
99
92
  const REQUIRE_ABBR_FLAG = "-r";
100
- const REQUIRE_FLAGS = /* @__PURE__ */ new Set([REQUIRE_FLAG, REQUIRE_ABBR_FLAG]);
93
+ const REQUIRE_FLAGS = new Set([REQUIRE_FLAG, REQUIRE_ABBR_FLAG]);
101
94
  const LOADER_FLAG = "--loader";
102
95
  const EXPERIMENTAL_LOADER_FLAG = "--experimental-loader";
103
- const LOADER_FLAGS = /* @__PURE__ */ new Set([LOADER_FLAG, EXPERIMENTAL_LOADER_FLAG]);
96
+ const LOADER_FLAGS = new Set([LOADER_FLAG, EXPERIMENTAL_LOADER_FLAG]);
104
97
  const IMPORT_FLAG_SUPPORTED = compareNodeVersion("20.6") >= 0;
105
98
  const INT32_BYTES = 4;
106
99
 
107
- var __defProp = Object.defineProperty;
108
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
109
- var __hasOwnProp = Object.prototype.hasOwnProperty;
110
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
111
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
112
- var __spreadValues = (a, b) => {
113
- for (var prop in b || (b = {}))
114
- if (__hasOwnProp.call(b, prop))
115
- __defNormalProp(a, prop, b[prop]);
116
- if (__getOwnPropSymbols)
117
- for (var prop of __getOwnPropSymbols(b)) {
118
- if (__propIsEnum.call(b, prop))
119
- __defNormalProp(a, prop, b[prop]);
120
- }
121
- return a;
122
- };
123
- var __objRest = (source, exclude) => {
124
- var target = {};
125
- for (var prop in source)
126
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
127
- target[prop] = source[prop];
128
- if (source != null && __getOwnPropSymbols)
129
- for (var prop of __getOwnPropSymbols(source)) {
130
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
131
- target[prop] = source[prop];
132
- }
133
- return target;
134
- };
135
- const import_meta = {};
136
- const isFile = (path2) => {
137
- var _a;
138
- try {
139
- return !!((_a = fs.statSync(path2, { throwIfNoEntry: false })) == null ? void 0 : _a.isFile());
140
- } catch (e) {
141
- return false;
142
- }
100
+ //#endregion
101
+ //#region src/helpers.ts
102
+ const isFile = (path$2) => {
103
+ try {
104
+ var _fs$statSync;
105
+ return !!((_fs$statSync = node_fs.default.statSync(path$2, { throwIfNoEntry: false })) === null || _fs$statSync === void 0 ? void 0 : _fs$statSync.isFile());
106
+ } catch {
107
+ /* istanbul ignore next */
108
+ return false;
109
+ }
143
110
  };
144
111
  const dataUrl = (code) => new URL(`data:text/javascript,${encodeURIComponent(code)}`);
145
112
  const hasRequireFlag = (execArgv) => execArgv.some((execArg) => REQUIRE_FLAGS.has(execArg));
146
113
  const hasImportFlag = (execArgv) => execArgv.includes(IMPORT_FLAG);
147
114
  const hasLoaderFlag = (execArgv) => execArgv.some((execArg) => LOADER_FLAGS.has(execArg));
148
- const setupTsRunner = (workerPath, {
149
- execArgv = DEFAULT_EXEC_ARGV,
150
- tsRunner
151
- } = {}) => {
152
- let ext = path.extname(workerPath);
153
- if (!/([/\\])node_modules\1/.test(workerPath) && (!ext || /^\.[cm]?js$/.test(ext))) {
154
- const workPathWithoutExt = ext ? workerPath.slice(0, -ext.length) : workerPath;
155
- let extensions;
156
- switch (ext) {
157
- case ".cjs": {
158
- extensions = [".cts", ".cjs"];
159
- break;
160
- }
161
- case ".mjs": {
162
- extensions = [".mts", ".mjs"];
163
- break;
164
- }
165
- default: {
166
- extensions = [".ts", ".js"];
167
- break;
168
- }
169
- }
170
- const found = core.tryExtensions(workPathWithoutExt, extensions);
171
- let differentExt;
172
- if (found && (!ext || (differentExt = found !== workPathWithoutExt))) {
173
- workerPath = found;
174
- if (differentExt) {
175
- ext = path.extname(workerPath);
176
- }
177
- }
178
- }
179
- const isTs = /\.[cm]?ts$/.test(workerPath);
180
- let jsUseEsm = ext === ".mjs";
181
- let tsUseEsm = ext === ".mts";
182
- if (isTs) {
183
- if (!tsUseEsm && ext !== ".cts") {
184
- const pkg = core.findUp(workerPath);
185
- if (pkg) {
186
- tsUseEsm = core.cjsRequire(pkg).type === "module";
187
- }
188
- }
189
- const stripTypesIndex = execArgv.indexOf(STRIP_TYPES_FLAG);
190
- const transformTypesIndex = execArgv.indexOf(TRANSFORM_TYPES_FLAG);
191
- const noStripTypesIndex = execArgv.indexOf(NO_STRIP_TYPES_FLAG);
192
- const execArgvNoStripTypes = noStripTypesIndex > stripTypesIndex || noStripTypesIndex > transformTypesIndex;
193
- const noStripTypes = execArgvNoStripTypes || stripTypesIndex === -1 && transformTypesIndex === -1 && NO_STRIP_TYPES;
194
- if (tsRunner == null) {
195
- if (process.versions.bun) {
196
- tsRunner = TsRunner.Bun;
197
- } else if (!noStripTypes && // >=
198
- compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0) {
199
- tsRunner = TsRunner.Node;
200
- } else if (core.isPkgAvailable(TsRunner.TsNode)) {
201
- tsRunner = TsRunner.TsNode;
202
- }
203
- }
204
- switch (tsRunner) {
205
- case TsRunner.Bun: {
206
- break;
207
- }
208
- case TsRunner.Node: {
209
- if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) < 0) {
210
- throw new Error(
211
- "type stripping is not supported in this node version"
212
- );
213
- }
214
- if (noStripTypes) {
215
- throw new Error("type stripping is disabled explicitly");
216
- }
217
- if (compareNodeVersion(DEFAULT_TYPES_NODE_VERSION) >= 0) {
218
- break;
219
- }
220
- if (
221
- // >=
222
- compareNodeVersion(TRANSFORM_TYPES_NODE_VERSION) >= 0 && !execArgv.includes(TRANSFORM_TYPES_FLAG)
223
- ) {
224
- execArgv = [TRANSFORM_TYPES_FLAG, ...execArgv];
225
- } else if (
226
- // >=
227
- compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0 && !execArgv.includes(STRIP_TYPES_FLAG)
228
- ) {
229
- execArgv = [STRIP_TYPES_FLAG, ...execArgv];
230
- }
231
- break;
232
- }
233
- // https://github.com/TypeStrong/ts-node#node-flags-and-other-tools
234
- case TsRunner.TsNode: {
235
- if (tsUseEsm) {
236
- if (!execArgv.includes(LOADER_FLAG)) {
237
- execArgv = [LOADER_FLAG, `${TsRunner.TsNode}/esm`, ...execArgv];
238
- }
239
- } else if (!hasRequireFlag(execArgv)) {
240
- execArgv = [
241
- REQUIRE_ABBR_FLAG,
242
- `${TsRunner.TsNode}/register`,
243
- ...execArgv
244
- ];
245
- }
246
- break;
247
- }
248
- // https://github.com/egoist/esbuild-register#usage
249
- case TsRunner.EsbuildRegister: {
250
- if (tsUseEsm) {
251
- if (!hasLoaderFlag(execArgv)) {
252
- execArgv = [
253
- LOADER_FLAG,
254
- `${TsRunner.EsbuildRegister}/loader`,
255
- ...execArgv
256
- ];
257
- }
258
- } else if (!hasRequireFlag(execArgv)) {
259
- execArgv = [REQUIRE_ABBR_FLAG, TsRunner.EsbuildRegister, ...execArgv];
260
- }
261
- break;
262
- }
263
- // https://github.com/folke/esbuild-runner#-usage
264
- case TsRunner.EsbuildRunner: {
265
- if (!hasRequireFlag(execArgv)) {
266
- execArgv = [
267
- REQUIRE_ABBR_FLAG,
268
- `${TsRunner.EsbuildRunner}/register`,
269
- ...execArgv
270
- ];
271
- }
272
- break;
273
- }
274
- // https://github.com/oxc-project/oxc-node#usage
275
- case TsRunner.OXC: {
276
- if (!execArgv.includes(IMPORT_FLAG)) {
277
- execArgv = [
278
- IMPORT_FLAG,
279
- `@${TsRunner.OXC}-node/core/register`,
280
- ...execArgv
281
- ];
282
- }
283
- break;
284
- }
285
- // https://github.com/swc-project/swc-node#usage
286
- case TsRunner.SWC: {
287
- if (tsUseEsm) {
288
- if (IMPORT_FLAG_SUPPORTED) {
289
- if (!hasImportFlag(execArgv)) {
290
- execArgv = [
291
- IMPORT_FLAG,
292
- `@${TsRunner.SWC}-node/register/esm-register`,
293
- ...execArgv
294
- ];
295
- }
296
- } else if (!hasLoaderFlag(execArgv)) {
297
- execArgv = [
298
- LOADER_FLAG,
299
- `@${TsRunner.SWC}-node/register/esm`,
300
- ...execArgv
301
- ];
302
- }
303
- } else if (!hasRequireFlag(execArgv)) {
304
- execArgv = [
305
- REQUIRE_ABBR_FLAG,
306
- `@${TsRunner.SWC}-node/register`,
307
- ...execArgv
308
- ];
309
- }
310
- break;
311
- }
312
- // https://tsx.is/dev-api/node-cli#node-js-cli
313
- case TsRunner.TSX: {
314
- if (IMPORT_FLAG_SUPPORTED) {
315
- if (!execArgv.includes(IMPORT_FLAG)) {
316
- execArgv = [IMPORT_FLAG, TsRunner.TSX, ...execArgv];
317
- }
318
- } else if (!execArgv.includes(LOADER_FLAG)) {
319
- execArgv = [LOADER_FLAG, TsRunner.TSX, ...execArgv];
320
- }
321
- break;
322
- }
323
- default: {
324
- throw new Error(`Unknown ts runner: ${String(tsRunner)}`);
325
- }
326
- }
327
- } else if (!jsUseEsm && ext !== ".cjs") {
328
- const pkg = core.findUp(workerPath);
329
- if (pkg) {
330
- jsUseEsm = core.cjsRequire(pkg).type === "module";
331
- }
332
- }
333
- let resolvedPnpLoaderPath;
334
- if (process.versions.pnp) {
335
- let pnpApiPath;
336
- try {
337
- pnpApiPath = core.cjsRequire.resolve("pnpapi");
338
- } catch (e) {
339
- }
340
- if (pnpApiPath && !NODE_OPTIONS.some(
341
- (option, index) => REQUIRE_FLAGS.has(option) && pnpApiPath === core.cjsRequire.resolve(NODE_OPTIONS[index + 1])
342
- ) && !execArgv.includes(pnpApiPath)) {
343
- execArgv = [REQUIRE_ABBR_FLAG, pnpApiPath, ...execArgv];
344
- const pnpLoaderPath = path.resolve(pnpApiPath, "../.pnp.loader.mjs");
345
- if (isFile(pnpLoaderPath)) {
346
- resolvedPnpLoaderPath = node_url.pathToFileURL(pnpLoaderPath).href;
347
- if (!MODULE_REGISTER_SUPPORTED) {
348
- execArgv = [LOADER_FLAG, resolvedPnpLoaderPath, ...execArgv];
349
- }
350
- }
351
- }
352
- }
353
- return {
354
- ext,
355
- isTs,
356
- jsUseEsm,
357
- tsRunner,
358
- tsUseEsm,
359
- workerPath,
360
- pnpLoaderPath: resolvedPnpLoaderPath,
361
- execArgv
362
- };
115
+ const setupTsRunner = (workerPath, { execArgv = DEFAULT_EXEC_ARGV, tsRunner } = {}) => {
116
+ let ext = node_path.default.extname(workerPath);
117
+ if (!/([/\\])node_modules\1/.test(workerPath) && (!ext || /^\.[cm]?js$/.test(ext))) {
118
+ const workPathWithoutExt = ext ? workerPath.slice(0, -ext.length) : workerPath;
119
+ let extensions;
120
+ switch (ext) {
121
+ case ".cjs": {
122
+ extensions = [".cts", ".cjs"];
123
+ break;
124
+ }
125
+ case ".mjs": {
126
+ extensions = [".mts", ".mjs"];
127
+ break;
128
+ }
129
+ default: {
130
+ extensions = [".ts", ".js"];
131
+ break;
132
+ }
133
+ }
134
+ const found = (0, __pkgr_core.tryExtensions)(workPathWithoutExt, extensions);
135
+ let differentExt;
136
+ if (found && (!ext || (differentExt = found !== workPathWithoutExt))) {
137
+ workerPath = found;
138
+ if (differentExt) ext = node_path.default.extname(workerPath);
139
+ }
140
+ }
141
+ const isTs = /\.[cm]?ts$/.test(workerPath);
142
+ let jsUseEsm = ext === ".mjs";
143
+ let tsUseEsm = ext === ".mts";
144
+ if (isTs) {
145
+ if (!tsUseEsm && ext !== ".cts") {
146
+ const pkg = (0, __pkgr_core.findUp)(workerPath);
147
+ if (pkg) tsUseEsm = (0, __pkgr_core.cjsRequire)(pkg).type === "module";
148
+ }
149
+ const stripTypesIndex = execArgv.indexOf(STRIP_TYPES_FLAG);
150
+ const transformTypesIndex = execArgv.indexOf(TRANSFORM_TYPES_FLAG);
151
+ const noStripTypesIndex = execArgv.indexOf(NO_STRIP_TYPES_FLAG);
152
+ const execArgvNoStripTypes = noStripTypesIndex > stripTypesIndex || noStripTypesIndex > transformTypesIndex;
153
+ const noStripTypes = execArgvNoStripTypes || stripTypesIndex === -1 && transformTypesIndex === -1 && NO_STRIP_TYPES;
154
+ if (tsRunner == null) {
155
+ if (process.versions.bun) tsRunner = TsRunner.Bun;
156
+ else if (!noStripTypes && compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0) tsRunner = TsRunner.Node;
157
+ else if ((0, __pkgr_core.isPkgAvailable)(TsRunner.TsNode)) tsRunner = TsRunner.TsNode;
158
+ }
159
+ switch (tsRunner) {
160
+ case TsRunner.Bun: break;
161
+ case TsRunner.Node: {
162
+ if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) < 0) throw new Error("type stripping is not supported in this node version");
163
+ if (noStripTypes) throw new Error("type stripping is disabled explicitly");
164
+ if (compareNodeVersion(DEFAULT_TYPES_NODE_VERSION) >= 0) break;
165
+ if (compareNodeVersion(TRANSFORM_TYPES_NODE_VERSION) >= 0 && !execArgv.includes(TRANSFORM_TYPES_FLAG)) execArgv = [TRANSFORM_TYPES_FLAG, ...execArgv];
166
+ else if (compareNodeVersion(STRIP_TYPES_NODE_VERSION) >= 0 && !execArgv.includes(STRIP_TYPES_FLAG)) execArgv = [STRIP_TYPES_FLAG, ...execArgv];
167
+ break;
168
+ }
169
+ case TsRunner.TsNode: {
170
+ if (tsUseEsm) {
171
+ if (!execArgv.includes(LOADER_FLAG)) execArgv = [
172
+ LOADER_FLAG,
173
+ `${TsRunner.TsNode}/esm`,
174
+ ...execArgv
175
+ ];
176
+ } else if (!hasRequireFlag(execArgv)) execArgv = [
177
+ REQUIRE_ABBR_FLAG,
178
+ `${TsRunner.TsNode}/register`,
179
+ ...execArgv
180
+ ];
181
+ break;
182
+ }
183
+ case TsRunner.EsbuildRegister: {
184
+ if (tsUseEsm) {
185
+ if (!hasLoaderFlag(execArgv)) execArgv = [
186
+ LOADER_FLAG,
187
+ `${TsRunner.EsbuildRegister}/loader`,
188
+ ...execArgv
189
+ ];
190
+ } else if (!hasRequireFlag(execArgv)) execArgv = [
191
+ REQUIRE_ABBR_FLAG,
192
+ TsRunner.EsbuildRegister,
193
+ ...execArgv
194
+ ];
195
+ break;
196
+ }
197
+ case TsRunner.EsbuildRunner: {
198
+ if (!hasRequireFlag(execArgv)) execArgv = [
199
+ REQUIRE_ABBR_FLAG,
200
+ `${TsRunner.EsbuildRunner}/register`,
201
+ ...execArgv
202
+ ];
203
+ break;
204
+ }
205
+ case TsRunner.OXC: {
206
+ if (!execArgv.includes(IMPORT_FLAG)) execArgv = [
207
+ IMPORT_FLAG,
208
+ `@${TsRunner.OXC}-node/core/register`,
209
+ ...execArgv
210
+ ];
211
+ break;
212
+ }
213
+ case TsRunner.SWC: {
214
+ if (tsUseEsm) {
215
+ if (IMPORT_FLAG_SUPPORTED) {
216
+ if (!hasImportFlag(execArgv)) execArgv = [
217
+ IMPORT_FLAG,
218
+ `@${TsRunner.SWC}-node/register/esm-register`,
219
+ ...execArgv
220
+ ];
221
+ } else if (!hasLoaderFlag(execArgv)) execArgv = [
222
+ LOADER_FLAG,
223
+ `@${TsRunner.SWC}-node/register/esm`,
224
+ ...execArgv
225
+ ];
226
+ } else if (!hasRequireFlag(execArgv)) execArgv = [
227
+ REQUIRE_ABBR_FLAG,
228
+ `@${TsRunner.SWC}-node/register`,
229
+ ...execArgv
230
+ ];
231
+ break;
232
+ }
233
+ case TsRunner.TSX: {
234
+ if (IMPORT_FLAG_SUPPORTED) {
235
+ if (!execArgv.includes(IMPORT_FLAG)) execArgv = [
236
+ IMPORT_FLAG,
237
+ TsRunner.TSX,
238
+ ...execArgv
239
+ ];
240
+ } else if (!execArgv.includes(LOADER_FLAG)) execArgv = [
241
+ LOADER_FLAG,
242
+ TsRunner.TSX,
243
+ ...execArgv
244
+ ];
245
+ break;
246
+ }
247
+ default: throw new Error(`Unknown ts runner: ${String(tsRunner)}`);
248
+ }
249
+ } else if (!jsUseEsm && ext !== ".cjs") {
250
+ const pkg = (0, __pkgr_core.findUp)(workerPath);
251
+ if (pkg) jsUseEsm = (0, __pkgr_core.cjsRequire)(pkg).type === "module";
252
+ }
253
+ let resolvedPnpLoaderPath;
254
+ /* istanbul ignore if -- https://github.com/facebook/jest/issues/5274 */
255
+ if (process.versions.pnp) {
256
+ let pnpApiPath;
257
+ try {
258
+ /** @see https://github.com/facebook/jest/issues/9543 */
259
+ pnpApiPath = __pkgr_core.cjsRequire.resolve("pnpapi");
260
+ } catch {}
261
+ if (pnpApiPath && !NODE_OPTIONS.some((option, index) => REQUIRE_FLAGS.has(option) && pnpApiPath === __pkgr_core.cjsRequire.resolve(NODE_OPTIONS[index + 1])) && !execArgv.includes(pnpApiPath)) {
262
+ execArgv = [
263
+ REQUIRE_ABBR_FLAG,
264
+ pnpApiPath,
265
+ ...execArgv
266
+ ];
267
+ const pnpLoaderPath = node_path.default.resolve(pnpApiPath, "../.pnp.loader.mjs");
268
+ if (isFile(pnpLoaderPath)) {
269
+ resolvedPnpLoaderPath = (0, node_url.pathToFileURL)(pnpLoaderPath).href;
270
+ if (!MODULE_REGISTER_SUPPORTED) execArgv = [
271
+ LOADER_FLAG,
272
+ resolvedPnpLoaderPath,
273
+ ...execArgv
274
+ ];
275
+ }
276
+ }
277
+ }
278
+ return {
279
+ ext,
280
+ isTs,
281
+ jsUseEsm,
282
+ tsRunner,
283
+ tsUseEsm,
284
+ workerPath,
285
+ pnpLoaderPath: resolvedPnpLoaderPath,
286
+ execArgv
287
+ };
363
288
  };
364
- const md5Hash = (text) => (
365
- // eslint-disable-next-line sonarjs/hashing
366
- node_crypto.createHash("md5").update(text).digest("hex")
367
- );
289
+ const md5Hash = (text) => (0, node_crypto.createHash)("md5").update(text).digest("hex");
368
290
  const encodeImportModule = (moduleNameOrGlobalShim, type = "import") => {
369
- const { moduleName, globalName, named, conditional } = typeof moduleNameOrGlobalShim === "string" ? { moduleName: moduleNameOrGlobalShim } : moduleNameOrGlobalShim;
370
- const importStatement = type === "import" ? `import${globalName ? " " + (named === null ? "* as " + globalName : (named == null ? void 0 : named.trim()) ? `{${named}}` : globalName) + " from" : ""} '${path.isAbsolute(moduleName) ? String(node_url.pathToFileURL(moduleName)) : moduleName}'` : `${globalName ? "const " + ((named == null ? void 0 : named.trim()) ? `{${named}}` : globalName) + "=" : ""}require('${moduleName.replace(/\\/g, "\\\\")}')`;
371
- if (!globalName) {
372
- return importStatement;
373
- }
374
- const overrideStatement = `globalThis.${globalName}=${(named == null ? void 0 : named.trim()) ? named : globalName}`;
375
- return importStatement + (conditional === false ? `;${overrideStatement}` : `;if(!globalThis.${globalName})${overrideStatement}`);
291
+ const { moduleName, globalName, named, conditional } = typeof moduleNameOrGlobalShim === "string" ? { moduleName: moduleNameOrGlobalShim } : moduleNameOrGlobalShim;
292
+ const importStatement = type === "import" ? `import${globalName ? " " + (named === null ? "* as " + globalName : (named === null || named === void 0 ? void 0 : named.trim()) ? `{${named}}` : globalName) + " from" : ""} '${node_path.default.isAbsolute(moduleName) ? String((0, node_url.pathToFileURL)(moduleName)) : moduleName}'` : `${globalName ? "const " + ((named === null || named === void 0 ? void 0 : named.trim()) ? `{${named}}` : globalName) + "=" : ""}require('${moduleName.replace(/\\/g, "\\\\")}')`;
293
+ if (!globalName) return importStatement;
294
+ const overrideStatement = `globalThis.${globalName}=${(named === null || named === void 0 ? void 0 : named.trim()) ? named : globalName}`;
295
+ return importStatement + (conditional === false ? `;${overrideStatement}` : `;if(!globalThis.${globalName})${overrideStatement}`);
376
296
  };
377
- const _generateGlobals = (globalShims, type) => globalShims.reduce(
378
- (acc, shim) => `${acc}${acc ? ";" : ""}${encodeImportModule(shim, type)}`,
379
- ""
380
- );
297
+ /** @internal */
298
+ const _generateGlobals = (globalShims, type) => globalShims.reduce((acc, shim) => `${acc}${acc ? ";" : ""}${encodeImportModule(shim, type)}`, "");
381
299
  let globalsCache;
382
300
  let tmpdir;
383
- const _dirname = typeof __dirname === "undefined" ? path.dirname(node_url.fileURLToPath(import_meta.url)) : (
384
- /* istanbul ignore next */
385
- __dirname
386
- );
301
+ const _dirname = typeof __dirname === "undefined" ? node_path.default.dirname((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href)) : __dirname;
387
302
  const generateGlobals = (workerPath, globalShims, type = "import") => {
388
- if (globalShims.length === 0) {
389
- return "";
390
- }
391
- globalsCache != null ? globalsCache : globalsCache = /* @__PURE__ */ new Map();
392
- const cached = globalsCache.get(workerPath);
393
- if (cached) {
394
- const [content2, filepath2] = cached;
395
- if (type === "require" && !filepath2 || type === "import" && filepath2 && isFile(filepath2)) {
396
- return content2;
397
- }
398
- }
399
- const globals = _generateGlobals(globalShims, type);
400
- let content = globals;
401
- let filepath;
402
- if (type === "import") {
403
- if (!tmpdir) {
404
- tmpdir = path.resolve(core.findUp(_dirname), "../node_modules/.synckit");
405
- }
406
- fs.mkdirSync(tmpdir, { recursive: true });
407
- filepath = path.resolve(tmpdir, md5Hash(workerPath) + ".mjs");
408
- content = encodeImportModule(filepath);
409
- fs.writeFileSync(filepath, globals);
410
- }
411
- globalsCache.set(workerPath, [content, filepath]);
412
- return content;
303
+ if (globalShims.length === 0) return "";
304
+ globalsCache ?? (globalsCache = new Map());
305
+ const cached = globalsCache.get(workerPath);
306
+ if (cached) {
307
+ const [content$1, filepath$1] = cached;
308
+ if (type === "require" && !filepath$1 || type === "import" && filepath$1 && isFile(filepath$1)) return content$1;
309
+ }
310
+ const globals = _generateGlobals(globalShims, type);
311
+ let content = globals;
312
+ let filepath;
313
+ if (type === "import") {
314
+ if (!tmpdir) tmpdir = node_path.default.resolve((0, __pkgr_core.findUp)(_dirname), "../node_modules/.synckit");
315
+ node_fs.default.mkdirSync(tmpdir, { recursive: true });
316
+ filepath = node_path.default.resolve(tmpdir, md5Hash(workerPath) + ".mjs");
317
+ content = encodeImportModule(filepath);
318
+ node_fs.default.writeFileSync(filepath, globals);
319
+ }
320
+ globalsCache.set(workerPath, [content, filepath]);
321
+ return content;
413
322
  };
323
+ /**
324
+ * Creates a shallow copy of the enumerable properties from the provided object.
325
+ *
326
+ * @param object - An optional object whose properties are to be extracted.
327
+ * @returns A new object containing the enumerable properties of the input, or
328
+ * undefined if no valid object is provided.
329
+ */
414
330
  function extractProperties(object) {
415
- if (object && typeof object === "object") {
416
- const properties = {};
417
- for (const key in object) {
418
- properties[key] = object[key];
419
- }
420
- return properties;
421
- }
331
+ if (object && typeof object === "object") {
332
+ const properties = {};
333
+ for (const key in object) properties[key] = object[key];
334
+ return properties;
335
+ }
422
336
  }
423
337
  let sharedBuffer;
424
338
  let sharedBufferView;
425
- function startWorkerThread(workerPath, {
426
- timeout = DEFAULT_TIMEOUT,
427
- execArgv = DEFAULT_EXEC_ARGV,
428
- tsRunner = DEFAULT_TS_RUNNER,
429
- transferList = [],
430
- globalShims = DEFAULT_GLOBAL_SHIMS
431
- } = {}) {
432
- const { port1: mainPort, port2: workerPort } = new node_worker_threads.MessageChannel();
433
- const {
434
- isTs,
435
- ext,
436
- jsUseEsm,
437
- tsUseEsm,
438
- tsRunner: finalTsRunner,
439
- workerPath: finalWorkerPath,
440
- pnpLoaderPath,
441
- execArgv: finalExecArgv
442
- } = setupTsRunner(workerPath, { execArgv, tsRunner });
443
- const workerPathUrl = node_url.pathToFileURL(finalWorkerPath);
444
- if (/\.[cm]ts$/.test(finalWorkerPath)) {
445
- const isTsxSupported = !tsUseEsm || TS_ESM_PARTIAL_SUPPORTED;
446
- if (!finalTsRunner) {
447
- throw new Error("No ts runner specified, ts worker path is not supported");
448
- } else if ([
449
- // https://github.com/egoist/esbuild-register/issues/96
450
- TsRunner.EsbuildRegister,
451
- // https://github.com/folke/esbuild-runner/issues/67
452
- TsRunner.EsbuildRunner,
453
- ...TS_ESM_PARTIAL_SUPPORTED ? [
454
- TsRunner.OXC,
455
- // https://github.com/swc-project/swc-node/issues/667
456
- TsRunner.SWC
457
- ] : [],
458
- .../* istanbul ignore next */
459
- isTsxSupported ? [] : [TsRunner.TSX]
460
- ].includes(finalTsRunner)) {
461
- throw new Error(
462
- `${finalTsRunner} is not supported for ${ext} files yet` + /* istanbul ignore next */
463
- (isTsxSupported ? ", you can try [tsx](https://github.com/esbuild-kit/tsx) instead" : MTS_SUPPORTED ? ", you can try [oxc](https://github.com/oxc-project/oxc-node) or [swc](https://github.com/swc-project/swc-node/tree/master/packages/register) instead" : "")
464
- );
465
- }
466
- }
467
- const finalGlobalShims = (globalShims === true ? DEFAULT_GLOBAL_SHIMS_PRESET : Array.isArray(globalShims) ? globalShims : []).filter(({ moduleName }) => core.isPkgAvailable(moduleName));
468
- sharedBufferView != null ? sharedBufferView : sharedBufferView = new Int32Array(
469
- /* istanbul ignore next */
470
- sharedBuffer != null ? sharedBuffer : sharedBuffer = new SharedArrayBuffer(
471
- INT32_BYTES
472
- ),
473
- 0,
474
- 1
475
- );
476
- const useGlobals = finalGlobalShims.length > 0;
477
- const useEval = isTs ? !tsUseEsm : !jsUseEsm && useGlobals;
478
- const worker = new node_worker_threads.Worker(
479
- jsUseEsm && useGlobals || tsUseEsm && finalTsRunner === TsRunner.TsNode ? dataUrl(
480
- `${generateGlobals(
481
- finalWorkerPath,
482
- finalGlobalShims
483
- )};import '${String(workerPathUrl)}'`
484
- ) : useEval ? `${generateGlobals(
485
- finalWorkerPath,
486
- finalGlobalShims,
487
- "require"
488
- )};${encodeImportModule(finalWorkerPath, "require")}` : workerPathUrl,
489
- {
490
- eval: useEval,
491
- workerData: { sharedBufferView, workerPort, pnpLoaderPath },
492
- transferList: [workerPort, ...transferList],
493
- execArgv: finalExecArgv
494
- }
495
- );
496
- let nextID = 0;
497
- const receiveMessageWithId = (port, expectedId, waitingTimeout) => {
498
- const start = Date.now();
499
- const status = Atomics.wait(sharedBufferView, 0, 0, waitingTimeout);
500
- Atomics.store(sharedBufferView, 0, 0);
501
- if (!["ok", "not-equal"].includes(status)) {
502
- const abortMsg = {
503
- id: expectedId,
504
- cmd: "abort"
505
- };
506
- port.postMessage(abortMsg);
507
- throw new Error("Internal error: Atomics.wait() failed: " + status);
508
- }
509
- const _a = node_worker_threads.receiveMessageOnPort(mainPort).message, { id } = _a, message = __objRest(_a, ["id"]);
510
- if (id < expectedId) {
511
- const waitingTime = Date.now() - start;
512
- return receiveMessageWithId(
513
- port,
514
- expectedId,
515
- waitingTimeout ? waitingTimeout - waitingTime : void 0
516
- );
517
- }
518
- if (expectedId !== id) {
519
- throw new Error(
520
- `Internal error: Expected id ${expectedId} but got id ${id}`
521
- );
522
- }
523
- return __spreadValues({ id }, message);
524
- };
525
- const syncFn = (...args) => {
526
- const id = nextID++;
527
- const msg = { id, args };
528
- worker.postMessage(msg);
529
- const { result, error, properties, stdio } = receiveMessageWithId(
530
- mainPort,
531
- id,
532
- timeout
533
- );
534
- for (const { type, chunk, encoding } of stdio) {
535
- process[type].write(chunk, encoding);
536
- }
537
- if (error) {
538
- throw Object.assign(error, properties);
539
- }
540
- return result;
541
- };
542
- worker.unref();
543
- return syncFn;
339
+ /**
340
+ * Spawns a worker thread and returns a synchronous function to dispatch tasks.
341
+ *
342
+ * The function initializes a worker thread with the specified script and
343
+ * configuration, setting up a dedicated message channel for bidirectional
344
+ * communication. It applies TypeScript runner settings, execution arguments,
345
+ * and global shims as needed. The returned function sends tasks to the worker,
346
+ * waits synchronously for a response using shared memory synchronization, and
347
+ * then returns the computed result.
348
+ *
349
+ * @param workerPath - The file path of the worker script to execute.
350
+ * @param options - An object containing configuration parameters:
351
+ *
352
+ * - Timeout: Maximum time in milliseconds to wait for the worker's response.
353
+ * - ExecArgv: Array of Node.js execution arguments for the worker.
354
+ * - TsRunner: Specifies the TypeScript runner to use if the worker script is
355
+ * TypeScript.
356
+ * - TransferList: List of additional transferable objects to pass to the worker.
357
+ * - GlobalShims: Modules to import as global shims; if true, a default preset is
358
+ * used.
359
+ *
360
+ * @returns A synchronous function that accepts task arguments intended for the
361
+ * worker thread and returns its result.
362
+ * @throws {Error} If a TypeScript runner is required but not specified, or if
363
+ * an unsupported TypeScript runner is used for the file type.
364
+ * @throws {Error} If internal synchronization fails or if the message
365
+ * identifier does not match the expected value.
366
+ */
367
+ function startWorkerThread(workerPath, { timeout = DEFAULT_TIMEOUT, execArgv = DEFAULT_EXEC_ARGV, tsRunner = DEFAULT_TS_RUNNER, transferList = [], globalShims = DEFAULT_GLOBAL_SHIMS } = {}) {
368
+ const { port1: mainPort, port2: workerPort } = new node_worker_threads.MessageChannel();
369
+ const { isTs, ext, jsUseEsm, tsUseEsm, tsRunner: finalTsRunner, workerPath: finalWorkerPath, pnpLoaderPath, execArgv: finalExecArgv } = setupTsRunner(workerPath, {
370
+ execArgv,
371
+ tsRunner
372
+ });
373
+ const workerPathUrl = (0, node_url.pathToFileURL)(finalWorkerPath);
374
+ if (/\.[cm]ts$/.test(finalWorkerPath)) {
375
+ const isTsxSupported = !tsUseEsm || TS_ESM_PARTIAL_SUPPORTED;
376
+ /* istanbul ignore if */
377
+ if (!finalTsRunner) throw new Error("No ts runner specified, ts worker path is not supported");
378
+ else if ([
379
+ TsRunner.EsbuildRegister,
380
+ TsRunner.EsbuildRunner,
381
+ ...TS_ESM_PARTIAL_SUPPORTED ? [TsRunner.OXC, TsRunner.SWC] : [],
382
+ ...isTsxSupported ? [] : [TsRunner.TSX]
383
+ ].includes(finalTsRunner)) throw new Error(`${finalTsRunner} is not supported for ${ext} files yet` + (isTsxSupported ? ", you can try [tsx](https://github.com/esbuild-kit/tsx) instead" : MTS_SUPPORTED ? ", you can try [oxc](https://github.com/oxc-project/oxc-node) or [swc](https://github.com/swc-project/swc-node/tree/master/packages/register) instead" : ""));
384
+ }
385
+ const finalGlobalShims = (globalShims === true ? DEFAULT_GLOBAL_SHIMS_PRESET : Array.isArray(globalShims) ? globalShims : []).filter(({ moduleName }) => (0, __pkgr_core.isPkgAvailable)(moduleName));
386
+ sharedBufferView ?? (sharedBufferView = new Int32Array(
387
+ /* istanbul ignore next */
388
+ sharedBuffer ?? (sharedBuffer = new SharedArrayBuffer(INT32_BYTES)),
389
+ 0,
390
+ 1
391
+ ));
392
+ const useGlobals = finalGlobalShims.length > 0;
393
+ const useEval = isTs ? !tsUseEsm : !jsUseEsm && useGlobals;
394
+ const worker = new node_worker_threads.Worker(jsUseEsm && useGlobals || tsUseEsm && finalTsRunner === TsRunner.TsNode ? dataUrl(`${generateGlobals(finalWorkerPath, finalGlobalShims)};import '${String(workerPathUrl)}'`) : useEval ? `${generateGlobals(finalWorkerPath, finalGlobalShims, "require")};${encodeImportModule(finalWorkerPath, "require")}` : workerPathUrl, {
395
+ eval: useEval,
396
+ workerData: {
397
+ sharedBufferView,
398
+ workerPort,
399
+ pnpLoaderPath
400
+ },
401
+ transferList: [workerPort, ...transferList],
402
+ execArgv: finalExecArgv
403
+ });
404
+ let nextID = 0;
405
+ const receiveMessageWithId = (port, expectedId, waitingTimeout) => {
406
+ const start = Date.now();
407
+ const status = Atomics.wait(sharedBufferView, 0, 0, waitingTimeout);
408
+ Atomics.store(sharedBufferView, 0, 0);
409
+ if (!["ok", "not-equal"].includes(status)) {
410
+ const abortMsg = {
411
+ id: expectedId,
412
+ cmd: "abort"
413
+ };
414
+ port.postMessage(abortMsg);
415
+ throw new Error("Internal error: Atomics.wait() failed: " + status);
416
+ }
417
+ const { id,...message } = (0, node_worker_threads.receiveMessageOnPort)(mainPort).message;
418
+ if (id < expectedId) {
419
+ const waitingTime = Date.now() - start;
420
+ return receiveMessageWithId(port, expectedId, waitingTimeout ? waitingTimeout - waitingTime : void 0);
421
+ }
422
+ if (expectedId !== id) throw new Error(`Internal error: Expected id ${expectedId} but got id ${id}`);
423
+ return {
424
+ id,
425
+ ...message
426
+ };
427
+ };
428
+ const syncFn = (...args) => {
429
+ const id = nextID++;
430
+ const msg = {
431
+ id,
432
+ args
433
+ };
434
+ worker.postMessage(msg);
435
+ const { result, error, properties, stdio } = receiveMessageWithId(mainPort, id, timeout);
436
+ for (const { type, chunk, encoding } of stdio) process[type].write(chunk, encoding);
437
+ if (error) throw Object.assign(error, properties);
438
+ return result;
439
+ };
440
+ worker.unref();
441
+ return syncFn;
544
442
  }
545
443
  const overrideStdio = (stdio) => {
546
- for (const type of ["stdout", "stderr"]) {
547
- process[type]._writev = (chunks, callback) => {
548
- for (const {
549
- // type-coverage:ignore-next-line -- we can't control
550
- chunk,
551
- encoding
552
- } of chunks) {
553
- stdio.push({
554
- type,
555
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- we can't control
556
- chunk,
557
- encoding
558
- });
559
- }
560
- callback();
561
- };
562
- }
444
+ for (const type of ["stdout", "stderr"]) process[type]._writev = (chunks, callback) => {
445
+ for (const { chunk, encoding } of chunks) stdio.push({
446
+ type,
447
+ chunk,
448
+ encoding
449
+ });
450
+ callback();
451
+ };
563
452
  };
564
453
 
565
- var __async = (__this, __arguments, generator) => {
566
- return new Promise((resolve, reject) => {
567
- var fulfilled = (value) => {
568
- try {
569
- step(generator.next(value));
570
- } catch (e) {
571
- reject(e);
572
- }
573
- };
574
- var rejected = (value) => {
575
- try {
576
- step(generator.throw(value));
577
- } catch (e) {
578
- reject(e);
579
- }
580
- };
581
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
582
- step((generator = generator.apply(__this, __arguments)).next());
583
- });
584
- };
454
+ //#endregion
455
+ //#region src/index.ts
585
456
  let syncFnCache;
457
+ /**
458
+ * Creates a synchronous worker function.
459
+ *
460
+ * Converts the provided worker path (URL or string) to an absolute file path,
461
+ * retrieves a cached synchronous function if one exists, or starts a new worker
462
+ * thread to handle task execution. The resulting function is cached to avoid
463
+ * redundant initialization.
464
+ *
465
+ * @param workerPath - The absolute file path or URL of the worker script. If
466
+ * given as a URL, it is converted to a file path.
467
+ * @param timeoutOrOptions - Optional timeout in milliseconds or an options
468
+ * object to configure the worker thread.
469
+ * @returns A synchronous function that executes tasks on the specified worker
470
+ * thread.
471
+ * @throws {Error} If the resulting worker path is not absolute.
472
+ */
586
473
  function createSyncFn(workerPath, timeoutOrOptions) {
587
- syncFnCache != null ? syncFnCache : syncFnCache = /* @__PURE__ */ new Map();
588
- if (typeof workerPath !== "string" || workerPath.startsWith("file://")) {
589
- workerPath = node_url.fileURLToPath(workerPath);
590
- }
591
- const cachedSyncFn = syncFnCache.get(workerPath);
592
- if (cachedSyncFn) {
593
- return cachedSyncFn;
594
- }
595
- if (!path.isAbsolute(workerPath)) {
596
- throw new Error("`workerPath` must be absolute");
597
- }
598
- const syncFn = startWorkerThread(
599
- workerPath,
600
- /* istanbul ignore next */
601
- typeof timeoutOrOptions === "number" ? { timeout: timeoutOrOptions } : timeoutOrOptions
602
- );
603
- syncFnCache.set(workerPath, syncFn);
604
- return syncFn;
474
+ syncFnCache ?? (syncFnCache = new Map());
475
+ if (typeof workerPath !== "string" || workerPath.startsWith("file://")) workerPath = (0, node_url.fileURLToPath)(workerPath);
476
+ const cachedSyncFn = syncFnCache.get(workerPath);
477
+ if (cachedSyncFn) return cachedSyncFn;
478
+ if (!node_path.default.isAbsolute(workerPath)) throw new Error("`workerPath` must be absolute");
479
+ const syncFn = startWorkerThread(
480
+ workerPath,
481
+ /* istanbul ignore next */
482
+ typeof timeoutOrOptions === "number" ? { timeout: timeoutOrOptions } : timeoutOrOptions
483
+ );
484
+ syncFnCache.set(workerPath, syncFn);
485
+ return syncFn;
605
486
  }
487
+ /* istanbul ignore next */
488
+ /**
489
+ * Configures the worker thread to listen for messages from the parent process
490
+ * and execute a provided function.
491
+ *
492
+ * If the worker is not initialized with the required data, the function exits
493
+ * without further action. Otherwise, it optionally registers a custom module
494
+ * loader when a valid loader path is provided and captures output generated
495
+ * during execution. It listens for messages containing an identifier and
496
+ * arguments, then invokes the supplied function asynchronously with those
497
+ * arguments. If an abort command is received for the same message, the response
498
+ * is suppressed. Upon completing execution, it posts a message back with either
499
+ * the result or error details, including extracted error properties.
500
+ *
501
+ * @param fn - The function to execute when a message is received.
502
+ */
606
503
  function runAsWorker(fn) {
607
- if (!node_worker_threads.workerData) {
608
- return;
609
- }
610
- const stdio = [];
611
- overrideStdio(stdio);
612
- const { workerPort, sharedBufferView, pnpLoaderPath } = node_worker_threads.workerData;
613
- if (pnpLoaderPath && MODULE_REGISTER_SUPPORTED) {
614
- module$1.register(pnpLoaderPath);
615
- }
616
- node_worker_threads.parentPort.on(
617
- "message",
618
- ({ id, args }) => {
619
- (() => __async(this, null, function* () {
620
- let isAborted = false;
621
- const handleAbortMessage = (msg2) => {
622
- if (msg2.id === id && msg2.cmd === "abort") {
623
- isAborted = true;
624
- }
625
- };
626
- workerPort.on("message", handleAbortMessage);
627
- let msg;
628
- try {
629
- msg = { id, stdio, result: yield fn(...args) };
630
- } catch (error) {
631
- msg = { id, stdio, error, properties: extractProperties(error) };
632
- }
633
- workerPort.off("message", handleAbortMessage);
634
- if (isAborted) {
635
- stdio.length = 0;
636
- return;
637
- }
638
- try {
639
- workerPort.postMessage(msg);
640
- Atomics.add(sharedBufferView, 0, 1);
641
- Atomics.notify(sharedBufferView, 0);
642
- } finally {
643
- stdio.length = 0;
644
- }
645
- }))();
646
- }
647
- );
504
+ if (!node_worker_threads.workerData) return;
505
+ const stdio = [];
506
+ overrideStdio(stdio);
507
+ const { workerPort, sharedBufferView: sharedBufferView$1, pnpLoaderPath } = node_worker_threads.workerData;
508
+ if (pnpLoaderPath && MODULE_REGISTER_SUPPORTED) node_module.default.register(pnpLoaderPath);
509
+ node_worker_threads.parentPort.on("message", ({ id, args }) => {
510
+ (async () => {
511
+ let isAborted = false;
512
+ const handleAbortMessage = (msg$1) => {
513
+ if (msg$1.id === id && msg$1.cmd === "abort") isAborted = true;
514
+ };
515
+ workerPort.on("message", handleAbortMessage);
516
+ let msg;
517
+ try {
518
+ msg = {
519
+ id,
520
+ stdio,
521
+ result: await fn(...args)
522
+ };
523
+ } catch (error) {
524
+ msg = {
525
+ id,
526
+ stdio,
527
+ error,
528
+ properties: extractProperties(error)
529
+ };
530
+ }
531
+ workerPort.off("message", handleAbortMessage);
532
+ if (isAborted) {
533
+ stdio.length = 0;
534
+ return;
535
+ }
536
+ try {
537
+ workerPort.postMessage(msg);
538
+ Atomics.add(sharedBufferView$1, 0, 1);
539
+ Atomics.notify(sharedBufferView$1, 0);
540
+ } finally {
541
+ stdio.length = 0;
542
+ }
543
+ })();
544
+ });
648
545
  }
649
546
 
547
+ //#endregion
650
548
  exports.DEFAULT_EXEC_ARGV = DEFAULT_EXEC_ARGV;
651
549
  exports.DEFAULT_GLOBAL_SHIMS = DEFAULT_GLOBAL_SHIMS;
652
550
  exports.DEFAULT_GLOBAL_SHIMS_PRESET = DEFAULT_GLOBAL_SHIMS_PRESET;
@@ -693,4 +591,4 @@ exports.overrideStdio = overrideStdio;
693
591
  exports.parseVersion = parseVersion;
694
592
  exports.runAsWorker = runAsWorker;
695
593
  exports.setupTsRunner = setupTsRunner;
696
- exports.startWorkerThread = startWorkerThread;
594
+ exports.startWorkerThread = startWorkerThread;