@scelar/nodepod 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/LICENSE +43 -0
  2. package/README.md +240 -0
  3. package/dist/child_process-BJOMsZje.js +8233 -0
  4. package/dist/child_process-BJOMsZje.js.map +1 -0
  5. package/dist/child_process-Cj8vOcuc.cjs +7434 -0
  6. package/dist/child_process-Cj8vOcuc.cjs.map +1 -0
  7. package/dist/index-Cb1Cgdnd.js +35308 -0
  8. package/dist/index-Cb1Cgdnd.js.map +1 -0
  9. package/dist/index-DsMGS-xc.cjs +37195 -0
  10. package/dist/index-DsMGS-xc.cjs.map +1 -0
  11. package/dist/index.cjs +65 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.mjs +59 -0
  14. package/dist/index.mjs.map +1 -0
  15. package/package.json +95 -0
  16. package/src/__tests__/smoke.test.ts +11 -0
  17. package/src/constants/cdn-urls.ts +18 -0
  18. package/src/constants/config.ts +236 -0
  19. package/src/cross-origin.ts +26 -0
  20. package/src/engine-factory.ts +176 -0
  21. package/src/engine-types.ts +56 -0
  22. package/src/helpers/byte-encoding.ts +39 -0
  23. package/src/helpers/digest.ts +9 -0
  24. package/src/helpers/event-loop.ts +96 -0
  25. package/src/helpers/wasm-cache.ts +133 -0
  26. package/src/iframe-sandbox.ts +141 -0
  27. package/src/index.ts +192 -0
  28. package/src/isolation-helpers.ts +148 -0
  29. package/src/memory-volume.ts +941 -0
  30. package/src/module-transformer.ts +368 -0
  31. package/src/packages/archive-extractor.ts +248 -0
  32. package/src/packages/browser-bundler.ts +284 -0
  33. package/src/packages/installer.ts +396 -0
  34. package/src/packages/registry-client.ts +131 -0
  35. package/src/packages/version-resolver.ts +411 -0
  36. package/src/polyfills/assert.ts +384 -0
  37. package/src/polyfills/async_hooks.ts +144 -0
  38. package/src/polyfills/buffer.ts +628 -0
  39. package/src/polyfills/child_process.ts +2288 -0
  40. package/src/polyfills/chokidar.ts +336 -0
  41. package/src/polyfills/cluster.ts +106 -0
  42. package/src/polyfills/console.ts +136 -0
  43. package/src/polyfills/constants.ts +123 -0
  44. package/src/polyfills/crypto.ts +885 -0
  45. package/src/polyfills/dgram.ts +87 -0
  46. package/src/polyfills/diagnostics_channel.ts +76 -0
  47. package/src/polyfills/dns.ts +134 -0
  48. package/src/polyfills/domain.ts +68 -0
  49. package/src/polyfills/esbuild.ts +854 -0
  50. package/src/polyfills/events.ts +276 -0
  51. package/src/polyfills/fs.ts +2888 -0
  52. package/src/polyfills/fsevents.ts +79 -0
  53. package/src/polyfills/http.ts +1449 -0
  54. package/src/polyfills/http2.ts +199 -0
  55. package/src/polyfills/https.ts +76 -0
  56. package/src/polyfills/inspector.ts +62 -0
  57. package/src/polyfills/lightningcss.ts +105 -0
  58. package/src/polyfills/module.ts +191 -0
  59. package/src/polyfills/net.ts +353 -0
  60. package/src/polyfills/os.ts +238 -0
  61. package/src/polyfills/path.ts +206 -0
  62. package/src/polyfills/perf_hooks.ts +102 -0
  63. package/src/polyfills/process.ts +690 -0
  64. package/src/polyfills/punycode.ts +159 -0
  65. package/src/polyfills/querystring.ts +93 -0
  66. package/src/polyfills/quic.ts +118 -0
  67. package/src/polyfills/readdirp.ts +229 -0
  68. package/src/polyfills/readline.ts +692 -0
  69. package/src/polyfills/repl.ts +134 -0
  70. package/src/polyfills/rollup.ts +119 -0
  71. package/src/polyfills/sea.ts +33 -0
  72. package/src/polyfills/sqlite.ts +78 -0
  73. package/src/polyfills/stream.ts +1620 -0
  74. package/src/polyfills/string_decoder.ts +25 -0
  75. package/src/polyfills/tailwindcss-oxide.ts +309 -0
  76. package/src/polyfills/test.ts +197 -0
  77. package/src/polyfills/timers.ts +32 -0
  78. package/src/polyfills/tls.ts +105 -0
  79. package/src/polyfills/trace_events.ts +50 -0
  80. package/src/polyfills/tty.ts +71 -0
  81. package/src/polyfills/url.ts +174 -0
  82. package/src/polyfills/util.ts +559 -0
  83. package/src/polyfills/v8.ts +126 -0
  84. package/src/polyfills/vm.ts +132 -0
  85. package/src/polyfills/volume-registry.ts +15 -0
  86. package/src/polyfills/wasi.ts +44 -0
  87. package/src/polyfills/worker_threads.ts +326 -0
  88. package/src/polyfills/ws.ts +595 -0
  89. package/src/polyfills/zlib.ts +881 -0
  90. package/src/request-proxy.ts +716 -0
  91. package/src/script-engine.ts +3375 -0
  92. package/src/sdk/nodepod-fs.ts +93 -0
  93. package/src/sdk/nodepod-process.ts +86 -0
  94. package/src/sdk/nodepod-terminal.ts +350 -0
  95. package/src/sdk/nodepod.ts +509 -0
  96. package/src/sdk/types.ts +70 -0
  97. package/src/shell/commands/bun.ts +121 -0
  98. package/src/shell/commands/directory.ts +297 -0
  99. package/src/shell/commands/file-ops.ts +525 -0
  100. package/src/shell/commands/git.ts +2142 -0
  101. package/src/shell/commands/node.ts +80 -0
  102. package/src/shell/commands/npm.ts +198 -0
  103. package/src/shell/commands/pm-types.ts +45 -0
  104. package/src/shell/commands/pnpm.ts +82 -0
  105. package/src/shell/commands/search.ts +264 -0
  106. package/src/shell/commands/shell-env.ts +352 -0
  107. package/src/shell/commands/text-processing.ts +1152 -0
  108. package/src/shell/commands/yarn.ts +84 -0
  109. package/src/shell/shell-builtins.ts +19 -0
  110. package/src/shell/shell-helpers.ts +250 -0
  111. package/src/shell/shell-interpreter.ts +514 -0
  112. package/src/shell/shell-parser.ts +429 -0
  113. package/src/shell/shell-types.ts +85 -0
  114. package/src/syntax-transforms.ts +561 -0
  115. package/src/threading/engine-worker.ts +64 -0
  116. package/src/threading/inline-worker.ts +372 -0
  117. package/src/threading/offload-types.ts +112 -0
  118. package/src/threading/offload-worker.ts +383 -0
  119. package/src/threading/offload.ts +271 -0
  120. package/src/threading/process-context.ts +92 -0
  121. package/src/threading/process-handle.ts +275 -0
  122. package/src/threading/process-manager.ts +956 -0
  123. package/src/threading/process-worker-entry.ts +854 -0
  124. package/src/threading/shared-vfs.ts +352 -0
  125. package/src/threading/sync-channel.ts +135 -0
  126. package/src/threading/task-queue.ts +177 -0
  127. package/src/threading/vfs-bridge.ts +231 -0
  128. package/src/threading/worker-pool.ts +233 -0
  129. package/src/threading/worker-protocol.ts +358 -0
  130. package/src/threading/worker-vfs.ts +218 -0
  131. package/src/types/externals.d.ts +38 -0
  132. package/src/types/fs-streams.ts +142 -0
  133. package/src/types/manifest.ts +17 -0
  134. package/src/worker-sandbox.ts +90 -0
