@secure-exec/browser 0.0.0-agentos-dylib-base.edaa4a4

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 (66) hide show
  1. package/README.md +6 -0
  2. package/dist/child-process-bridge.d.ts +25 -0
  3. package/dist/child-process-bridge.js +50 -0
  4. package/dist/converged-base64.d.ts +2 -0
  5. package/dist/converged-base64.js +41 -0
  6. package/dist/converged-dgram-bridge.d.ts +11 -0
  7. package/dist/converged-dgram-bridge.js +147 -0
  8. package/dist/converged-driver-setup.d.ts +22 -0
  9. package/dist/converged-driver-setup.js +72 -0
  10. package/dist/converged-execution-host-bridge.d.ts +7 -0
  11. package/dist/converged-execution-host-bridge.js +85 -0
  12. package/dist/converged-executor-session.d.ts +60 -0
  13. package/dist/converged-executor-session.js +127 -0
  14. package/dist/converged-fs-bridge.d.ts +42 -0
  15. package/dist/converged-fs-bridge.js +245 -0
  16. package/dist/converged-module-servicer.d.ts +8 -0
  17. package/dist/converged-module-servicer.js +79 -0
  18. package/dist/converged-net-bridge.d.ts +28 -0
  19. package/dist/converged-net-bridge.js +155 -0
  20. package/dist/converged-permissions.d.ts +9 -0
  21. package/dist/converged-permissions.js +46 -0
  22. package/dist/converged-sync-bridge-handler.d.ts +47 -0
  23. package/dist/converged-sync-bridge-handler.js +140 -0
  24. package/dist/converged-sync-bridge-router.d.ts +33 -0
  25. package/dist/converged-sync-bridge-router.js +41 -0
  26. package/dist/driver.d.ts +91 -0
  27. package/dist/driver.js +386 -0
  28. package/dist/encoding.d.ts +4 -0
  29. package/dist/encoding.js +102 -0
  30. package/dist/generated/util-polyfill.d.ts +1 -0
  31. package/dist/generated/util-polyfill.js +2 -0
  32. package/dist/index.d.ts +9 -0
  33. package/dist/index.js +5 -0
  34. package/dist/kernel-backed-filesystem.d.ts +33 -0
  35. package/dist/kernel-backed-filesystem.js +205 -0
  36. package/dist/os-filesystem.d.ts +47 -0
  37. package/dist/os-filesystem.js +409 -0
  38. package/dist/permission-validation.d.ts +15 -0
  39. package/dist/permission-validation.js +62 -0
  40. package/dist/root-filesystem-from-vfs.d.ts +13 -0
  41. package/dist/root-filesystem-from-vfs.js +95 -0
  42. package/dist/runtime-driver.d.ts +66 -0
  43. package/dist/runtime-driver.js +611 -0
  44. package/dist/runtime.d.ts +248 -0
  45. package/dist/runtime.js +2296 -0
  46. package/dist/sidecar-wasm-module.d.ts +62 -0
  47. package/dist/sidecar-wasm-module.js +28 -0
  48. package/dist/sidecar-worker-protocol.d.ts +14 -0
  49. package/dist/sidecar-worker-protocol.js +9 -0
  50. package/dist/sidecar-worker.d.ts +19 -0
  51. package/dist/sidecar-worker.js +63 -0
  52. package/dist/signals.d.ts +13 -0
  53. package/dist/signals.js +89 -0
  54. package/dist/sync-bridge.d.ts +50 -0
  55. package/dist/sync-bridge.js +93 -0
  56. package/dist/wasi-polyfill.d.ts +1 -0
  57. package/dist/wasi-polyfill.js +2154 -0
  58. package/dist/worker-adapter.d.ts +21 -0
  59. package/dist/worker-adapter.js +41 -0
  60. package/dist/worker-protocol.d.ts +104 -0
  61. package/dist/worker-protocol.js +1 -0
  62. package/dist/worker-sidecar-client.d.ts +71 -0
  63. package/dist/worker-sidecar-client.js +152 -0
  64. package/dist/worker.d.ts +1 -0
  65. package/dist/worker.js +2125 -0
  66. package/package.json +111 -0
@@ -0,0 +1,2296 @@
1
+ import { createInMemoryFileSystem, InMemoryFileSystem, } from "./os-filesystem.js";
2
+ import { guestEncodingBootstrapCode } from "./encoding.js";
3
+ import { BROWSER_WASI_POLYFILL_CODE } from "./wasi-polyfill.js";
4
+ import { PROCESS_SIGNAL_NUMBERS } from "./signals.js";
5
+ import { BROWSER_UTIL_POLYFILL_CODE } from "./generated/util-polyfill.js";
6
+ export const allowAllFs = () => true;
7
+ export const allowAllNetwork = () => true;
8
+ export const allowAllChildProcess = () => true;
9
+ export const allowAllEnv = () => true;
10
+ export const allowAll = {
11
+ fs: allowAllFs,
12
+ network: allowAllNetwork,
13
+ childProcess: allowAllChildProcess,
14
+ env: allowAllEnv,
15
+ };
16
+ function normalizePath(inputPath) {
17
+ if (!inputPath)
18
+ return "/";
19
+ let normalized = inputPath.startsWith("/") ? inputPath : `/${inputPath}`;
20
+ normalized = normalized.replace(/\/+/g, "/");
21
+ if (normalized.length > 1 && normalized.endsWith("/")) {
22
+ normalized = normalized.slice(0, -1);
23
+ }
24
+ const parts = normalized.split("/");
25
+ const resolved = [];
26
+ for (const part of parts) {
27
+ if (!part || part === ".")
28
+ continue;
29
+ if (part === "..") {
30
+ resolved.pop();
31
+ continue;
32
+ }
33
+ resolved.push(part);
34
+ }
35
+ return resolved.length === 0 ? "/" : `/${resolved.join("/")}`;
36
+ }
37
+ function dirname(inputPath) {
38
+ const normalized = normalizePath(inputPath);
39
+ if (normalized === "/")
40
+ return "/";
41
+ const parts = normalized.split("/").filter(Boolean);
42
+ return parts.length <= 1 ? "/" : `/${parts.slice(0, -1).join("/")}`;
43
+ }
44
+ export function permissionAllowed(decision) {
45
+ if (decision === undefined)
46
+ return true;
47
+ if (typeof decision === "boolean")
48
+ return decision;
49
+ return "allowed" in decision ? decision.allowed : decision.allow;
50
+ }
51
+ export function filterEnv(env, permissions) {
52
+ const source = env ?? {};
53
+ if (!permissions?.env)
54
+ return { ...source };
55
+ const output = {};
56
+ for (const [name, value] of Object.entries(source)) {
57
+ if (permissionAllowed(permissions.env({ name, value }))) {
58
+ output[name] = value;
59
+ }
60
+ }
61
+ return output;
62
+ }
63
+ export function createEnosysError(operation) {
64
+ const error = new Error(`ENOSYS: ${operation} is not supported`);
65
+ error.code = "ENOSYS";
66
+ return error;
67
+ }
68
+ export function createFsStub() {
69
+ return createInMemoryFileSystem();
70
+ }
71
+ export function createNetworkStub() {
72
+ return {
73
+ async fetch() {
74
+ throw createEnosysError("network.fetch");
75
+ },
76
+ async dnsLookup() {
77
+ return { error: "DNS not supported", code: "ENOSYS" };
78
+ },
79
+ async httpRequest() {
80
+ throw createEnosysError("network.httpRequest");
81
+ },
82
+ };
83
+ }
84
+ export function createCommandExecutorStub() {
85
+ return {
86
+ spawn() {
87
+ throw createEnosysError("child_process.spawn");
88
+ },
89
+ };
90
+ }
91
+ export function wrapCommandExecutor(adapter, permissions) {
92
+ if (!permissions?.childProcess)
93
+ return adapter;
94
+ const check = (command, args, options) => {
95
+ if (!permissionAllowed(permissions.childProcess?.({
96
+ command,
97
+ args,
98
+ cwd: options?.cwd,
99
+ env: options?.env,
100
+ }))) {
101
+ const error = new Error(`EACCES: blocked child_process spawn '${command}'`);
102
+ error.code = "EACCES";
103
+ throw error;
104
+ }
105
+ };
106
+ return {
107
+ spawn(command, args, options) {
108
+ check(command, args, options);
109
+ return adapter.spawn(command, args, options);
110
+ },
111
+ };
112
+ }
113
+ export function wrapFileSystem(filesystem, permissions) {
114
+ if (!permissions?.fs)
115
+ return filesystem;
116
+ const check = (path, operation) => {
117
+ if (!permissionAllowed(permissions.fs?.({ path, operation }))) {
118
+ throw new Error(`EACCES: blocked ${operation} on '${path}'`);
119
+ }
120
+ };
121
+ return {
122
+ readFile(path) {
123
+ check(path, "readFile");
124
+ return filesystem.readFile(path);
125
+ },
126
+ readTextFile(path) {
127
+ check(path, "readTextFile");
128
+ return filesystem.readTextFile(path);
129
+ },
130
+ readDir(path) {
131
+ check(path, "readDir");
132
+ return filesystem.readDir(path);
133
+ },
134
+ readDirWithTypes(path) {
135
+ check(path, "readDirWithTypes");
136
+ return filesystem.readDirWithTypes(path);
137
+ },
138
+ writeFile(path, content) {
139
+ check(path, "writeFile");
140
+ return filesystem.writeFile(path, content);
141
+ },
142
+ createDir(path) {
143
+ check(path, "createDir");
144
+ return filesystem.createDir(path);
145
+ },
146
+ mkdir(path, options) {
147
+ check(path, "mkdir");
148
+ return filesystem.mkdir(path, options);
149
+ },
150
+ exists(path) {
151
+ check(path, "exists");
152
+ return filesystem.exists(path);
153
+ },
154
+ stat(path) {
155
+ check(path, "stat");
156
+ return filesystem.stat(path);
157
+ },
158
+ removeFile(path) {
159
+ check(path, "removeFile");
160
+ return filesystem.removeFile(path);
161
+ },
162
+ removeDir(path) {
163
+ check(path, "removeDir");
164
+ return filesystem.removeDir(path);
165
+ },
166
+ rename(oldPath, newPath) {
167
+ check(oldPath, "rename");
168
+ check(newPath, "rename");
169
+ return filesystem.rename(oldPath, newPath);
170
+ },
171
+ realpath(path) {
172
+ check(path, "realpath");
173
+ return filesystem.realpath(path);
174
+ },
175
+ symlink(target, linkPath) {
176
+ check(linkPath, "symlink");
177
+ return filesystem.symlink(target, linkPath);
178
+ },
179
+ readlink(path) {
180
+ check(path, "readlink");
181
+ return filesystem.readlink(path);
182
+ },
183
+ lstat(path) {
184
+ check(path, "lstat");
185
+ return filesystem.lstat(path);
186
+ },
187
+ link(oldPath, newPath) {
188
+ check(oldPath, "link");
189
+ check(newPath, "link");
190
+ return filesystem.link(oldPath, newPath);
191
+ },
192
+ chmod(path, mode) {
193
+ check(path, "chmod");
194
+ return filesystem.chmod(path, mode);
195
+ },
196
+ chown(path, uid, gid) {
197
+ check(path, "chown");
198
+ return filesystem.chown(path, uid, gid);
199
+ },
200
+ utimes(path, atime, mtime) {
201
+ check(path, "utimes");
202
+ return filesystem.utimes(path, atime, mtime);
203
+ },
204
+ truncate(path, length) {
205
+ check(path, "truncate");
206
+ return filesystem.truncate(path, length);
207
+ },
208
+ pread(path, offset, length) {
209
+ check(path, "pread");
210
+ return filesystem.pread(path, offset, length);
211
+ },
212
+ pwrite(path, offset, data) {
213
+ check(path, "pwrite");
214
+ return filesystem.pwrite(path, offset, data);
215
+ },
216
+ };
217
+ }
218
+ export function wrapNetworkAdapter(adapter, permissions) {
219
+ if (!permissions?.network)
220
+ return adapter;
221
+ const check = (request) => {
222
+ if (!permissionAllowed(permissions.network?.(request))) {
223
+ throw new Error(`EACCES: blocked network access to '${request.url ?? request.host ?? ""}'`);
224
+ }
225
+ };
226
+ return {
227
+ async fetch(url, options) {
228
+ check({ url });
229
+ return adapter.fetch(url, options);
230
+ },
231
+ async dnsLookup(hostname) {
232
+ check({ host: hostname });
233
+ return adapter.dnsLookup(hostname);
234
+ },
235
+ async httpRequest(url, options) {
236
+ check({ url });
237
+ return adapter.httpRequest(url, options);
238
+ },
239
+ };
240
+ }
241
+ export async function mkdir(filesystem, path, options) {
242
+ if (typeof options === "boolean") {
243
+ return filesystem.mkdir(path, { recursive: options });
244
+ }
245
+ return filesystem.mkdir(path, options);
246
+ }
247
+ export async function loadFile(path, filesystem) {
248
+ try {
249
+ return await filesystem.readTextFile(path);
250
+ }
251
+ catch {
252
+ return null;
253
+ }
254
+ }
255
+ export async function moduleFormat(path, filesystem) {
256
+ if (path.startsWith("node:")) {
257
+ return "module";
258
+ }
259
+ const normalized = normalizePath(path);
260
+ if (normalized.endsWith(".mjs") || normalized.endsWith(".mts")) {
261
+ return "module";
262
+ }
263
+ if (normalized.endsWith(".cjs") || normalized.endsWith(".cts")) {
264
+ return "commonjs";
265
+ }
266
+ if (normalized.endsWith(".json")) {
267
+ return "json";
268
+ }
269
+ if (!normalized.endsWith(".js")) {
270
+ return null;
271
+ }
272
+ const packageType = await nearestPackageJsonType(normalized, filesystem);
273
+ return packageType === "module" ? "module" : "commonjs";
274
+ }
275
+ export async function resolveModule(specifier, fromPath, filesystem, mode = "require") {
276
+ if (specifier.startsWith("node:")) {
277
+ return specifier;
278
+ }
279
+ const fromDir = await resolveImporterDir(fromPath, filesystem);
280
+ if (specifier.startsWith("file:")) {
281
+ const filePath = fileUrlToPath(specifier);
282
+ return filePath === null ? null : resolvePath(filePath, filesystem, mode);
283
+ }
284
+ if (specifier.startsWith(".") || specifier.startsWith("/")) {
285
+ const base = specifier.startsWith("/")
286
+ ? specifier
287
+ : `${fromDir}/${specifier}`;
288
+ return resolvePath(base, filesystem, mode);
289
+ }
290
+ if (specifier.startsWith("#")) {
291
+ return resolvePackageImports(specifier, fromDir, filesystem, mode);
292
+ }
293
+ return ((await resolvePackageSelfReference(specifier, fromDir, filesystem, mode)) ??
294
+ resolveNodeModules(specifier, fromDir, filesystem, mode));
295
+ }
296
+ function fileUrlToPath(specifier) {
297
+ let pathname;
298
+ if (specifier.startsWith("file://")) {
299
+ pathname = specifier.slice("file://".length);
300
+ }
301
+ else {
302
+ pathname = specifier.slice("file:".length);
303
+ }
304
+ const terminator = pathname.search(/[?#]/);
305
+ if (terminator >= 0) {
306
+ pathname = pathname.slice(0, terminator);
307
+ }
308
+ if (!pathname.startsWith("/")) {
309
+ const slashIndex = pathname.indexOf("/");
310
+ if (slashIndex < 0) {
311
+ return null;
312
+ }
313
+ const host = pathname.slice(0, slashIndex);
314
+ if (host !== "" && host !== "localhost") {
315
+ return null;
316
+ }
317
+ pathname = pathname.slice(slashIndex);
318
+ }
319
+ try {
320
+ return normalizePath(decodeURIComponent(pathname));
321
+ }
322
+ catch {
323
+ return null;
324
+ }
325
+ }
326
+ async function resolveImporterDir(fromPath, filesystem) {
327
+ let fromDir = normalizePath(fromPath);
328
+ try {
329
+ const stat = await filesystem.stat(fromDir);
330
+ if (!stat.isDirectory) {
331
+ return dirname(fromDir);
332
+ }
333
+ return await realpathOrSelf(fromDir, filesystem);
334
+ }
335
+ catch {
336
+ const basename = fromDir.split("/").at(-1) ?? "";
337
+ if (basename.includes(".")) {
338
+ fromDir = dirname(fromDir);
339
+ }
340
+ return fromDir;
341
+ }
342
+ }
343
+ async function realpathOrSelf(path, filesystem) {
344
+ try {
345
+ return normalizePath(await filesystem.realpath(path));
346
+ }
347
+ catch {
348
+ return normalizePath(path);
349
+ }
350
+ }
351
+ async function resolveNodeModules(specifier, fromDir, filesystem, mode) {
352
+ const parsed = parsePackageSpecifier(specifier);
353
+ if (!parsed) {
354
+ return null;
355
+ }
356
+ for (const dir of ancestorDirs(fromDir)) {
357
+ if (dir === "/node_modules" || dir.endsWith("/node_modules")) {
358
+ continue;
359
+ }
360
+ const packageDir = normalizePath(`${dir}/node_modules/${parsed.name}`);
361
+ const resolved = await resolvePackageEntry(packageDir, parsed.subpath, filesystem, mode);
362
+ if (resolved) {
363
+ return resolved;
364
+ }
365
+ }
366
+ for (const root of ["/root/node_modules", "/node_modules"]) {
367
+ const resolved = await resolvePackageEntry(normalizePath(`${root}/${parsed.name}`), parsed.subpath, filesystem, mode);
368
+ if (resolved) {
369
+ return resolved;
370
+ }
371
+ }
372
+ return null;
373
+ }
374
+ async function resolvePackageImports(specifier, fromDir, filesystem, mode) {
375
+ let dir = normalizePath(fromDir);
376
+ while (true) {
377
+ const packageJson = await readPackageJson(dir, filesystem);
378
+ if (packageJson && Object.hasOwn(packageJson, "imports")) {
379
+ const target = resolveImportsTarget(packageJson.imports, specifier, mode);
380
+ if (!target) {
381
+ return null;
382
+ }
383
+ const targetPath = target.startsWith("/") ? target : `${dir}/${target}`;
384
+ return resolvePath(targetPath, filesystem, mode);
385
+ }
386
+ if (dir === "/") {
387
+ break;
388
+ }
389
+ dir = dirname(dir);
390
+ }
391
+ return null;
392
+ }
393
+ async function resolvePackageSelfReference(specifier, fromDir, filesystem, mode) {
394
+ const parsed = parsePackageSpecifier(specifier);
395
+ if (!parsed) {
396
+ return null;
397
+ }
398
+ for (const dir of ancestorDirs(fromDir)) {
399
+ const packageJson = await readPackageJson(dir, filesystem);
400
+ if (packageJson && packageJson.name === parsed.name) {
401
+ return resolvePackageEntry(dir, parsed.subpath, filesystem, mode);
402
+ }
403
+ }
404
+ return null;
405
+ }
406
+ function parsePackageSpecifier(specifier) {
407
+ const parts = specifier.split("/").filter(Boolean);
408
+ if (parts.length === 0) {
409
+ return null;
410
+ }
411
+ if (parts[0]?.startsWith("@")) {
412
+ if (parts.length < 2) {
413
+ return null;
414
+ }
415
+ return {
416
+ name: `${parts[0]}/${parts[1]}`,
417
+ subpath: parts.slice(2).join("/"),
418
+ };
419
+ }
420
+ return {
421
+ name: parts[0] ?? "",
422
+ subpath: parts.slice(1).join("/"),
423
+ };
424
+ }
425
+ function ancestorDirs(fromDir) {
426
+ const dirs = [];
427
+ let current = normalizePath(fromDir);
428
+ while (true) {
429
+ dirs.push(current);
430
+ if (current === "/") {
431
+ break;
432
+ }
433
+ current = dirname(current);
434
+ }
435
+ return dirs;
436
+ }
437
+ async function resolvePackageEntry(packageDir, subpath, filesystem, mode) {
438
+ const packageJson = await readPackageJson(packageDir, filesystem);
439
+ if (packageJson && Object.hasOwn(packageJson, "exports")) {
440
+ const exportsSubpath = subpath ? `./${subpath}` : ".";
441
+ const exportsTarget = resolveExportsTarget(packageJson.exports, exportsSubpath, mode);
442
+ if (!exportsTarget) {
443
+ return null;
444
+ }
445
+ const targetPath = normalizePath(`${packageDir}/${exportsTarget}`);
446
+ return (await resolvePath(targetPath, filesystem, mode)) ?? targetPath;
447
+ }
448
+ if (subpath) {
449
+ return resolvePath(`${packageDir}/${subpath}`, filesystem, mode);
450
+ }
451
+ if (typeof packageJson?.main === "string" && packageJson.main.length > 0) {
452
+ const mainResolved = await resolvePath(`${packageDir}/${packageJson.main}`, filesystem, mode);
453
+ if (mainResolved) {
454
+ return mainResolved;
455
+ }
456
+ }
457
+ return resolvePath(`${packageDir}/index`, filesystem, mode);
458
+ }
459
+ async function resolvePath(basePath, filesystem, mode) {
460
+ return ((await resolveAsFile(basePath, filesystem)) ??
461
+ resolveAsDirectory(basePath, filesystem, mode));
462
+ }
463
+ async function resolveAsFile(basePath, filesystem) {
464
+ const normalized = normalizePath(basePath);
465
+ const candidates = [
466
+ normalized,
467
+ `${normalized}.js`,
468
+ `${normalized}.json`,
469
+ `${normalized}.mjs`,
470
+ `${normalized}.cjs`,
471
+ ];
472
+ for (const candidate of candidates) {
473
+ try {
474
+ const stat = await filesystem.stat(candidate);
475
+ if (!stat.isDirectory) {
476
+ return realpathOrSelf(candidate, filesystem);
477
+ }
478
+ }
479
+ catch {
480
+ // Try the next candidate.
481
+ }
482
+ }
483
+ return null;
484
+ }
485
+ async function resolveAsDirectory(basePath, filesystem, mode) {
486
+ const dir = normalizePath(basePath);
487
+ try {
488
+ const stat = await filesystem.stat(dir);
489
+ if (!stat.isDirectory) {
490
+ return null;
491
+ }
492
+ }
493
+ catch {
494
+ return null;
495
+ }
496
+ const packageJson = await readPackageJson(dir, filesystem);
497
+ if (packageJson && Object.hasOwn(packageJson, "exports")) {
498
+ const exportsTarget = resolveExportsTarget(packageJson.exports, ".", mode);
499
+ if (exportsTarget) {
500
+ const resolved = await resolvePath(`${dir}/${exportsTarget}`, filesystem, mode);
501
+ if (resolved) {
502
+ return resolved;
503
+ }
504
+ }
505
+ }
506
+ if (typeof packageJson?.main === "string" && packageJson.main.length > 0) {
507
+ const mainResolved = await resolvePath(`${dir}/${packageJson.main}`, filesystem, mode);
508
+ if (mainResolved) {
509
+ return mainResolved;
510
+ }
511
+ }
512
+ return resolveAsFile(`${dir}/index`, filesystem);
513
+ }
514
+ async function readPackageJson(packageDir, filesystem) {
515
+ try {
516
+ const source = await filesystem.readTextFile(normalizePath(`${packageDir}/package.json`));
517
+ const parsed = JSON.parse(source);
518
+ return parsed && typeof parsed === "object"
519
+ ? parsed
520
+ : null;
521
+ }
522
+ catch {
523
+ return null;
524
+ }
525
+ }
526
+ async function nearestPackageJsonType(filePath, filesystem) {
527
+ for (const dir of ancestorDirs(dirname(filePath))) {
528
+ const packageJson = await readPackageJson(dir, filesystem);
529
+ if (packageJson && typeof packageJson.type === "string") {
530
+ return packageJson.type;
531
+ }
532
+ }
533
+ return null;
534
+ }
535
+ function resolveExportsTarget(exportsField, subpath, mode) {
536
+ const resolved = resolveExportsValue(exportsField, subpath, mode);
537
+ if (typeof resolved !== "string" || !resolved.startsWith("./")) {
538
+ return null;
539
+ }
540
+ return resolved.slice(2);
541
+ }
542
+ function resolveExportsValue(value, subpath, mode) {
543
+ if (typeof value === "string") {
544
+ return subpath === "." ? value : null;
545
+ }
546
+ if (Array.isArray(value)) {
547
+ for (const item of value) {
548
+ const resolved = resolveExportsValue(item, subpath, mode);
549
+ if (resolved) {
550
+ return resolved;
551
+ }
552
+ }
553
+ return null;
554
+ }
555
+ if (!value || typeof value !== "object") {
556
+ return null;
557
+ }
558
+ const entries = Object.entries(value);
559
+ const hasSubpathKeys = entries.some(([key]) => key === "." || key.startsWith("./"));
560
+ if (hasSubpathKeys) {
561
+ const exact = value[subpath];
562
+ if (exact !== undefined) {
563
+ const resolved = resolveExportsValue(exact, ".", mode);
564
+ if (resolved) {
565
+ return resolved;
566
+ }
567
+ }
568
+ for (const [key, target] of entries) {
569
+ if (!key.includes("*")) {
570
+ continue;
571
+ }
572
+ const [prefix, suffix] = key.split("*", 2);
573
+ if (!prefix || suffix === undefined) {
574
+ continue;
575
+ }
576
+ if (subpath.startsWith(prefix) && subpath.endsWith(suffix)) {
577
+ const wildcard = subpath.slice(prefix.length, subpath.length - suffix.length);
578
+ const resolved = resolveExportsValue(target, ".", mode);
579
+ if (resolved) {
580
+ return resolved.replaceAll("*", wildcard);
581
+ }
582
+ }
583
+ }
584
+ return null;
585
+ }
586
+ const conditions = mode === "import"
587
+ ? ["import", "node", "module", "default", "require"]
588
+ : ["require", "node", "default", "import", "module"];
589
+ for (const condition of conditions) {
590
+ const target = value[condition];
591
+ if (target === undefined) {
592
+ continue;
593
+ }
594
+ const resolved = resolveExportsValue(target, subpath, mode);
595
+ if (resolved) {
596
+ return resolved;
597
+ }
598
+ }
599
+ return null;
600
+ }
601
+ function resolveImportsTarget(importsField, specifier, mode) {
602
+ if (typeof importsField === "string") {
603
+ return importsField;
604
+ }
605
+ if (Array.isArray(importsField)) {
606
+ for (const item of importsField) {
607
+ const resolved = resolveImportsTarget(item, specifier, mode);
608
+ if (resolved) {
609
+ return resolved;
610
+ }
611
+ }
612
+ return null;
613
+ }
614
+ if (!importsField || typeof importsField !== "object") {
615
+ return null;
616
+ }
617
+ const record = importsField;
618
+ if (Object.hasOwn(record, specifier)) {
619
+ return resolveExportsValue(record[specifier], ".", mode);
620
+ }
621
+ for (const [key, target] of Object.entries(record)) {
622
+ const wildcardIndex = key.indexOf("*");
623
+ if (wildcardIndex < 0) {
624
+ continue;
625
+ }
626
+ const prefix = key.slice(0, wildcardIndex);
627
+ const suffix = key.slice(wildcardIndex + 1);
628
+ if (specifier.startsWith(prefix) && specifier.endsWith(suffix)) {
629
+ const wildcard = specifier.slice(prefix.length, specifier.length - suffix.length);
630
+ const resolved = resolveExportsValue(target, ".", mode);
631
+ if (resolved) {
632
+ return resolved.replaceAll("*", wildcard);
633
+ }
634
+ }
635
+ }
636
+ return null;
637
+ }
638
+ export function isESM(code, filePath) {
639
+ if (filePath?.endsWith(".mjs"))
640
+ return true;
641
+ return /\b(import|export)\b/.test(code);
642
+ }
643
+ export function transformDynamicImport(code) {
644
+ return code;
645
+ }
646
+ export const POLYFILL_CODE_MAP = {
647
+ fs: "module.exports = globalThis._fsModule;",
648
+ "node:fs": "module.exports = globalThis._fsModule;",
649
+ util: BROWSER_UTIL_POLYFILL_CODE,
650
+ "node:util": "module.exports = require('util');",
651
+ console: "module.exports = globalThis.console;",
652
+ "node:console": "module.exports = require('console');",
653
+ child_process: `
654
+ const callSync = (ref, ...args) => {
655
+ if (typeof ref === "function") return ref(...args);
656
+ if (ref && typeof ref.applySync === "function") return ref.applySync(undefined, args);
657
+ if (ref && typeof ref.applySyncPromise === "function") return ref.applySyncPromise(undefined, args);
658
+ throw new Error("child_process bridge is not configured");
659
+ };
660
+ const encodeBytes = globalThis.__agentOsEncoding.encodeBytesPayload;
661
+ const decodeBytes = globalThis.__agentOsEncoding.decodeBytesPayload;
662
+ const text = (bytes) => new TextDecoder().decode(bytes);
663
+ const bufferLike = (value) => {
664
+ const bytes = decodeBytes(value);
665
+ bytes.toString = () => text(bytes);
666
+ return bytes;
667
+ };
668
+ class Emitter {
669
+ constructor() {
670
+ this._listeners = new Map();
671
+ }
672
+ on(event, listener) {
673
+ const listeners = this._listeners.get(event) || [];
674
+ listeners.push(listener);
675
+ this._listeners.set(event, listeners);
676
+ return this;
677
+ }
678
+ once(event, listener) {
679
+ const wrapped = (...args) => {
680
+ this.off(event, wrapped);
681
+ listener(...args);
682
+ };
683
+ return this.on(event, wrapped);
684
+ }
685
+ off(event, listener) {
686
+ const listeners = this._listeners.get(event) || [];
687
+ this._listeners.set(event, listeners.filter((entry) => entry !== listener));
688
+ return this;
689
+ }
690
+ removeListener(event, listener) {
691
+ return this.off(event, listener);
692
+ }
693
+ emit(event, ...args) {
694
+ const listeners = this._listeners.get(event) || [];
695
+ for (const listener of [...listeners]) listener(...args);
696
+ return listeners.length > 0;
697
+ }
698
+ }
699
+ class ChildProcess extends Emitter {
700
+ constructor(sessionId) {
701
+ super();
702
+ this.pid = Number(sessionId) || -1;
703
+ this.exitCode = null;
704
+ this.signalCode = null;
705
+ this.killed = false;
706
+ this.stdout = new Emitter();
707
+ this.stderr = new Emitter();
708
+ this.stdin = {
709
+ write: (data) => {
710
+ callSync(globalThis._childProcessStdinWrite, sessionId, typeof data === "string" ? new TextEncoder().encode(data) : data);
711
+ return true;
712
+ },
713
+ end: (data) => {
714
+ if (data != null) this.stdin.write(data);
715
+ callSync(globalThis._childProcessStdinClose, sessionId);
716
+ },
717
+ };
718
+ }
719
+ }
720
+ const normalizeArgs = (args, options) => {
721
+ if (Array.isArray(args)) return { args, options: options || {} };
722
+ return { args: [], options: args || {} };
723
+ };
724
+ const signalNumbers = ${JSON.stringify(PROCESS_SIGNAL_NUMBERS)};
725
+ const normalizeSignal = (signal) => {
726
+ if (signal === undefined || signal === null) return 15;
727
+ if (typeof signal === "number" && Number.isFinite(signal)) {
728
+ const numeric = Math.trunc(signal);
729
+ if (numeric >= 0 && numeric <= 31) return numeric;
730
+ throw unknownSignalError(signal);
731
+ }
732
+ const raw = String(signal).trim();
733
+ if (/^[+-]?\\d+$/.test(raw)) {
734
+ const numeric = Number.parseInt(raw, 10);
735
+ if (numeric >= 0 && numeric <= 31) return numeric;
736
+ throw unknownSignalError(signal);
737
+ }
738
+ const upper = raw.toUpperCase();
739
+ const signalName = upper.startsWith("SIG") ? upper : "SIG" + upper;
740
+ const numeric = signalNumbers[signalName];
741
+ if (numeric !== undefined) return numeric;
742
+ throw unknownSignalError(signal);
743
+ };
744
+ const unknownSignalError = (signal) => {
745
+ const error = new TypeError("Unknown signal: " + String(signal));
746
+ error.code = "ERR_UNKNOWN_SIGNAL";
747
+ return error;
748
+ };
749
+ function spawn(command, argsOrOptions, maybeOptions) {
750
+ const { args, options } = normalizeArgs(argsOrOptions, maybeOptions);
751
+ let sessionId;
752
+ try {
753
+ sessionId = callSync(
754
+ globalThis._childProcessSpawnStart,
755
+ {
756
+ command: String(command),
757
+ args: args.map(String),
758
+ options: {
759
+ cwd: options.cwd || (globalThis.process && globalThis.process.cwd ? globalThis.process.cwd() : "/"),
760
+ env: options.env,
761
+ },
762
+ },
763
+ );
764
+ } catch (error) {
765
+ const child = new ChildProcess(-1);
766
+ queueMicrotask(() => child.emit("error", error));
767
+ return child;
768
+ }
769
+ const child = new ChildProcess(sessionId);
770
+ child.kill = (signal) => {
771
+ callSync(globalThis._childProcessKill, sessionId, normalizeSignal(signal));
772
+ child.killed = true;
773
+ return true;
774
+ };
775
+ const poll = () => {
776
+ const event = callSync(globalThis._childProcessPoll, sessionId, 0);
777
+ if (!event) {
778
+ setTimeout(poll, 0);
779
+ return;
780
+ }
781
+ if (event.type === "stdout") {
782
+ child.stdout.emit("data", bufferLike(event.data));
783
+ setTimeout(poll, 0);
784
+ return;
785
+ }
786
+ if (event.type === "stderr") {
787
+ child.stderr.emit("data", bufferLike(event.data));
788
+ setTimeout(poll, 0);
789
+ return;
790
+ }
791
+ if (event.type === "exit") {
792
+ child.exitCode = event.exitCode;
793
+ child.signalCode = event.signal;
794
+ child.emit("exit", event.exitCode, event.signal);
795
+ child.emit("close", event.exitCode, event.signal);
796
+ }
797
+ };
798
+ queueMicrotask(() => {
799
+ child.emit("spawn");
800
+ poll();
801
+ });
802
+ return child;
803
+ }
804
+ function spawnSync(command, argsOrOptions, maybeOptions) {
805
+ const { args, options } = normalizeArgs(argsOrOptions, maybeOptions);
806
+ try {
807
+ const raw = callSync(
808
+ globalThis._childProcessSpawnSync,
809
+ {
810
+ command: String(command),
811
+ args: args.map(String),
812
+ options: {
813
+ cwd: options.cwd || (globalThis.process && globalThis.process.cwd ? globalThis.process.cwd() : "/"),
814
+ env: options.env,
815
+ input: encodeBytes(options.input),
816
+ },
817
+ },
818
+ );
819
+ const result = typeof raw === "string" ? JSON.parse(raw) : raw;
820
+ const stdout = options.encoding === "utf8" || options.encoding === "utf-8" ? result.stdout : new TextEncoder().encode(result.stdout || "");
821
+ const stderr = options.encoding === "utf8" || options.encoding === "utf-8" ? result.stderr : new TextEncoder().encode(result.stderr || "");
822
+ return {
823
+ pid: -1,
824
+ output: [null, stdout, stderr],
825
+ stdout,
826
+ stderr,
827
+ status: result.code,
828
+ signal: null,
829
+ error: undefined,
830
+ };
831
+ } catch (error) {
832
+ const message = error instanceof Error ? error.message : String(error);
833
+ const stderr = options.encoding === "utf8" || options.encoding === "utf-8" ? message : new TextEncoder().encode(message);
834
+ return {
835
+ pid: -1,
836
+ output: [null, "", stderr],
837
+ stdout: options.encoding === "utf8" || options.encoding === "utf-8" ? "" : new Uint8Array(0),
838
+ stderr,
839
+ status: 1,
840
+ signal: null,
841
+ error,
842
+ };
843
+ }
844
+ }
845
+ module.exports = { spawn, spawnSync, default: { spawn, spawnSync } };
846
+ `,
847
+ "node:child_process": "module.exports = require('child_process');",
848
+ dns: `
849
+ const callAsync = (ref, ...args) => {
850
+ if (typeof ref === "function") return Promise.resolve(ref(...args));
851
+ if (ref && typeof ref.apply === "function") return ref.apply(undefined, args);
852
+ throw new Error("dns bridge is not configured");
853
+ };
854
+ const normalizeLookup = (hostname, options, callback) => {
855
+ let done = callback;
856
+ let normalized = {};
857
+ if (typeof options === "function") {
858
+ done = options;
859
+ } else if (typeof options === "number") {
860
+ normalized.family = options;
861
+ } else if (options && typeof options === "object") {
862
+ normalized = { ...options };
863
+ }
864
+ const family = normalized.family === 4 || normalized.family === 6 ? normalized.family : undefined;
865
+ return {
866
+ callback: done,
867
+ options: {
868
+ hostname: String(hostname),
869
+ family,
870
+ all: normalized.all === true,
871
+ },
872
+ };
873
+ };
874
+ const parseLookupRecords = (resultJson) => {
875
+ let parsed = resultJson;
876
+ if (typeof parsed === "string") parsed = JSON.parse(parsed);
877
+ if (parsed && typeof parsed === "object" && Array.isArray(parsed.records)) parsed = parsed.records;
878
+ else if (parsed && typeof parsed === "object" && typeof parsed.address === "string") parsed = [parsed];
879
+ if (!Array.isArray(parsed)) return [];
880
+ return parsed
881
+ .filter((record) => record && typeof record.address === "string")
882
+ .map((record) => ({ address: record.address, family: record.family === 6 ? 6 : 4 }));
883
+ };
884
+ const lookupRecords = (hostname, options, callback) => {
885
+ const invocation = normalizeLookup(hostname, options, callback);
886
+ return callAsync(globalThis._networkDnsLookupRaw, invocation.options)
887
+ .then(parseLookupRecords)
888
+ .then((records) => {
889
+ if (typeof invocation.callback === "function") {
890
+ if (invocation.options.all) invocation.callback(null, records);
891
+ else {
892
+ const first = records[0] || { address: null, family: invocation.options.family || 0 };
893
+ invocation.callback(null, first.address, first.family);
894
+ }
895
+ }
896
+ return invocation.options.all ? records : records[0] || { address: "", family: invocation.options.family || 0 };
897
+ })
898
+ .catch((error) => {
899
+ if (typeof invocation.callback === "function") {
900
+ invocation.callback(error);
901
+ return undefined;
902
+ }
903
+ throw error;
904
+ });
905
+ };
906
+ const promises = { lookup: (hostname, options) => lookupRecords(hostname, options) };
907
+ function lookup(hostname, options, callback) {
908
+ lookupRecords(hostname, options, callback);
909
+ }
910
+ module.exports = { lookup, promises, default: { lookup, promises } };
911
+ `,
912
+ "dns/promises": "module.exports = require('dns').promises;",
913
+ dgram: `
914
+ const encoder = new TextEncoder();
915
+ const decoder = new TextDecoder();
916
+ const callSync = (ref, ...args) => {
917
+ if (typeof ref === "function") return ref(...args);
918
+ if (ref && typeof ref.applySync === "function") return ref.applySync(undefined, args);
919
+ if (ref && typeof ref.applySyncPromise === "function") return ref.applySyncPromise(undefined, args);
920
+ throw new Error("dgram bridge is not configured");
921
+ };
922
+ const parseResult = (value) => {
923
+ if (typeof value !== "string") return value;
924
+ try { return JSON.parse(value); } catch { return value; }
925
+ };
926
+ const listenersFor = (map, event) => map.get(event) || [];
927
+ const normalizeType = (optionsOrType) => {
928
+ const type = typeof optionsOrType === "string" ? optionsOrType : optionsOrType && optionsOrType.type;
929
+ if (type === "udp6") return "udp6";
930
+ if (type === "udp4" || type === undefined) return "udp4";
931
+ const error = new TypeError("Bad socket type specified. Valid types are: udp4, udp6");
932
+ error.code = "ERR_SOCKET_BAD_TYPE";
933
+ throw error;
934
+ };
935
+ const normalizePort = (port) => {
936
+ const value = Number(port);
937
+ if (!Number.isInteger(value) || value < 0 || value > 65535) {
938
+ const error = new RangeError("Port should be >= 0 and < 65536");
939
+ error.code = "ERR_SOCKET_BAD_PORT";
940
+ throw error;
941
+ }
942
+ return value;
943
+ };
944
+ const normalizeMessage = (value) => {
945
+ if (typeof value === "string") return encoder.encode(value);
946
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
947
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
948
+ if (Array.isArray(value)) {
949
+ const parts = value.map(normalizeMessage);
950
+ const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
951
+ const output = new Uint8Array(total);
952
+ let offset = 0;
953
+ for (const part of parts) {
954
+ output.set(part, offset);
955
+ offset += part.byteLength;
956
+ }
957
+ return output;
958
+ }
959
+ return encoder.encode(String(value ?? ""));
960
+ };
961
+ const messageBytes = (value) => {
962
+ let bytes;
963
+ if (value && typeof value === "object" && value.__agentOsType === "bytes" && typeof value.base64 === "string") {
964
+ bytes = globalThis.__agentOsEncoding.base64ToBytes(value.base64);
965
+ } else {
966
+ bytes = normalizeMessage(value);
967
+ }
968
+ Object.defineProperty(bytes, "toString", {
969
+ value() { return decoder.decode(bytes); },
970
+ configurable: true,
971
+ });
972
+ return bytes;
973
+ };
974
+ class Socket {
975
+ constructor(optionsOrType, callback) {
976
+ this._type = normalizeType(optionsOrType);
977
+ this._listeners = new Map();
978
+ this._onceListeners = new Map();
979
+ this._closed = false;
980
+ this._bound = false;
981
+ this._polling = false;
982
+ const created = parseResult(callSync(globalThis._dgramSocketCreateRaw, { type: this._type }));
983
+ this._socketId = String(created && created.socketId !== undefined ? created.socketId : created);
984
+ if (typeof callback === "function") this.on("message", callback);
985
+ }
986
+ on(event, listener) {
987
+ const list = listenersFor(this._listeners, event).slice();
988
+ list.push(listener);
989
+ this._listeners.set(event, list);
990
+ return this;
991
+ }
992
+ addListener(event, listener) { return this.on(event, listener); }
993
+ once(event, listener) {
994
+ const list = listenersFor(this._onceListeners, event).slice();
995
+ list.push(listener);
996
+ this._onceListeners.set(event, list);
997
+ return this;
998
+ }
999
+ off(event, listener) { return this.removeListener(event, listener); }
1000
+ removeListener(event, listener) {
1001
+ this._listeners.set(event, listenersFor(this._listeners, event).filter((entry) => entry !== listener));
1002
+ this._onceListeners.set(event, listenersFor(this._onceListeners, event).filter((entry) => entry !== listener));
1003
+ return this;
1004
+ }
1005
+ _emit(event, ...args) {
1006
+ for (const listener of listenersFor(this._listeners, event).slice()) listener(...args);
1007
+ const once = listenersFor(this._onceListeners, event).slice();
1008
+ this._onceListeners.delete(event);
1009
+ for (const listener of once) listener(...args);
1010
+ return once.length > 0 || listenersFor(this._listeners, event).length > 0;
1011
+ }
1012
+ emit(event, ...args) { return this._emit(event, ...args); }
1013
+ bind(...args) {
1014
+ let port = 0;
1015
+ let address = this._type === "udp6" ? "::" : "0.0.0.0";
1016
+ let callback;
1017
+ if (typeof args[0] === "object" && args[0] !== null) {
1018
+ port = normalizePort(args[0].port ?? 0);
1019
+ address = String(args[0].address ?? address);
1020
+ callback = args[1];
1021
+ } else {
1022
+ if (typeof args[0] === "function") callback = args[0];
1023
+ else {
1024
+ port = normalizePort(args[0] ?? 0);
1025
+ if (typeof args[1] === "string") address = args[1];
1026
+ callback = typeof args[1] === "function" ? args[1] : args[2];
1027
+ }
1028
+ }
1029
+ try {
1030
+ parseResult(callSync(globalThis._dgramSocketBindRaw, this._socketId, { port, address }));
1031
+ this._bound = true;
1032
+ queueMicrotask(() => {
1033
+ this._emit("listening");
1034
+ if (typeof callback === "function") callback.call(this);
1035
+ this._poll();
1036
+ });
1037
+ } catch (error) {
1038
+ queueMicrotask(() => this._emit("error", error));
1039
+ }
1040
+ return this;
1041
+ }
1042
+ address() {
1043
+ return parseResult(callSync(globalThis._dgramSocketAddressRaw, this._socketId));
1044
+ }
1045
+ send(message, ...args) {
1046
+ let offset = 0;
1047
+ let length;
1048
+ let port;
1049
+ let address;
1050
+ let callback;
1051
+ if (typeof args[0] === "number" && typeof args[1] === "number" && typeof args[2] === "number") {
1052
+ offset = args[0];
1053
+ length = args[1];
1054
+ port = args[2];
1055
+ address = typeof args[3] === "string" ? args[3] : undefined;
1056
+ callback = typeof args[3] === "function" ? args[3] : args[4];
1057
+ } else {
1058
+ port = args[0];
1059
+ address = typeof args[1] === "string" ? args[1] : undefined;
1060
+ callback = typeof args[1] === "function" ? args[1] : args[2];
1061
+ }
1062
+ const full = normalizeMessage(message);
1063
+ const data = length === undefined ? full : full.subarray(offset, offset + length);
1064
+ try {
1065
+ const result = parseResult(callSync(globalThis._dgramSocketSendRaw, this._socketId, data, {
1066
+ port: normalizePort(port),
1067
+ address: address || (this._type === "udp6" ? "::1" : "127.0.0.1"),
1068
+ }));
1069
+ if (typeof callback === "function") queueMicrotask(() => callback(null, result && typeof result.bytes === "number" ? result.bytes : data.length));
1070
+ } catch (error) {
1071
+ if (typeof callback === "function") queueMicrotask(() => callback(error));
1072
+ else queueMicrotask(() => this._emit("error", error));
1073
+ }
1074
+ }
1075
+ _poll() {
1076
+ if (this._closed || !this._bound || this._polling) return;
1077
+ this._polling = true;
1078
+ try {
1079
+ const event = parseResult(callSync(globalThis._dgramSocketRecvRaw, this._socketId, 10));
1080
+ if (event && event.type === "message") {
1081
+ const message = messageBytes({ __agentOsType: "bytes", base64: String(event.data || "") });
1082
+ this._emit("message", message, {
1083
+ address: event.remoteAddress,
1084
+ port: event.remotePort,
1085
+ family: event.remoteFamily || (String(event.remoteAddress).includes(":") ? "IPv6" : "IPv4"),
1086
+ size: message.length,
1087
+ });
1088
+ }
1089
+ } catch (error) {
1090
+ this._emit("error", error);
1091
+ } finally {
1092
+ this._polling = false;
1093
+ }
1094
+ if (!this._closed && this._bound) setTimeout(() => this._poll(), 10);
1095
+ }
1096
+ close(callback) {
1097
+ if (typeof callback === "function") this.once("close", callback);
1098
+ if (this._closed) return this;
1099
+ this._closed = true;
1100
+ callSync(globalThis._dgramSocketCloseRaw, this._socketId);
1101
+ queueMicrotask(() => this._emit("close"));
1102
+ return this;
1103
+ }
1104
+ ref() { return this; }
1105
+ unref() { return this; }
1106
+ setRecvBufferSize(size) { callSync(globalThis._dgramSocketSetBufferSizeRaw, this._socketId, "recv", Number(size)); }
1107
+ setSendBufferSize(size) { callSync(globalThis._dgramSocketSetBufferSizeRaw, this._socketId, "send", Number(size)); }
1108
+ getRecvBufferSize() { return Number(callSync(globalThis._dgramSocketGetBufferSizeRaw, this._socketId, "recv")); }
1109
+ getSendBufferSize() { return Number(callSync(globalThis._dgramSocketGetBufferSizeRaw, this._socketId, "send")); }
1110
+ }
1111
+ function createSocket(optionsOrType, callback) {
1112
+ return new Socket(optionsOrType, callback);
1113
+ }
1114
+ module.exports = { Socket, createSocket, default: { Socket, createSocket } };
1115
+ `,
1116
+ "node:dgram": "module.exports = require('dgram');",
1117
+ crypto: `
1118
+ const callSync = (ref, ...args) => {
1119
+ if (typeof ref === "function") return ref(...args);
1120
+ if (ref && typeof ref.applySync === "function") return ref.applySync(undefined, args);
1121
+ if (ref && typeof ref.applySyncPromise === "function") return ref.applySyncPromise(undefined, args);
1122
+ throw new Error("crypto bridge is not configured");
1123
+ };
1124
+ const encoder = new TextEncoder();
1125
+ const decoder = new TextDecoder();
1126
+ const toBytes = globalThis.__agentOsEncoding.toBytes;
1127
+ const concat = (chunks) => {
1128
+ const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
1129
+ const out = new Uint8Array(total);
1130
+ let offset = 0;
1131
+ for (const chunk of chunks) {
1132
+ out.set(chunk, offset);
1133
+ offset += chunk.byteLength;
1134
+ }
1135
+ return out;
1136
+ };
1137
+ const toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1138
+ const SUPPORTED_CIPHERS = ["aes-128-cbc", "aes-128-ctr", "aes-128-gcm", "aes-192-cbc", "aes-192-ctr", "aes-192-gcm", "aes-256-cbc", "aes-256-ctr", "aes-256-gcm", "aes128", "aes192", "aes256"];
1139
+ const SUPPORTED_CURVES = ["prime256v1", "secp256k1", "secp384r1", "secp521r1"];
1140
+ const toBase64 = globalThis.__agentOsEncoding.bytesToBase64;
1141
+ const encodeOutput = (bytes, encoding) => {
1142
+ if (!encoding) return makeBuffer(bytes);
1143
+ if (encoding === "hex") return toHex(bytes);
1144
+ if (encoding === "base64") return toBase64(bytes);
1145
+ if (encoding === "utf8" || encoding === "utf-8") return decoder.decode(bytes);
1146
+ throw new Error("Unsupported crypto output encoding: " + encoding);
1147
+ };
1148
+ const makeBuffer = (bytes) => {
1149
+ if (typeof Buffer === "function") return Buffer.from(bytes);
1150
+ const out = new Uint8Array(bytes);
1151
+ out.toString = (encoding = "utf8") => encodeOutput(out, encoding);
1152
+ out.equals = (other) => {
1153
+ const rhs = toBytes(other);
1154
+ if (rhs.byteLength !== out.byteLength) return false;
1155
+ for (let i = 0; i < out.byteLength; i += 1) {
1156
+ if (out[i] !== rhs[i]) return false;
1157
+ }
1158
+ return true;
1159
+ };
1160
+ return out;
1161
+ };
1162
+ class Hash {
1163
+ constructor(algorithm) {
1164
+ this.algorithm = String(algorithm);
1165
+ this.chunks = [];
1166
+ }
1167
+ update(data, inputEncoding) {
1168
+ this.chunks.push(toBytes(data, inputEncoding));
1169
+ return this;
1170
+ }
1171
+ digest(encoding) {
1172
+ const bytes = callSync(globalThis._cryptoHashDigest, this.algorithm, concat(this.chunks));
1173
+ return encodeOutput(bytes, encoding);
1174
+ }
1175
+ }
1176
+ class Hmac {
1177
+ constructor(algorithm, key) {
1178
+ this.algorithm = String(algorithm);
1179
+ this.key = toBytes(key);
1180
+ this.chunks = [];
1181
+ }
1182
+ update(data, inputEncoding) {
1183
+ this.chunks.push(toBytes(data, inputEncoding));
1184
+ return this;
1185
+ }
1186
+ digest(encoding) {
1187
+ const bytes = callSync(globalThis._cryptoHmacDigest, this.algorithm, this.key, concat(this.chunks));
1188
+ return encodeOutput(bytes, encoding);
1189
+ }
1190
+ }
1191
+ const CRYPTO_CONSTANTS = {
1192
+ RSA_PKCS1_PADDING: 1,
1193
+ RSA_PKCS1_OAEP_PADDING: 4,
1194
+ };
1195
+ const normalizeKeyInput = (key) => {
1196
+ if (typeof key === "string") return key;
1197
+ if (key && typeof key === "object" && typeof key.export === "function") return key.export({ format: "pem" });
1198
+ if (key && typeof key === "object" && typeof key.key === "string") return key.key;
1199
+ if (key && typeof key === "object" && key.key && typeof key.key.export === "function") return key.key.export({ format: "pem" });
1200
+ throw new Error("Browser node:crypto RSA key must be a PEM string");
1201
+ };
1202
+ const normalizeAsymmetricOptions = (keyOrOptions) => {
1203
+ if (typeof keyOrOptions === "string") return { key: keyOrOptions };
1204
+ if (keyOrOptions && typeof keyOrOptions === "object" && typeof keyOrOptions.export === "function") return { key: keyOrOptions };
1205
+ if (keyOrOptions && typeof keyOrOptions === "object") return keyOrOptions;
1206
+ throw new Error("Browser node:crypto RSA key must be a PEM string");
1207
+ };
1208
+ class KeyObject {
1209
+ constructor(type, key) {
1210
+ this.type = type;
1211
+ if (type === "secret") {
1212
+ this.symmetricKeySize = toBytes(key).byteLength;
1213
+ this.key = new Uint8Array(toBytes(key));
1214
+ } else if (key && typeof key === "object" && key.asymmetricKeyType === "x25519") {
1215
+ this.asymmetricKeyType = "x25519";
1216
+ this.key = new Uint8Array(toBytes(key.key));
1217
+ this.publicKey = key.publicKey ? new Uint8Array(toBytes(key.publicKey)) : undefined;
1218
+ } else {
1219
+ this.asymmetricKeyType = "rsa";
1220
+ this.key = normalizeKeyInput(key);
1221
+ }
1222
+ }
1223
+ export(options = {}) {
1224
+ if (this.type === "secret") {
1225
+ return makeBuffer(this.key);
1226
+ }
1227
+ if (this.asymmetricKeyType === "x25519") {
1228
+ throw new Error("Browser node:crypto X25519 KeyObject export is not implemented yet");
1229
+ }
1230
+ if (!options || options.format == null || options.format === "pem") return this.key;
1231
+ throw new Error("Browser node:crypto KeyObject only supports PEM export");
1232
+ }
1233
+ }
1234
+ class Sign {
1235
+ constructor(algorithm) {
1236
+ this.algorithm = String(algorithm);
1237
+ this.chunks = [];
1238
+ }
1239
+ update(data, inputEncoding) {
1240
+ this.chunks.push(toBytes(data, inputEncoding));
1241
+ return this;
1242
+ }
1243
+ write(data, inputEncoding) {
1244
+ this.update(data, inputEncoding);
1245
+ return true;
1246
+ }
1247
+ end(data, inputEncoding) {
1248
+ if (data !== undefined) this.update(data, inputEncoding);
1249
+ return this;
1250
+ }
1251
+ sign(key, outputEncoding) {
1252
+ const bytes = callSync(globalThis._cryptoSign, this.algorithm, concat(this.chunks), normalizeKeyInput(key));
1253
+ return encodeOutput(bytes, outputEncoding);
1254
+ }
1255
+ }
1256
+ class Verify extends Sign {
1257
+ verify(key, signature, signatureEncoding) {
1258
+ return Boolean(callSync(
1259
+ globalThis._cryptoVerify,
1260
+ this.algorithm,
1261
+ concat(this.chunks),
1262
+ normalizeKeyInput(key),
1263
+ toBytes(signature, signatureEncoding),
1264
+ ));
1265
+ }
1266
+ }
1267
+ function createPrivateKey(key) {
1268
+ return new KeyObject("private", key);
1269
+ }
1270
+ function createPublicKey(key) {
1271
+ return new KeyObject("public", key);
1272
+ }
1273
+ function createSecretKey(key) {
1274
+ return new KeyObject("secret", toBytes(key));
1275
+ }
1276
+ function signOneShot(algorithm, data, key) {
1277
+ const signer = new Sign(algorithm);
1278
+ signer.update(data);
1279
+ return signer.sign(key);
1280
+ }
1281
+ function verifyOneShot(algorithm, data, key, signature) {
1282
+ const verifier = new Verify(algorithm);
1283
+ verifier.update(data);
1284
+ return verifier.verify(key, signature);
1285
+ }
1286
+ function modInverse(value, modulus) {
1287
+ let t = 0n;
1288
+ let newT = 1n;
1289
+ let r = modulus;
1290
+ let newR = mod(value, modulus);
1291
+ while (newR !== 0n) {
1292
+ const quotient = r / newR;
1293
+ const nextT = t - quotient * newT;
1294
+ t = newT;
1295
+ newT = nextT;
1296
+ const nextR = r - quotient * newR;
1297
+ r = newR;
1298
+ newR = nextR;
1299
+ }
1300
+ if (r !== 1n) throw new Error("Browser node:crypto RSA values are not invertible");
1301
+ return t < 0n ? t + modulus : t;
1302
+ }
1303
+ function gcd(left, right) {
1304
+ let a = left < 0n ? -left : left;
1305
+ let b = right < 0n ? -right : right;
1306
+ while (b !== 0n) {
1307
+ const next = a % b;
1308
+ a = b;
1309
+ b = next;
1310
+ }
1311
+ return a;
1312
+ }
1313
+ function derLength(length) {
1314
+ if (length < 0x80) return new Uint8Array([length]);
1315
+ const bytes = [];
1316
+ let remaining = length;
1317
+ while (remaining > 0) {
1318
+ bytes.unshift(remaining & 0xff);
1319
+ remaining >>= 8;
1320
+ }
1321
+ return new Uint8Array([0x80 | bytes.length, ...bytes]);
1322
+ }
1323
+ function der(tag, content) {
1324
+ return concat([new Uint8Array([tag]), derLength(content.byteLength), content]);
1325
+ }
1326
+ function derInteger(value) {
1327
+ let bytes = bigIntToMinimalBytes(value);
1328
+ if ((bytes[0] & 0x80) !== 0) bytes = concat([new Uint8Array([0]), bytes]);
1329
+ return der(0x02, bytes);
1330
+ }
1331
+ function derSequence(items) {
1332
+ return der(0x30, concat(items));
1333
+ }
1334
+ function derOctetString(bytes) {
1335
+ return der(0x04, bytes);
1336
+ }
1337
+ function derBitString(bytes) {
1338
+ return der(0x03, concat([new Uint8Array([0]), bytes]));
1339
+ }
1340
+ function derNull() {
1341
+ return new Uint8Array([0x05, 0x00]);
1342
+ }
1343
+ function derObjectIdentifier(parts) {
1344
+ const out = [parts[0] * 40 + parts[1]];
1345
+ for (const part of parts.slice(2)) {
1346
+ const stack = [part & 0x7f];
1347
+ let remaining = part >> 7;
1348
+ while (remaining > 0) {
1349
+ stack.unshift(0x80 | (remaining & 0x7f));
1350
+ remaining >>= 7;
1351
+ }
1352
+ out.push(...stack);
1353
+ }
1354
+ return der(0x06, new Uint8Array(out));
1355
+ }
1356
+ const RSA_ENCRYPTION_ALGORITHM = derSequence([
1357
+ derObjectIdentifier([1, 2, 840, 113549, 1, 1, 1]),
1358
+ derNull(),
1359
+ ]);
1360
+ function pem(label, derBytes) {
1361
+ const body = toBase64(derBytes).replace(/.{1,64}/g, "$&\\n").trimEnd();
1362
+ return "-----BEGIN " + label + "-----\\n" + body + "\\n-----END " + label + "-----";
1363
+ }
1364
+ function normalizePublicExponent(value) {
1365
+ if (value === undefined) return 65537n;
1366
+ if (typeof value === "number") return BigInt(value);
1367
+ if (typeof value === "bigint") return value;
1368
+ return bytesToBigInt(toBytes(value));
1369
+ }
1370
+ function encodeRsaPublicKeyDer(key) {
1371
+ return derSequence([derInteger(key.n), derInteger(key.e)]);
1372
+ }
1373
+ function encodeRsaPrivateKeyDer(key) {
1374
+ return derSequence([
1375
+ derInteger(0n),
1376
+ derInteger(key.n),
1377
+ derInteger(key.e),
1378
+ derInteger(key.d),
1379
+ derInteger(key.p),
1380
+ derInteger(key.q),
1381
+ derInteger(key.d % (key.p - 1n)),
1382
+ derInteger(key.d % (key.q - 1n)),
1383
+ derInteger(modInverse(key.q, key.p)),
1384
+ ]);
1385
+ }
1386
+ function encodeRsaSpkiDer(key) {
1387
+ return derSequence([RSA_ENCRYPTION_ALGORITHM, derBitString(encodeRsaPublicKeyDer(key))]);
1388
+ }
1389
+ function encodeRsaPkcs8Der(key) {
1390
+ return derSequence([
1391
+ derInteger(0n),
1392
+ RSA_ENCRYPTION_ALGORITHM,
1393
+ derOctetString(encodeRsaPrivateKeyDer(key)),
1394
+ ]);
1395
+ }
1396
+ function encodeGeneratedRsaKey(key, encoding, defaultType) {
1397
+ if (!encoding) {
1398
+ return defaultType === "public"
1399
+ ? new KeyObject("public", pem("PUBLIC KEY", encodeRsaSpkiDer(key)))
1400
+ : new KeyObject("private", pem("PRIVATE KEY", encodeRsaPkcs8Der(key)));
1401
+ }
1402
+ const format = encoding.format || "pem";
1403
+ const type = encoding.type || (defaultType === "public" ? "spki" : "pkcs8");
1404
+ let derBytes;
1405
+ let label;
1406
+ if (defaultType === "public" && type === "spki") {
1407
+ derBytes = encodeRsaSpkiDer(key);
1408
+ label = "PUBLIC KEY";
1409
+ } else if (defaultType === "public" && (type === "pkcs1" || type === "rsa")) {
1410
+ derBytes = encodeRsaPublicKeyDer(key);
1411
+ label = "RSA PUBLIC KEY";
1412
+ } else if (defaultType === "private" && type === "pkcs8") {
1413
+ derBytes = encodeRsaPkcs8Der(key);
1414
+ label = "PRIVATE KEY";
1415
+ } else if (defaultType === "private" && (type === "pkcs1" || type === "rsa")) {
1416
+ derBytes = encodeRsaPrivateKeyDer(key);
1417
+ label = "RSA PRIVATE KEY";
1418
+ } else {
1419
+ throw new Error("Browser node:crypto unsupported RSA key encoding type");
1420
+ }
1421
+ if (format === "der") return makeBuffer(derBytes);
1422
+ if (format === "pem") return pem(label, derBytes);
1423
+ throw new Error("Browser node:crypto unsupported RSA key encoding format");
1424
+ }
1425
+ function generateRsaKeyPair(options = {}) {
1426
+ const modulusLength = Number(options.modulusLength || 2048);
1427
+ if (!Number.isInteger(modulusLength) || modulusLength < 512) {
1428
+ throw new Error("Browser node:crypto RSA modulusLength must be at least 512 bits");
1429
+ }
1430
+ const e = normalizePublicExponent(options.publicExponent);
1431
+ const pBits = Math.floor(modulusLength / 2);
1432
+ const qBits = modulusLength - pBits;
1433
+ while (true) {
1434
+ const p = generatePrimeSync(pBits, { bigint: true });
1435
+ const q = generatePrimeSync(qBits, { bigint: true });
1436
+ if (p === q) continue;
1437
+ const phi = (p - 1n) * (q - 1n);
1438
+ if (gcd(e, phi) !== 1n) continue;
1439
+ const n = p * q;
1440
+ if (n.toString(2).length !== modulusLength) continue;
1441
+ const d = modInverse(e, phi);
1442
+ const key = { n, e, d, p, q };
1443
+ return {
1444
+ publicKey: encodeGeneratedRsaKey(key, options.publicKeyEncoding, "public"),
1445
+ privateKey: encodeGeneratedRsaKey(key, options.privateKeyEncoding, "private"),
1446
+ };
1447
+ }
1448
+ }
1449
+ const X25519_PRIME = (1n << 255n) - 19n;
1450
+ const X25519_A24 = 121665n;
1451
+ const X25519_BASE_POINT = new Uint8Array([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1452
+ function mod(value, modulus) {
1453
+ const result = value % modulus;
1454
+ return result < 0n ? result + modulus : result;
1455
+ }
1456
+ function bytesToLittleEndianBigInt(bytes) {
1457
+ let value = 0n;
1458
+ for (let i = bytes.byteLength - 1; i >= 0; i -= 1) {
1459
+ value = (value << 8n) | BigInt(bytes[i]);
1460
+ }
1461
+ return value;
1462
+ }
1463
+ function littleEndianBigIntToBytes(value, byteLength) {
1464
+ const out = new Uint8Array(byteLength);
1465
+ let cursor = BigInt(value);
1466
+ for (let i = 0; i < byteLength; i += 1) {
1467
+ out[i] = Number(cursor & 0xffn);
1468
+ cursor >>= 8n;
1469
+ }
1470
+ return out;
1471
+ }
1472
+ function normalizeX25519PrivateKey(key) {
1473
+ if (!key || key.type !== "private" || key.asymmetricKeyType !== "x25519" || key.key.byteLength !== 32) {
1474
+ throw new Error("Browser node:crypto diffieHellman requires an X25519 private KeyObject");
1475
+ }
1476
+ return key.key;
1477
+ }
1478
+ function normalizeX25519PublicKey(key) {
1479
+ if (!key || key.type !== "public" || key.asymmetricKeyType !== "x25519" || key.key.byteLength !== 32) {
1480
+ throw new Error("Browser node:crypto diffieHellman requires an X25519 public KeyObject");
1481
+ }
1482
+ return key.key;
1483
+ }
1484
+ function x25519(privateKey, publicKey) {
1485
+ const scalarBytes = new Uint8Array(privateKey);
1486
+ scalarBytes[0] &= 248;
1487
+ scalarBytes[31] &= 127;
1488
+ scalarBytes[31] |= 64;
1489
+ const uBytes = new Uint8Array(publicKey);
1490
+ uBytes[31] &= 127;
1491
+ const scalar = bytesToLittleEndianBigInt(scalarBytes);
1492
+ const x1 = bytesToLittleEndianBigInt(uBytes);
1493
+ let x2 = 1n;
1494
+ let z2 = 0n;
1495
+ let x3 = x1;
1496
+ let z3 = 1n;
1497
+ let swap = 0n;
1498
+ const cswap = (bit) => {
1499
+ if (bit === 0n) return;
1500
+ let tmp = x2;
1501
+ x2 = x3;
1502
+ x3 = tmp;
1503
+ tmp = z2;
1504
+ z2 = z3;
1505
+ z3 = tmp;
1506
+ };
1507
+ for (let t = 254; t >= 0; t -= 1) {
1508
+ const bit = (scalar >> BigInt(t)) & 1n;
1509
+ swap ^= bit;
1510
+ cswap(swap);
1511
+ swap = bit;
1512
+ const a = mod(x2 + z2, X25519_PRIME);
1513
+ const aa = mod(a * a, X25519_PRIME);
1514
+ const b = mod(x2 - z2, X25519_PRIME);
1515
+ const bb = mod(b * b, X25519_PRIME);
1516
+ const e = mod(aa - bb, X25519_PRIME);
1517
+ const c = mod(x3 + z3, X25519_PRIME);
1518
+ const d = mod(x3 - z3, X25519_PRIME);
1519
+ const da = mod(d * a, X25519_PRIME);
1520
+ const cb = mod(c * b, X25519_PRIME);
1521
+ x3 = mod((da + cb) * (da + cb), X25519_PRIME);
1522
+ z3 = mod(x1 * mod((da - cb) * (da - cb), X25519_PRIME), X25519_PRIME);
1523
+ x2 = mod(aa * bb, X25519_PRIME);
1524
+ z2 = mod(e * mod(aa + X25519_A24 * e, X25519_PRIME), X25519_PRIME);
1525
+ }
1526
+ cswap(swap);
1527
+ const result = mod(x2 * modPow(z2, X25519_PRIME - 2n, X25519_PRIME), X25519_PRIME);
1528
+ return littleEndianBigIntToBytes(result, 32);
1529
+ }
1530
+ function generateKeyPairSync(type, options = {}) {
1531
+ const keyType = String(type).toLowerCase();
1532
+ if (keyType === "rsa") {
1533
+ return generateRsaKeyPair(options || {});
1534
+ }
1535
+ if (keyType !== "x25519") {
1536
+ return unsupportedBrowserCrypto("generateKeyPairSync");
1537
+ }
1538
+ const privateBytes = new Uint8Array(callSync(globalThis._cryptoRandomFill, 32));
1539
+ const publicBytes = x25519(privateBytes, X25519_BASE_POINT);
1540
+ return {
1541
+ publicKey: new KeyObject("public", { asymmetricKeyType: "x25519", key: publicBytes }),
1542
+ privateKey: new KeyObject("private", { asymmetricKeyType: "x25519", key: privateBytes, publicKey: publicBytes }),
1543
+ };
1544
+ }
1545
+ function generateKeyPair(type, options, callback) {
1546
+ if (typeof options === "function") {
1547
+ callback = options;
1548
+ options = {};
1549
+ }
1550
+ if (typeof callback !== "function") {
1551
+ throw new TypeError('The "callback" argument must be of type function');
1552
+ }
1553
+ queueMicrotask(() => {
1554
+ try {
1555
+ const pair = generateKeyPairSync(type, options || {});
1556
+ callback(null, pair.publicKey, pair.privateKey);
1557
+ } catch (error) {
1558
+ callback(error);
1559
+ }
1560
+ });
1561
+ }
1562
+ function diffieHellman(options) {
1563
+ if (!options || typeof options !== "object") {
1564
+ throw new TypeError("Browser node:crypto diffieHellman options must be an object");
1565
+ }
1566
+ const privateKey = normalizeX25519PrivateKey(options.privateKey);
1567
+ const publicKey = normalizeX25519PublicKey(options.publicKey);
1568
+ return makeBuffer(x25519(privateKey, publicKey));
1569
+ }
1570
+ const P256_P = BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff");
1571
+ const P256_A = P256_P - 3n;
1572
+ const P256_B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");
1573
+ const P256_N = BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551");
1574
+ const P256_G = {
1575
+ x: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
1576
+ y: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),
1577
+ };
1578
+ function p256Inverse(value) {
1579
+ return modPow(mod(value, P256_P), P256_P - 2n, P256_P);
1580
+ }
1581
+ function p256PointAdd(left, right) {
1582
+ if (!left) return right;
1583
+ if (!right) return left;
1584
+ if (left.x === right.x) {
1585
+ if (mod(left.y + right.y, P256_P) === 0n) return null;
1586
+ const slope = mod((3n * left.x * left.x + P256_A) * p256Inverse(2n * left.y), P256_P);
1587
+ const x = mod(slope * slope - 2n * left.x, P256_P);
1588
+ const y = mod(slope * (left.x - x) - left.y, P256_P);
1589
+ return { x, y };
1590
+ }
1591
+ const slope = mod((right.y - left.y) * p256Inverse(right.x - left.x), P256_P);
1592
+ const x = mod(slope * slope - left.x - right.x, P256_P);
1593
+ const y = mod(slope * (left.x - x) - left.y, P256_P);
1594
+ return { x, y };
1595
+ }
1596
+ function p256ScalarMult(scalar, point) {
1597
+ let result = null;
1598
+ let addend = point;
1599
+ let remaining = scalar;
1600
+ while (remaining > 0n) {
1601
+ if ((remaining & 1n) === 1n) result = p256PointAdd(result, addend);
1602
+ addend = p256PointAdd(addend, addend);
1603
+ remaining >>= 1n;
1604
+ }
1605
+ return result;
1606
+ }
1607
+ function p256RandomScalar() {
1608
+ while (true) {
1609
+ const scalar = bytesToBigInt(callSync(globalThis._cryptoRandomFill, 32)) % P256_N;
1610
+ if (scalar > 0n) return scalar;
1611
+ }
1612
+ }
1613
+ function p256EncodePoint(point, format = "uncompressed") {
1614
+ if (!point) throw new Error("Browser node:crypto ECDH point is not available");
1615
+ if (format === "compressed") {
1616
+ const out = new Uint8Array(33);
1617
+ out[0] = point.y & 1n ? 0x03 : 0x02;
1618
+ out.set(bigIntToBytes(point.x, 32), 1);
1619
+ return out;
1620
+ }
1621
+ if (format !== "uncompressed" && format !== "hybrid") {
1622
+ throw new Error("Browser node:crypto ECDH only supports uncompressed, compressed, and hybrid public keys");
1623
+ }
1624
+ const out = new Uint8Array(65);
1625
+ out[0] = format === "hybrid" ? (point.y & 1n ? 0x07 : 0x06) : 0x04;
1626
+ out.set(bigIntToBytes(point.x, 32), 1);
1627
+ out.set(bigIntToBytes(point.y, 32), 33);
1628
+ return out;
1629
+ }
1630
+ function p256DecodePoint(value, encoding) {
1631
+ const bytes = toBytes(value, encoding);
1632
+ if (bytes.byteLength !== 65 || (bytes[0] !== 0x04 && bytes[0] !== 0x06 && bytes[0] !== 0x07)) {
1633
+ throw new Error("Browser node:crypto ECDH peer public key must be an uncompressed P-256 point");
1634
+ }
1635
+ const x = bytesToBigInt(bytes.subarray(1, 33));
1636
+ const y = bytesToBigInt(bytes.subarray(33, 65));
1637
+ if (mod(y * y - (x * x * x + P256_A * x + P256_B), P256_P) !== 0n) {
1638
+ throw new Error("Browser node:crypto ECDH peer public key is not on P-256");
1639
+ }
1640
+ return { x, y };
1641
+ }
1642
+ class ECDH {
1643
+ constructor(name) {
1644
+ const curve = String(name);
1645
+ if (curve !== "prime256v1" && curve !== "P-256") {
1646
+ const error = new Error("Invalid EC curve name");
1647
+ error.code = "ERR_CRYPTO_INVALID_CURVE";
1648
+ throw error;
1649
+ }
1650
+ this.privateKey = null;
1651
+ this.publicPoint = null;
1652
+ }
1653
+ generateKeys(encoding, format = "uncompressed") {
1654
+ this.privateKey = p256RandomScalar();
1655
+ this.publicPoint = p256ScalarMult(this.privateKey, P256_G);
1656
+ return encodeOutput(p256EncodePoint(this.publicPoint, format), encoding);
1657
+ }
1658
+ computeSecret(otherPublicKey, inputEncoding, outputEncoding) {
1659
+ if (this.privateKey === null) this.generateKeys();
1660
+ const shared = p256ScalarMult(this.privateKey, p256DecodePoint(otherPublicKey, inputEncoding));
1661
+ if (!shared) throw new Error("Browser node:crypto ECDH failed to compute shared secret");
1662
+ return encodeOutput(bigIntToBytes(shared.x, 32), outputEncoding);
1663
+ }
1664
+ getPublicKey(encoding, format = "uncompressed") {
1665
+ if (!this.publicPoint) throw new Error("Failed to get ECDH public key");
1666
+ return encodeOutput(p256EncodePoint(this.publicPoint, format), encoding);
1667
+ }
1668
+ getPrivateKey(encoding) {
1669
+ if (this.privateKey === null) throw new Error("Failed to get ECDH private key");
1670
+ return encodeOutput(bigIntToBytes(this.privateKey, 32), encoding);
1671
+ }
1672
+ setPrivateKey(privateKey, encoding) {
1673
+ const scalar = bytesToBigInt(toBytes(privateKey, encoding));
1674
+ if (scalar <= 0n || scalar >= P256_N) throw new Error("Invalid ECDH private key");
1675
+ this.privateKey = scalar;
1676
+ this.publicPoint = p256ScalarMult(this.privateKey, P256_G);
1677
+ }
1678
+ setPublicKey(publicKey, encoding) {
1679
+ this.publicPoint = p256DecodePoint(publicKey, encoding);
1680
+ }
1681
+ }
1682
+ function createECDH(name) {
1683
+ return new ECDH(name);
1684
+ }
1685
+ function generateKeySync(type, options = {}) {
1686
+ const keyType = String(type).toLowerCase();
1687
+ const length = Number(options && options.length);
1688
+ if (!Number.isInteger(length) || length <= 0) {
1689
+ throw new Error("Browser node:crypto generateKeySync length must be a positive integer");
1690
+ }
1691
+ if (keyType === "aes" && ![128, 192, 256].includes(length)) {
1692
+ const error = new Error("The property 'options.length' must be one of: 128, 192, 256.");
1693
+ error.code = "ERR_INVALID_ARG_VALUE";
1694
+ throw error;
1695
+ }
1696
+ if (keyType !== "hmac" && keyType !== "aes") {
1697
+ return unsupportedBrowserCrypto("generateKeySync");
1698
+ }
1699
+ return createSecretKey(callSync(globalThis._cryptoRandomFill, Math.ceil(length / 8)));
1700
+ }
1701
+ function bytesToBigInt(bytes) {
1702
+ let value = 0n;
1703
+ for (const byte of bytes) value = (value << 8n) | BigInt(byte);
1704
+ return value;
1705
+ }
1706
+ function bigIntToBytes(value, byteLength) {
1707
+ const out = new Uint8Array(byteLength);
1708
+ let cursor = BigInt(value);
1709
+ for (let i = byteLength - 1; i >= 0; i -= 1) {
1710
+ out[i] = Number(cursor & 0xffn);
1711
+ cursor >>= 8n;
1712
+ }
1713
+ return out;
1714
+ }
1715
+ function normalizePrimeOption(name, value) {
1716
+ if (value === undefined) return undefined;
1717
+ if (typeof value === "bigint") return value;
1718
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || Array.isArray(value) || (value && value.type === "Buffer" && Array.isArray(value.data))) {
1719
+ return bytesToBigInt(toBytes(value));
1720
+ }
1721
+ const error = new TypeError('The "options.' + name + '" property must be of type bigint or an instance of ArrayBuffer, TypedArray, Buffer, or DataView.');
1722
+ error.code = "ERR_INVALID_ARG_TYPE";
1723
+ throw error;
1724
+ }
1725
+ function modPow(base, exponent, modulus) {
1726
+ let result = 1n;
1727
+ let cursor = base % modulus;
1728
+ let remaining = exponent;
1729
+ while (remaining > 0n) {
1730
+ if ((remaining & 1n) === 1n) result = (result * cursor) % modulus;
1731
+ cursor = (cursor * cursor) % modulus;
1732
+ remaining >>= 1n;
1733
+ }
1734
+ return result;
1735
+ }
1736
+ const SMALL_PRIMES = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n, 41n, 43n, 47n, 53n, 59n, 61n, 67n, 71n, 73n, 79n, 83n, 89n, 97n];
1737
+ const MILLER_RABIN_BASES = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n];
1738
+ function isProbablePrime(value) {
1739
+ if (value < 2n) return false;
1740
+ for (const prime of SMALL_PRIMES) {
1741
+ if (value === prime) return true;
1742
+ if (value % prime === 0n) return false;
1743
+ }
1744
+ let d = value - 1n;
1745
+ let s = 0;
1746
+ while ((d & 1n) === 0n) {
1747
+ d >>= 1n;
1748
+ s += 1;
1749
+ }
1750
+ for (const base of MILLER_RABIN_BASES) {
1751
+ if (base >= value - 2n) continue;
1752
+ let x = modPow(base, d, value);
1753
+ if (x === 1n || x === value - 1n) continue;
1754
+ let witness = false;
1755
+ for (let r = 1; r < s; r += 1) {
1756
+ x = (x * x) % value;
1757
+ if (x === value - 1n) {
1758
+ witness = true;
1759
+ break;
1760
+ }
1761
+ }
1762
+ if (!witness) return false;
1763
+ }
1764
+ return true;
1765
+ }
1766
+ function randomPrimeCandidate(size, add, rem) {
1767
+ const byteLength = Math.ceil(size / 8);
1768
+ const mask = (1n << BigInt(size)) - 1n;
1769
+ const highBit = 1n << BigInt(size - 1);
1770
+ let candidate = (bytesToBigInt(callSync(globalThis._cryptoRandomFill, byteLength)) & mask) | highBit;
1771
+ if (add !== undefined) {
1772
+ const desired = rem === undefined ? 1n : rem;
1773
+ const delta = (desired - (candidate % add) + add) % add;
1774
+ candidate += delta;
1775
+ if (candidate > mask) candidate -= add;
1776
+ } else {
1777
+ candidate |= 1n;
1778
+ }
1779
+ return candidate;
1780
+ }
1781
+ function generatePrimeSync(size, options = {}) {
1782
+ const bitLength = Number(size);
1783
+ if (!Number.isInteger(bitLength) || bitLength < 2) {
1784
+ throw new RangeError("Browser node:crypto generatePrimeSync size must be an integer greater than 1");
1785
+ }
1786
+ if (bitLength > 4096) {
1787
+ throw new RangeError("Browser node:crypto generatePrimeSync supports primes up to 4096 bits");
1788
+ }
1789
+ const primeOptions = options || {};
1790
+ const add = normalizePrimeOption("add", primeOptions.add);
1791
+ const rem = normalizePrimeOption("rem", primeOptions.rem);
1792
+ if (add !== undefined && add <= 0n) {
1793
+ throw new RangeError("Browser node:crypto generatePrimeSync options.add must be greater than zero");
1794
+ }
1795
+ if (rem !== undefined && add === undefined) {
1796
+ throw new RangeError("Browser node:crypto generatePrimeSync options.rem requires options.add");
1797
+ }
1798
+ const safe = primeOptions.safe === true;
1799
+ while (true) {
1800
+ const candidate = randomPrimeCandidate(bitLength, add, rem);
1801
+ if (candidate < 2n || candidate.toString(2).length !== bitLength) continue;
1802
+ if (!isProbablePrime(candidate)) continue;
1803
+ if (safe && !isProbablePrime((candidate - 1n) / 2n)) continue;
1804
+ if (primeOptions.bigint === true) return candidate;
1805
+ const bytes = bigIntToBytes(candidate, Math.ceil(bitLength / 8));
1806
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1807
+ }
1808
+ }
1809
+ const DIFFIE_HELLMAN_GROUPS = {
1810
+ modp14: {
1811
+ prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff",
1812
+ generator: 2n,
1813
+ },
1814
+ };
1815
+ function bigIntToMinimalBytes(value) {
1816
+ if (value === 0n) return new Uint8Array([0]);
1817
+ return bigIntToBytes(value, Math.ceil(value.toString(16).length / 2));
1818
+ }
1819
+ function normalizeDhNumber(value, encoding) {
1820
+ if (typeof value === "bigint") return value;
1821
+ if (typeof value === "number") return BigInt(value);
1822
+ return bytesToBigInt(toBytes(value, encoding));
1823
+ }
1824
+ class DiffieHellman {
1825
+ constructor(prime, generator = 2n) {
1826
+ this.prime = BigInt(prime);
1827
+ this.generator = BigInt(generator);
1828
+ this.primeLength = Math.ceil(this.prime.toString(2).length / 8);
1829
+ this.privateKey = null;
1830
+ this.publicKey = null;
1831
+ this.verifyError = 0;
1832
+ }
1833
+ _generatePrivateKey() {
1834
+ const randomLength = Math.min(this.primeLength, 32);
1835
+ const random = bytesToBigInt(callSync(globalThis._cryptoRandomFill, randomLength));
1836
+ return 2n + (random % (this.prime - 3n));
1837
+ }
1838
+ generateKeys(encoding) {
1839
+ this.privateKey = this._generatePrivateKey();
1840
+ this.publicKey = modPow(this.generator, this.privateKey, this.prime);
1841
+ return encodeOutput(bigIntToBytes(this.publicKey, this.primeLength), encoding);
1842
+ }
1843
+ computeSecret(otherPublicKey, inputEncoding, outputEncoding) {
1844
+ if (this.privateKey === null) this.generateKeys();
1845
+ const peer = normalizeDhNumber(otherPublicKey, inputEncoding);
1846
+ const secret = modPow(peer, this.privateKey, this.prime);
1847
+ return encodeOutput(bigIntToBytes(secret, this.primeLength), outputEncoding);
1848
+ }
1849
+ getPrime(encoding) {
1850
+ return encodeOutput(bigIntToBytes(this.prime, this.primeLength), encoding);
1851
+ }
1852
+ getGenerator(encoding) {
1853
+ return encodeOutput(bigIntToMinimalBytes(this.generator), encoding);
1854
+ }
1855
+ getPublicKey(encoding) {
1856
+ if (this.publicKey === null) this.generateKeys();
1857
+ return encodeOutput(bigIntToBytes(this.publicKey, this.primeLength), encoding);
1858
+ }
1859
+ getPrivateKey(encoding) {
1860
+ if (this.privateKey === null) this.generateKeys();
1861
+ return encodeOutput(bigIntToMinimalBytes(this.privateKey), encoding);
1862
+ }
1863
+ setPublicKey(key, encoding) {
1864
+ this.publicKey = normalizeDhNumber(key, encoding);
1865
+ }
1866
+ setPrivateKey(key, encoding) {
1867
+ this.privateKey = normalizeDhNumber(key, encoding);
1868
+ this.publicKey = modPow(this.generator, this.privateKey, this.prime);
1869
+ }
1870
+ }
1871
+ function createDiffieHellman(prime, primeEncoding, generator, generatorEncoding) {
1872
+ let normalizedGenerator = generator;
1873
+ let normalizedGeneratorEncoding = generatorEncoding;
1874
+ if (typeof primeEncoding !== "string") {
1875
+ normalizedGenerator = primeEncoding === undefined ? generator : primeEncoding;
1876
+ normalizedGeneratorEncoding = typeof generator === "string" ? generator : undefined;
1877
+ primeEncoding = undefined;
1878
+ }
1879
+ const primeValue = normalizeDhNumber(prime, primeEncoding);
1880
+ const generatorValue = normalizedGenerator === undefined
1881
+ ? 2n
1882
+ : normalizeDhNumber(normalizedGenerator, normalizedGeneratorEncoding);
1883
+ return new DiffieHellman(primeValue, generatorValue);
1884
+ }
1885
+ function getDiffieHellman(name) {
1886
+ const group = DIFFIE_HELLMAN_GROUPS[String(name).toLowerCase()];
1887
+ if (!group) {
1888
+ const error = new Error("Unknown DH group");
1889
+ error.code = "ERR_CRYPTO_UNKNOWN_DH_GROUP";
1890
+ throw error;
1891
+ }
1892
+ return new DiffieHellman(bytesToBigInt(toBytes(group.prime, "hex")), group.generator);
1893
+ }
1894
+ function publicEncrypt(keyOrOptions, buffer) {
1895
+ const options = normalizeAsymmetricOptions(keyOrOptions);
1896
+ const bytes = callSync(
1897
+ globalThis._cryptoAsymmetricOp,
1898
+ "publicEncrypt",
1899
+ normalizeKeyInput(options.key),
1900
+ toBytes(buffer),
1901
+ JSON.stringify({
1902
+ padding: options.padding,
1903
+ oaepHash: options.oaepHash,
1904
+ oaepLabel: options.oaepLabel ? Array.from(toBytes(options.oaepLabel)) : undefined,
1905
+ }),
1906
+ );
1907
+ return makeBuffer(bytes);
1908
+ }
1909
+ function privateDecrypt(keyOrOptions, buffer) {
1910
+ const options = normalizeAsymmetricOptions(keyOrOptions);
1911
+ const bytes = callSync(
1912
+ globalThis._cryptoAsymmetricOp,
1913
+ "privateDecrypt",
1914
+ normalizeKeyInput(options.key),
1915
+ toBytes(buffer),
1916
+ JSON.stringify({
1917
+ padding: options.padding,
1918
+ oaepHash: options.oaepHash,
1919
+ oaepLabel: options.oaepLabel ? Array.from(toBytes(options.oaepLabel)) : undefined,
1920
+ }),
1921
+ );
1922
+ return makeBuffer(bytes);
1923
+ }
1924
+ function randomBytes(size, callback) {
1925
+ const bytes = makeBuffer(callSync(globalThis._cryptoRandomFill, Number(size)));
1926
+ if (typeof callback === "function") queueMicrotask(() => callback(null, bytes));
1927
+ return bytes;
1928
+ }
1929
+ function randomFillSync(buffer, offset = 0, size) {
1930
+ const view = toBytes(buffer);
1931
+ const start = Number(offset) || 0;
1932
+ const length = size == null ? view.byteLength - start : Number(size);
1933
+ view.set(callSync(globalThis._cryptoRandomFill, length), start);
1934
+ return buffer;
1935
+ }
1936
+ function pbkdf2Sync(password, salt, iterations, keyLength, digest = "sha1") {
1937
+ return makeBuffer(callSync(
1938
+ globalThis._cryptoPbkdf2,
1939
+ toBytes(password),
1940
+ toBytes(salt),
1941
+ Number(iterations),
1942
+ Number(keyLength),
1943
+ String(digest),
1944
+ ));
1945
+ }
1946
+ function pbkdf2(password, salt, iterations, keyLength, digest, callback) {
1947
+ if (typeof digest === "function") {
1948
+ callback = digest;
1949
+ digest = "sha1";
1950
+ }
1951
+ queueMicrotask(() => {
1952
+ try {
1953
+ callback(null, pbkdf2Sync(password, salt, iterations, keyLength, digest || "sha1"));
1954
+ } catch (error) {
1955
+ callback(error);
1956
+ }
1957
+ });
1958
+ }
1959
+ function scryptSync(password, salt, keyLength, options = undefined) {
1960
+ return makeBuffer(callSync(
1961
+ globalThis._cryptoScrypt,
1962
+ toBytes(password),
1963
+ toBytes(salt),
1964
+ Number(keyLength),
1965
+ options || {},
1966
+ ));
1967
+ }
1968
+ function scrypt(password, salt, keyLength, options, callback) {
1969
+ if (typeof options === "function") {
1970
+ callback = options;
1971
+ options = undefined;
1972
+ }
1973
+ if (typeof callback !== "function") {
1974
+ throw new TypeError('The "callback" argument must be of type function');
1975
+ }
1976
+ queueMicrotask(() => {
1977
+ try {
1978
+ callback(null, scryptSync(password, salt, keyLength, options));
1979
+ } catch (error) {
1980
+ callback(error);
1981
+ }
1982
+ });
1983
+ }
1984
+ class Cipheriv {
1985
+ constructor(mode, algorithm, key, iv, options = {}) {
1986
+ this.mode = mode;
1987
+ this.algorithm = String(algorithm);
1988
+ this.key = toBytes(key);
1989
+ this.iv = toBytes(iv);
1990
+ this.options = { ...(options || {}) };
1991
+ this.chunks = [];
1992
+ this.finished = false;
1993
+ this.authTag = null;
1994
+ }
1995
+ update(data, inputEncoding, outputEncoding) {
1996
+ if (this.finished) throw new Error("Cipheriv final already called");
1997
+ this.chunks.push(toBytes(data, inputEncoding));
1998
+ return encodeOutput(new Uint8Array(0), outputEncoding);
1999
+ }
2000
+ final(outputEncoding) {
2001
+ if (this.finished) throw new Error("Cipheriv final already called");
2002
+ this.finished = true;
2003
+ const input = concat(this.chunks);
2004
+ let result;
2005
+ if (this.mode === "cipher") {
2006
+ result = callSync(globalThis._cryptoCipheriv, this.algorithm, this.key, this.iv, input, this.options);
2007
+ if (this.algorithm.toLowerCase().endsWith("-gcm")) {
2008
+ this.authTag = result.slice(result.byteLength - 16);
2009
+ result = result.slice(0, result.byteLength - 16);
2010
+ }
2011
+ } else {
2012
+ result = callSync(globalThis._cryptoDecipheriv, this.algorithm, this.key, this.iv, input, this.options);
2013
+ }
2014
+ return encodeOutput(result, outputEncoding);
2015
+ }
2016
+ setAutoPadding(autoPadding = true) {
2017
+ if (this.finished) throw new Error("Cipheriv final already called");
2018
+ this.options.autoPadding = autoPadding !== false;
2019
+ return this;
2020
+ }
2021
+ setAAD(aad) {
2022
+ if (this.finished) throw new Error("Cipheriv final already called");
2023
+ this.options.aad = toBytes(aad);
2024
+ return this;
2025
+ }
2026
+ getAuthTag() {
2027
+ if (!this.authTag) throw new Error("Cipheriv auth tag is not available");
2028
+ return makeBuffer(this.authTag);
2029
+ }
2030
+ setAuthTag(tag) {
2031
+ if (this.finished) throw new Error("Cipheriv final already called");
2032
+ this.options.authTag = toBytes(tag);
2033
+ return this;
2034
+ }
2035
+ }
2036
+ function unsupportedBrowserCrypto(operation) {
2037
+ const error = new Error("node:crypto " + operation + " is not implemented in the browser runtime yet");
2038
+ error.code = "ERR_UNSUPPORTED_BROWSER_CRYPTO";
2039
+ throw error;
2040
+ }
2041
+ module.exports = {
2042
+ createCipheriv: (algorithm, key, iv, options) => new Cipheriv("cipher", algorithm, key, iv, options),
2043
+ createDecipheriv: (algorithm, key, iv, options) => new Cipheriv("decipher", algorithm, key, iv, options),
2044
+ createDiffieHellman,
2045
+ createECDH,
2046
+ createHash: (algorithm) => new Hash(algorithm),
2047
+ createHmac: (algorithm, key) => new Hmac(algorithm, key),
2048
+ constants: CRYPTO_CONSTANTS,
2049
+ createPrivateKey,
2050
+ createPublicKey,
2051
+ createSecretKey,
2052
+ createSign: (algorithm) => new Sign(algorithm),
2053
+ createVerify: (algorithm) => new Verify(algorithm),
2054
+ diffieHellman,
2055
+ generateKeyPair,
2056
+ generateKeyPairSync,
2057
+ generateKeySync,
2058
+ generatePrimeSync,
2059
+ getCiphers: () => [...SUPPORTED_CIPHERS],
2060
+ getCurves: () => [...SUPPORTED_CURVES],
2061
+ getDiffieHellman,
2062
+ getHashes: () => ["md5", "sha1", "sha224", "sha256", "sha384", "sha512"],
2063
+ pbkdf2,
2064
+ pbkdf2Sync,
2065
+ privateDecrypt,
2066
+ publicEncrypt,
2067
+ randomBytes,
2068
+ randomFillSync,
2069
+ randomUUID: () => callSync(globalThis._cryptoRandomUUID),
2070
+ scrypt,
2071
+ scryptSync,
2072
+ sign: signOneShot,
2073
+ subtle: globalThis.crypto && globalThis.crypto.subtle,
2074
+ verify: verifyOneShot,
2075
+ webcrypto: globalThis.crypto,
2076
+ };
2077
+ `,
2078
+ "node:crypto": "module.exports = require('crypto');",
2079
+ wasi: BROWSER_WASI_POLYFILL_CODE,
2080
+ "node:wasi": "module.exports = require('wasi');",
2081
+ os: `
2082
+ const virtualOs = globalThis.__agentOsVirtualOs || {};
2083
+ const stringValue = (value, fallback) =>
2084
+ typeof value === "string" && value.length > 0 ? value : fallback;
2085
+ const platform = stringValue(virtualOs.platform, "linux");
2086
+ const arch = stringValue(virtualOs.arch, "x64");
2087
+ const homedir = stringValue(virtualOs.homedir, "/home/user");
2088
+ const tmpdir = stringValue(virtualOs.tmpdir, "/tmp");
2089
+ const username = stringValue(virtualOs.user, "user");
2090
+ const shell = stringValue(virtualOs.shell, "/bin/sh");
2091
+ const positiveInteger = (value, fallback) =>
2092
+ Number.isSafeInteger(value) && value > 0 ? value : fallback;
2093
+ const nonNegativeInteger = (value, fallback) =>
2094
+ Number.isSafeInteger(value) && value >= 0 ? value : fallback;
2095
+ const cpuCount = positiveInteger(virtualOs.cpuCount, 1);
2096
+ const totalmem = positiveInteger(virtualOs.totalmem, 1024 * 1024 * 1024);
2097
+ const freemem = Math.min(
2098
+ positiveInteger(virtualOs.freemem, 512 * 1024 * 1024),
2099
+ totalmem,
2100
+ );
2101
+ const uid = nonNegativeInteger(virtualOs.uid, 1000);
2102
+ const gid = nonNegativeInteger(virtualOs.gid, 1000);
2103
+ const cpuInfo = () => ({
2104
+ model: stringValue(virtualOs.cpuModel, "secure-exec virtual CPU"),
2105
+ speed: 0,
2106
+ times: { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 },
2107
+ });
2108
+ module.exports = {
2109
+ EOL: "\\n",
2110
+ arch: () => arch,
2111
+ cpus: () => Array.from({ length: cpuCount }, cpuInfo),
2112
+ endianness: () => "LE",
2113
+ freemem: () => freemem,
2114
+ getPriority: () => 0,
2115
+ homedir: () => homedir,
2116
+ hostname: () => stringValue(virtualOs.hostname, "secure-exec"),
2117
+ loadavg: () => [0, 0, 0],
2118
+ machine: () => stringValue(virtualOs.machine, "x86_64"),
2119
+ networkInterfaces: () => ({}),
2120
+ platform: () => platform,
2121
+ release: () => stringValue(virtualOs.release, "6.8.0-secure-exec"),
2122
+ tmpdir: () => tmpdir,
2123
+ totalmem: () => totalmem,
2124
+ type: () => stringValue(virtualOs.type, platform === "win32" ? "Windows_NT" : "Linux"),
2125
+ uptime: () => 0,
2126
+ userInfo: () => ({ username, uid, gid, shell, homedir }),
2127
+ version: () => stringValue(virtualOs.version, "#1 SMP PREEMPT_DYNAMIC secure-exec"),
2128
+ };
2129
+ `,
2130
+ "node:os": "module.exports = require('os');",
2131
+ };
2132
+ export function exposeCustomGlobal(name, value) {
2133
+ globalThis[name] = value;
2134
+ }
2135
+ export function exposeMutableRuntimeStateGlobal(name, value) {
2136
+ globalThis[name] = value;
2137
+ }
2138
+ export function getIsolateRuntimeSource(id) {
2139
+ if (id === "overrideProcessCwd") {
2140
+ return `
2141
+ if (globalThis.process && globalThis.__runtimeProcessCwdOverride) {
2142
+ globalThis.process.cwd = () => String(globalThis.__runtimeProcessCwdOverride);
2143
+ }
2144
+ `;
2145
+ }
2146
+ return "";
2147
+ }
2148
+ export function getRequireSetupCode() {
2149
+ return `
2150
+ (function () {
2151
+ ${guestEncodingBootstrapCode()}
2152
+
2153
+ const callSyncBridge = (ref, ...args) => {
2154
+ if (typeof ref === "function") {
2155
+ return ref(...args);
2156
+ }
2157
+ if (ref && typeof ref.applySync === "function") {
2158
+ return ref.applySync(undefined, args);
2159
+ }
2160
+ if (ref && typeof ref.applySyncPromise === "function") {
2161
+ return ref.applySyncPromise(undefined, args);
2162
+ }
2163
+ return undefined;
2164
+ };
2165
+
2166
+ const pathDirname = (value) => {
2167
+ const normalized = String(value || "/").replace(/\\\\/g, "/");
2168
+ if (normalized === "/") return "/";
2169
+ const parts = normalized.split("/").filter(Boolean);
2170
+ return parts.length <= 1 ? "/" : "/" + parts.slice(0, -1).join("/");
2171
+ };
2172
+
2173
+ globalThis.require = function require(specifier) {
2174
+ const polyfillSource = callSyncBridge(
2175
+ globalThis._loadPolyfill,
2176
+ specifier.replace(/^node:/, ""),
2177
+ );
2178
+ if (polyfillSource) {
2179
+ const module = { exports: {} };
2180
+ const fn = new Function("module", "exports", polyfillSource);
2181
+ fn(module, module.exports);
2182
+ return module.exports;
2183
+ }
2184
+
2185
+ const currentModule = globalThis._currentModule || { dirname: "/" };
2186
+ const resolved = callSyncBridge(
2187
+ globalThis._resolveModuleSync,
2188
+ specifier,
2189
+ currentModule.dirname || "/",
2190
+ "require",
2191
+ );
2192
+ if (!resolved) {
2193
+ throw new Error("Cannot resolve module '" + specifier + "'");
2194
+ }
2195
+
2196
+ const cache = globalThis._moduleCache || (globalThis._moduleCache = {});
2197
+ if (cache[resolved]) {
2198
+ return cache[resolved].exports;
2199
+ }
2200
+
2201
+ const source = callSyncBridge(
2202
+ globalThis._loadFileSync,
2203
+ resolved,
2204
+ "require",
2205
+ );
2206
+ if (source == null) {
2207
+ throw new Error("Cannot load module '" + resolved + "'");
2208
+ }
2209
+
2210
+ const module = { exports: {} };
2211
+ cache[resolved] = module;
2212
+ const previous = globalThis._currentModule;
2213
+ globalThis._currentModule = { filename: resolved, dirname: pathDirname(resolved) };
2214
+ try {
2215
+ const fn = new Function(
2216
+ "require",
2217
+ "module",
2218
+ "exports",
2219
+ "__filename",
2220
+ "__dirname",
2221
+ source,
2222
+ );
2223
+ fn(globalThis.require, module, module.exports, resolved, pathDirname(resolved));
2224
+ } finally {
2225
+ globalThis._currentModule = previous;
2226
+ }
2227
+ return module.exports;
2228
+ };
2229
+
2230
+ const util = globalThis.require("util");
2231
+ const formatConsoleLine = (...args) => {
2232
+ if (!util || typeof util.formatWithOptions !== "function") {
2233
+ throw new Error("console formatting requires util.formatWithOptions");
2234
+ }
2235
+ return util.formatWithOptions({ colors: false }, ...args) + "\\n";
2236
+ };
2237
+ const writeConsole = (ref, args) => {
2238
+ callSyncBridge(ref, formatConsoleLine(...args));
2239
+ };
2240
+ const consoleObject = {
2241
+ log: (...args) => writeConsole(globalThis._log, args),
2242
+ info: (...args) => writeConsole(globalThis._log, args),
2243
+ debug: (...args) => writeConsole(globalThis._log, args),
2244
+ warn: (...args) => writeConsole(globalThis._error, args),
2245
+ error: (...args) => writeConsole(globalThis._error, args),
2246
+ dir: (value) => writeConsole(globalThis._log, [value]),
2247
+ dirxml: (...args) => writeConsole(globalThis._log, args),
2248
+ assert: (condition, ...args) => {
2249
+ if (condition) return;
2250
+ writeConsole(globalThis._error, args.length > 0 ? args : ["Assertion failed"]);
2251
+ },
2252
+ clear: () => {},
2253
+ count: (label = "default") => {
2254
+ const key = String(label);
2255
+ consoleObject._counts.set(key, (consoleObject._counts.get(key) || 0) + 1);
2256
+ consoleObject.log(key + ": " + consoleObject._counts.get(key));
2257
+ },
2258
+ countReset: (label = "default") => {
2259
+ consoleObject._counts.delete(String(label));
2260
+ },
2261
+ group: (...args) => {
2262
+ if (args.length > 0) consoleObject.log(...args);
2263
+ },
2264
+ groupCollapsed: (...args) => {
2265
+ if (args.length > 0) consoleObject.log(...args);
2266
+ },
2267
+ groupEnd: () => {},
2268
+ table: (value) => consoleObject.log(value),
2269
+ time: (label = "default") => {
2270
+ consoleObject._times.set(String(label), Date.now());
2271
+ },
2272
+ timeEnd: (label = "default") => {
2273
+ const key = String(label);
2274
+ if (!consoleObject._times.has(key)) return;
2275
+ const startedAt = consoleObject._times.get(key);
2276
+ consoleObject._times.delete(key);
2277
+ consoleObject.log(key + ": " + (Date.now() - startedAt) + "ms");
2278
+ },
2279
+ timeLog: (label = "default", ...args) => {
2280
+ const key = String(label);
2281
+ if (!consoleObject._times.has(key)) return;
2282
+ consoleObject.log(key + ": " + (Date.now() - consoleObject._times.get(key)) + "ms", ...args);
2283
+ },
2284
+ trace: (...args) => {
2285
+ const message = formatConsoleLine(...args).trimEnd();
2286
+ const error = new Error(message);
2287
+ writeConsole(globalThis._error, [error.stack || message]);
2288
+ },
2289
+ _counts: new Map(),
2290
+ _times: new Map(),
2291
+ };
2292
+ globalThis.console = consoleObject;
2293
+ })();
2294
+ `;
2295
+ }
2296
+ export { createInMemoryFileSystem, InMemoryFileSystem };