@@ -0,0 +1,383 @@
1
+ // Offload Worker entry point — runs transform/extract/build tasks in a dedicated thread.
2
+ // Tar parser and base64 helpers are duplicated here since workers can't share module state.
3
+
4
+ import { expose } from "comlink";
5
+ import type {
6
+ OffloadWorkerEndpoint,
7
+ TransformTask,
8
+ TransformResult,
9
+ ExtractTask,
10
+ ExtractResult,
11
+ ExtractedFile,
12
+ BuildTask,
13
+ BuildResult,
14
+ BuildOutputFile,
15
+ } from "./offload-types";
16
+
17
+ let esbuildEngine: any = null;
18
+ let pakoModule: any = null;
19
+ let initialized = false;
20
+
21
+ import { CDN_ESBUILD_ESM, CDN_ESBUILD_BINARY, cdnImport } from "../constants/cdn-urls";
22
+ import { CDN_PAKO } from "../constants/config";
23
+
24
+ const ESBUILD_ESM_URL = CDN_ESBUILD_ESM;
25
+ const ESBUILD_WASM_URL = CDN_ESBUILD_BINARY;
26
+ const PAKO_URL = CDN_PAKO;
27
+
28
+ // --- Base64 helpers (duplicated from helpers/byte-encoding.ts) ---
29
+
30
+ const SEGMENT_SIZE = 8192;
31
+
32
+ function uint8ToBase64(data: Uint8Array): string {
33
+ const segments: string[] = [];
34
+ for (let offset = 0; offset < data.length; offset += SEGMENT_SIZE) {
35
+ segments.push(
36
+ String.fromCharCode.apply(
37
+ null,
38
+ Array.from(data.subarray(offset, offset + SEGMENT_SIZE)),
39
+ ),
40
+ );
41
+ }
42
+ return btoa(segments.join(""));
43
+ }
44
+
45
+ // --- Tar parser (duplicated from packages/archive-extractor.ts) ---
46
+
47
+ function readNullTerminated(
48
+ buf: Uint8Array,
49
+ start: number,
50
+ len: number,
51
+ ): string {
52
+ const slice = buf.slice(start, start + len);
53
+ const zeroPos = slice.indexOf(0);
54
+ const trimmed = zeroPos >= 0 ? slice.slice(0, zeroPos) : slice;
55
+ return new TextDecoder().decode(trimmed);
56
+ }
57
+
58
+ function readOctalField(
59
+ buf: Uint8Array,
60
+ start: number,
61
+ len: number,
62
+ ): number {
63
+ const raw = readNullTerminated(buf, start, len).trim();
64
+ return parseInt(raw, 8) || 0;
65
+ }
66
+
67
+ type EntryKind = "file" | "directory" | "link" | "other";
68
+
69
+ function classifyTypeFlag(flag: string): EntryKind {
70
+ switch (flag) {
71
+ case "0":
72
+ case "\0":
73
+ case "":
74
+ return "file";
75
+ case "5":
76
+ return "directory";
77
+ case "1":
78
+ case "2":
79
+ return "link";
80
+ default:
81
+ return "other";
82
+ }
83
+ }
84
+
85
+ interface TarEntry {
86
+ filepath: string;
87
+ kind: EntryKind;
88
+ byteSize: number;
89
+ payload?: Uint8Array;
90
+ }
91
+
92
+ function* parseTar(raw: Uint8Array): Generator<TarEntry> {
93
+ const BLOCK = 512;
94
+ let cursor = 0;
95
+
96
+ while (cursor + BLOCK <= raw.length) {
97
+ const header = raw.slice(cursor, cursor + BLOCK);
98
+ cursor += BLOCK;
99
+
100
+ if (header.every((b) => b === 0)) break;
101
+
102
+ const nameField = readNullTerminated(header, 0, 100);
103
+ if (!nameField) continue;
104
+
105
+ const byteSize = readOctalField(header, 124, 12);
106
+ const typeChar = String.fromCharCode(header[156]);
107
+ const prefixField = readNullTerminated(header, 345, 155);
108
+ const filepath = prefixField
109
+ ? `${prefixField}/${nameField}`
110
+ : nameField;
111
+ const kind = classifyTypeFlag(typeChar);
112
+
113
+ let payload: Uint8Array | undefined;
114
+ if (kind === "file") {
115
+ payload =
116
+ byteSize > 0
117
+ ? raw.slice(cursor, cursor + byteSize)
118
+ : new Uint8Array(0);
119
+ if (byteSize > 0) {
120
+ cursor += Math.ceil(byteSize / BLOCK) * BLOCK;
121
+ }
122
+ }
123
+
124
+ yield { filepath, kind, byteSize, payload };
125
+ }
126
+ }
127
+
128
+ // --- JSX detection (duplicated from module-transformer.ts) ---
129
+
130
+ function detectJsx(source: string): boolean {
131
+ if (/<[A-Z][a-zA-Z0-9.]*[\s/>]/.test(source)) return true;
132
+ if (/<\/[a-zA-Z]/.test(source)) return true;
133
+ if (/\/>/.test(source)) return true;
134
+ if (/<>|<\/>/.test(source)) return true;
135
+ if (/React\.createElement\b/.test(source)) return true;
136
+ if (/jsx\(|jsxs\(|jsxDEV\(/.test(source)) return true;
137
+ return false;
138
+ }
139
+
140
+ // --- Default define map for esbuild transforms ---
141
+
142
+ const DEFAULT_DEFINE: Record<string, string> = {
143
+ "import.meta.url": "import_meta.url",
144
+ "import.meta.dirname": "import_meta.dirname",
145
+ "import.meta.filename": "import_meta.filename",
146
+ "import.meta": "import_meta",
147
+ };
148
+
149
+ // --- Worker endpoint ---
150
+
151
+ const workerEndpoint: OffloadWorkerEndpoint = {
152
+ async init(): Promise<void> {
153
+ if (initialized) return;
154
+
155
+ const pakoMod = await cdnImport(PAKO_URL);
156
+ pakoModule = pakoMod.default || pakoMod;
157
+
158
+ const esbuildMod = await cdnImport(ESBUILD_ESM_URL);
159
+ esbuildEngine = esbuildMod.default || esbuildMod;
160
+
161
+ try {
162
+ await esbuildEngine.initialize({ wasmURL: ESBUILD_WASM_URL });
163
+ } catch (err: any) {
164
+ if (
165
+ !(
166
+ err instanceof Error &&
167
+ err.message.includes('Cannot call "initialize" more than once')
168
+ )
169
+ ) {
170
+ throw err;
171
+ }
172
+ }
173
+
174
+ initialized = true;
175
+ },
176
+
177
+ async transform(task: TransformTask): Promise<TransformResult> {
178
+ if (!esbuildEngine) throw new Error("Worker not initialized");
179
+
180
+ const opts = task.options || {};
181
+ let loader: string = opts.loader || "js";
182
+ const format = opts.format || "cjs";
183
+ const define = opts.define || DEFAULT_DEFINE;
184
+
185
+ if (loader === "js" && detectJsx(task.source)) loader = "jsx";
186
+
187
+ const transformOpts = {
188
+ loader,
189
+ format,
190
+ target: opts.target || "esnext",
191
+ platform: opts.platform || "neutral",
192
+ define,
193
+ };
194
+
195
+ try {
196
+ const output = await esbuildEngine.transform(task.source, transformOpts);
197
+ return {
198
+ type: "transform" as const,
199
+ id: task.id,
200
+ code: output.code,
201
+ warnings: (output.warnings || []).map(
202
+ (w: any) => w.text || String(w),
203
+ ),
204
+ };
205
+ } catch (err: any) {
206
+ // Retry with fallback loaders
207
+ const fallbacks: string[] =
208
+ loader === "js"
209
+ ? ["jsx", "tsx", "ts"]
210
+ : loader === "jsx"
211
+ ? ["tsx"]
212
+ : [];
213
+
214
+ for (const fb of fallbacks) {
215
+ try {
216
+ const output = await esbuildEngine.transform(task.source, {
217
+ ...transformOpts,
218
+ loader: fb,
219
+ });
220
+ return {
221
+ type: "transform" as const,
222
+ id: task.id,
223
+ code: output.code,
224
+ warnings: [],
225
+ };
226
+ } catch {
227
+ /* try next fallback */
228
+ }
229
+ }
230
+
231
+ // TLA: fall back to ESM format
232
+ if (err?.message?.includes("Top-level await")) {
233
+ try {
234
+ const output = await esbuildEngine.transform(task.source, {
235
+ ...transformOpts,
236
+ format: "esm",
237
+ });
238
+ return {
239
+ type: "transform" as const,
240
+ id: task.id,
241
+ code: output.code,
242
+ warnings: [],
243
+ };
244
+ } catch {
245
+ /* fall through */
246
+ }
247
+ }
248
+
249
+ // All retries exhausted — return original source
250
+ return {
251
+ type: "transform" as const,
252
+ id: task.id,
253
+ code: task.source,
254
+ warnings: [err?.message || "transform failed"],
255
+ };
256
+ }
257
+ },
258
+
259
+ async extract(task: ExtractTask): Promise<ExtractResult> {
260
+ if (!pakoModule) throw new Error("Worker not initialized");
261
+
262
+ const response = await fetch(task.tarballUrl);
263
+ if (!response.ok) {
264
+ throw new Error(
265
+ `Archive download failed (HTTP ${response.status}): ${task.tarballUrl}`,
266
+ );
267
+ }
268
+
269
+ const compressed = new Uint8Array(await response.arrayBuffer());
270
+ const tarBytes = pakoModule.inflate(compressed) as Uint8Array;
271
+
272
+ const files: ExtractedFile[] = [];
273
+ for (const entry of parseTar(tarBytes)) {
274
+ if (entry.kind !== "file" && entry.kind !== "directory") continue;
275
+
276
+ let relative = entry.filepath;
277
+ if (task.stripComponents > 0) {
278
+ const segments = relative.split("/").filter(Boolean);
279
+ if (segments.length <= task.stripComponents) continue;
280
+ relative = segments.slice(task.stripComponents).join("/");
281
+ }
282
+
283
+ if (entry.kind === "file" && entry.payload) {
284
+ let data: string;
285
+ let isBinary = false;
286
+ try {
287
+ data = new TextDecoder("utf-8", { fatal: true }).decode(
288
+ entry.payload,
289
+ );
290
+ } catch {
291
+ data = uint8ToBase64(entry.payload);
292
+ isBinary = true;
293
+ }
294
+ files.push({ path: relative, data, isBinary });
295
+ }
296
+ }
297
+
298
+ return { type: "extract" as const, id: task.id, files };
299
+ },
300
+
301
+ async build(task: BuildTask): Promise<BuildResult> {
302
+ if (!esbuildEngine) throw new Error("Worker not initialized");
303
+
304
+ const fileMap = new Map<string, string>();
305
+ for (const [p, content] of Object.entries(task.files)) {
306
+ fileMap.set(p, content);
307
+ }
308
+
309
+ const volumePlugin = {
310
+ name: "offload-volume",
311
+ setup(build: any) {
312
+ build.onLoad({ filter: /.*/ }, (args: any) => {
313
+ const content = fileMap.get(args.path);
314
+ if (content === undefined) return null;
315
+ const ext = args.path.substring(args.path.lastIndexOf("."));
316
+ const loaderMap: Record<string, string> = {
317
+ ".ts": "ts",
318
+ ".tsx": "tsx",
319
+ ".js": "js",
320
+ ".mjs": "js",
321
+ ".cjs": "js",
322
+ ".jsx": "jsx",
323
+ ".json": "json",
324
+ ".css": "css",
325
+ };
326
+ return {
327
+ contents: content,
328
+ loader: loaderMap[ext] || undefined,
329
+ };
330
+ });
331
+ },
332
+ };
333
+
334
+ try {
335
+ const result = await esbuildEngine.build({
336
+ entryPoints: task.entryPoints,
337
+ stdin: task.stdin,
338
+ bundle: task.bundle ?? true,
339
+ format: task.format || "esm",
340
+ platform: task.platform || "browser",
341
+ target: task.target || "esnext",
342
+ minify: task.minify ?? false,
343
+ external: task.external,
344
+ write: false,
345
+ plugins: [volumePlugin],
346
+ absWorkingDir: task.absWorkingDir || "/",
347
+ });
348
+
349
+ const outputFiles: BuildOutputFile[] = (result.outputFiles || []).map(
350
+ (f: any) => ({
351
+ path: f.path,
352
+ text: f.text || new TextDecoder().decode(f.contents),
353
+ }),
354
+ );
355
+
356
+ return {
357
+ type: "build" as const,
358
+ id: task.id,
359
+ outputFiles,
360
+ errors: (result.errors || []).map(
361
+ (e: any) => e.text || String(e),
362
+ ),
363
+ warnings: (result.warnings || []).map(
364
+ (w: any) => w.text || String(w),
365
+ ),
366
+ };
367
+ } catch (err: any) {
368
+ return {
369
+ type: "build" as const,
370
+ id: task.id,
371
+ outputFiles: [],
372
+ errors: [err?.message || "build failed"],
373
+ warnings: [],
374
+ };
375
+ }
376
+ },
377
+
378
+ ping(): boolean {
379
+ return true;
380
+ },
381
+ };
382
+
383
+ expose(workerEndpoint);
@@ -0,0 +1,271 @@
1
+ // Offload API — routes CPU-heavy tasks (esbuild, tarball extraction, bundling)
2
+ // to a Web Worker pool. Falls back to main-thread if Workers aren't available.
3
+
4
+ import { WorkerPool } from "./worker-pool";
5
+ import { TaskQueue } from "./task-queue";
6
+ import type {
7
+ OffloadTask,
8
+ OffloadResult,
9
+ PoolConfig,
10
+ TransformTask,
11
+ TransformResult,
12
+ ExtractTask,
13
+ ExtractResult,
14
+ BuildTask,
15
+ BuildResult,
16
+ } from "./offload-types";
17
+
18
+ export { TaskPriority } from "./offload-types";
19
+ export type {
20
+ TransformTask,
21
+ TransformResult,
22
+ ExtractTask,
23
+ ExtractResult,
24
+ BuildTask,
25
+ BuildResult,
26
+ OffloadTask,
27
+ OffloadResult,
28
+ PoolConfig,
29
+ } from "./offload-types";
30
+
31
+ // --- Singleton state ---
32
+
33
+ let pool: WorkerPool | null = null;
34
+ let queue: TaskQueue | null = null;
35
+ let fallbackMode = false;
36
+ let storedConfig: PoolConfig | undefined;
37
+
38
+ // --- Environment detection ---
39
+
40
+ function canUseWorkers(): boolean {
41
+ return (
42
+ typeof Worker !== "undefined" &&
43
+ typeof Blob !== "undefined" &&
44
+ typeof URL !== "undefined" &&
45
+ typeof URL.createObjectURL === "function"
46
+ );
47
+ }
48
+
49
+ // --- Pool lifecycle ---
50
+
51
+ function ensurePool(): TaskQueue {
52
+ if (queue) return queue;
53
+
54
+ if (!canUseWorkers()) {
55
+ fallbackMode = true;
56
+ throw new Error("Workers not available");
57
+ }
58
+
59
+ pool = new WorkerPool(storedConfig);
60
+ queue = new TaskQueue(pool);
61
+ return queue;
62
+ }
63
+
64
+ // --- Main-thread fallback implementations ---
65
+
66
+ async function mainThreadTransform(
67
+ task: TransformTask,
68
+ ): Promise<TransformResult> {
69
+ // convertFileDirect, not convertFile — avoids circular: convertFile → offload → fallback → loop
70
+ const { convertFileDirect, prepareTransformer } = await import(
71
+ "../module-transformer"
72
+ );
73
+ await prepareTransformer();
74
+
75
+ const code = await convertFileDirect(task.source, task.filePath);
76
+ return { type: "transform", id: task.id, code, warnings: [] };
77
+ }
78
+
79
+ async function mainThreadExtract(
80
+ task: ExtractTask,
81
+ ): Promise<ExtractResult> {
82
+ const pako = await import("pako");
83
+ const { parseTarArchive } = await import("../packages/archive-extractor");
84
+ const { bytesToBase64 } = await import("../helpers/byte-encoding");
85
+
86
+ const response = await fetch(task.tarballUrl);
87
+ if (!response.ok) {
88
+ throw new Error(
89
+ `Archive download failed (HTTP ${response.status}): ${task.tarballUrl}`,
90
+ );
91
+ }
92
+
93
+ const compressed = new Uint8Array(await response.arrayBuffer());
94
+ const tarBytes = pako.inflate(compressed);
95
+
96
+ const files: ExtractResult["files"] = [];
97
+ for (const entry of parseTarArchive(tarBytes)) {
98
+ if (entry.kind !== "file" || !entry.payload) continue;
99
+
100
+ let relative = entry.filepath;
101
+ if (task.stripComponents > 0) {
102
+ const segments = relative.split("/").filter(Boolean);
103
+ if (segments.length <= task.stripComponents) continue;
104
+ relative = segments.slice(task.stripComponents).join("/");
105
+ }
106
+
107
+ let data: string;
108
+ let isBinary = false;
109
+ try {
110
+ data = new TextDecoder("utf-8", { fatal: true }).decode(entry.payload);
111
+ } catch {
112
+ data = bytesToBase64(entry.payload);
113
+ isBinary = true;
114
+ }
115
+ files.push({ path: relative, data, isBinary });
116
+ }
117
+
118
+ return { type: "extract", id: task.id, files };
119
+ }
120
+
121
+ async function mainThreadBuild(task: BuildTask): Promise<BuildResult> {
122
+ const esbuild = await import("../polyfills/esbuild");
123
+ try {
124
+ const result = await (esbuild as any).build({
125
+ entryPoints: task.entryPoints,
126
+ stdin: task.stdin,
127
+ bundle: task.bundle,
128
+ format: task.format,
129
+ platform: task.platform,
130
+ target: task.target,
131
+ minify: task.minify,
132
+ external: task.external,
133
+ write: false,
134
+ absWorkingDir: task.absWorkingDir,
135
+ });
136
+ return {
137
+ type: "build",
138
+ id: task.id,
139
+ outputFiles: (result.outputFiles || []).map((f: any) => ({
140
+ path: f.path,
141
+ text: f.text || new TextDecoder().decode(f.contents),
142
+ })),
143
+ errors: (result.errors || []).map((e: any) => e.text || String(e)),
144
+ warnings: (result.warnings || []).map(
145
+ (w: any) => w.text || String(w),
146
+ ),
147
+ };
148
+ } catch (err: any) {
149
+ return {
150
+ type: "build",
151
+ id: task.id,
152
+ outputFiles: [],
153
+ errors: [err?.message || "build failed"],
154
+ warnings: [],
155
+ };
156
+ }
157
+ }
158
+
159
+ // --- Public API ---
160
+
161
+ export function taskId(): string {
162
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
163
+ return crypto.randomUUID();
164
+ }
165
+ return `task-${Date.now()}-${Math.random().toString(36).slice(2)}`;
166
+ }
167
+
168
+ export async function offload<T extends OffloadTask>(
169
+ task: T,
170
+ ): Promise<
171
+ T extends TransformTask
172
+ ? TransformResult
173
+ : T extends ExtractTask
174
+ ? ExtractResult
175
+ : T extends BuildTask
176
+ ? BuildResult
177
+ : OffloadResult
178
+ > {
179
+ // Fast path: already know Workers aren't available
180
+ if (fallbackMode) {
181
+ return runFallback(task) as any;
182
+ }
183
+
184
+ try {
185
+ const q = ensurePool();
186
+ return await q.submit(task) as any;
187
+ } catch (err) {
188
+ // Log once so consumers know fallback is active
189
+ if (!fallbackMode) {
190
+ console.debug(
191
+ "[offload] Falling back to main thread:",
192
+ err instanceof Error ? err.message : err,
193
+ );
194
+ }
195
+ switchToFallback();
196
+ return runFallback(task) as any;
197
+ }
198
+ }
199
+
200
+ export async function offloadBatch(
201
+ tasks: OffloadTask[],
202
+ ): Promise<OffloadResult[]> {
203
+ if (fallbackMode) {
204
+ return Promise.all(tasks.map((t) => runFallback(t)));
205
+ }
206
+
207
+ try {
208
+ const q = ensurePool();
209
+ return await q.submitBatch(tasks);
210
+ } catch {
211
+ switchToFallback();
212
+ return Promise.all(tasks.map((t) => runFallback(t)));
213
+ }
214
+ }
215
+
216
+ function switchToFallback(): void {
217
+ fallbackMode = true;
218
+ if (pool) {
219
+ pool.dispose();
220
+ pool = null;
221
+ }
222
+ queue = null;
223
+ }
224
+
225
+ async function runFallback(task: OffloadTask): Promise<OffloadResult> {
226
+ switch (task.type) {
227
+ case "transform":
228
+ return mainThreadTransform(task);
229
+ case "extract":
230
+ return mainThreadExtract(task);
231
+ case "build":
232
+ return mainThreadBuild(task);
233
+ default:
234
+ throw new Error(`Unknown task type: ${(task as any).type}`);
235
+ }
236
+ }
237
+
238
+ export function cancelTask(id: string): boolean {
239
+ return queue?.cancel(id) ?? false;
240
+ }
241
+
242
+ export function poolStats(): {
243
+ total: number;
244
+ busy: number;
245
+ idle: number;
246
+ initialized: number;
247
+ fallback: boolean;
248
+ } {
249
+ const stats = pool?.stats() ?? {
250
+ total: 0,
251
+ busy: 0,
252
+ idle: 0,
253
+ initialized: 0,
254
+ };
255
+ return { ...stats, fallback: fallbackMode };
256
+ }
257
+
258
+ export function disposePool(): void {
259
+ queue = null;
260
+ pool?.dispose();
261
+ pool = null;
262
+ fallbackMode = false;
263
+ }
264
+
265
+ // Must be called before any offload() task is submitted
266
+ export function configurePool(config: PoolConfig): void {
267
+ if (pool) {
268
+ throw new Error("Pool already created; call disposePool() first");
269
+ }
270
+ storedConfig = config;
271
+ }