Repository navigation
Expand file tree
/
Copy pathprocess.ts
More file actions
2274 lines (2127 loc) · 84.3 KB
/
Copy pathprocess.ts
File metadata and controls
2274 lines (2127 loc) · 84.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// node:process — Node's `process` object, in Zun TypeScript over the native
// `node:process` extension.
//
// Behavior is defined by Node.js 25: this module is finished when it passes
// 100% of Node's own `test/parallel/test-process-*` files (see
// ../../test/process/). The API shaping follows Node's
// `lib/internal/process/per_thread.js`, `lib/internal/process/warning.js` and
// `lib/internal/bootstrap/node.js` (MIT, Copyright Joyent, Inc. and other Node
// contributors) — the `exit` ordering, the `exitCode` coercion ladder, `kill`'s
// signal resolution through `_kill`, `cpuUsage`'s validation order, `hrtime`'s
// borrow arithmetic, the `emitWarning` option grammar and the
// `NodeEnvironmentFlagsSet` shape — because every one of those is observable
// through the corpus rather than derivable.
//
// ---------------------------------------------------------------------------
// Why this module is split in THREE files
// ---------------------------------------------------------------------------
//
// `os`, `fs` and `child_process` are each two files: a Rust extension and a
// Node-shaped `.ts` that imports it. `process` cannot be, and the reason is
// the whole design:
//
// > **every** bundle in this library inlines this file, and most of them run
// > without `--ext`.
//
// `path`, `events`, `util`, `assert`, `url`, `querystring`, `punycode` and
// `timers` are pure computation; their tests run as `zun run <bundle.ts>` with
// no extension at all. If this file said `import * as native from
// "node:process"`, every one of those bundles would fail to *compile* for want
// of a cdylib it does not need — exactly the coupling PLAN.md's principle 2
// keeps out of a pure-computation module.
//
// So the import lives in a third file. `src/process/native.ts` is nothing but
//
// import * as __procNative from "node:process";
// __processInstallNative({ /* one method per native */ });
//
// and `tools/bundle_node_test.sh` inlines it only when the bundle will be run
// with `--ext` (the `ZUN_NODE_EXT` gate, which `tools/run_node_tests.sh` sets
// for its `zun-ts+ext` kinds). All the logic is here; `native.ts` carries none.
// Every native-backed value therefore has two paths:
//
// * **with the extension** — the real syscall, through `__procOps()`.
// * **without it** — a documented fallback. Each one is marked `NO-EXT:` at
// its use site, and the complete list is:
//
// | value | without the extension |
// |--------------------------------|--------------------------------------|
// | `pid`, `ppid` | `0` (the host surface reports none) |
// | `platform` | derived from the shape of `cwd()` |
// | `arch` | `"x64"` |
// | `execPath`, `argv[0]` | the raw `argv[0]` the host was given |
// | `title` | the basename of `argv[0]` |
// | `env` | a snapshot of a fixed name list |
// | `hrtime`, `uptime` | `Date.now()`, millisecond resolution |
// | `cpuUsage`, `threadCpuUsage` | zeros |
// | `memoryUsage`, `resourceUsage` | zeros |
// | `availableMemory`/`constrained` | `0` |
// | `umask` | the platform default, remembered |
// | `chdir`, `kill` | `ERR_METHOD_NOT_IMPLEMENTED` |
// | `abort` | exit with 128 + SIGABRT |
// | `getuid` and the other four | absent, as on Windows |
// | `stdout.isTTY` | the host's single `isTty()` flag |
//
// `src/os/os.ts` used to patch `process.pid` from its own native, because this
// file had none. That line is gone: the pid comes from `procFacts` now, and a
// bundle that has `os` has `--ext` and therefore has `native.ts` too.
//
// ---------------------------------------------------------------------------
// The shape of `process` itself
// ---------------------------------------------------------------------------
//
// `process` stays an **object literal** rather than becoming an `EventEmitter`
// subclass, for the reason it always has: an object-literal method is the only
// shape in which a method can carry a rest parameter and `arguments` at the
// same time in this engine, and `process.emit(type, ...args)` needs both. The
// emitter side is delegated to one `EventEmitter` instance.
//
// The `EventEmitter`-derived prototype Node gives `process` (with its own
// `constructor` descriptor, which `test-process-prototype.js` reads) is set on
// the literal afterwards with `Object.setPrototypeOf` (`__processProto`).
//
// ---------------------------------------------------------------------------
// Engine workarounds in this file, each tied to an open zun issue
// (https://github.com/UrubuCode/zun/issues)
// ---------------------------------------------------------------------------
// * `Number(x.length)` throughout: the checker still types `.length` as
// `u64`, so it can be neither assigned to nor passed as a `number` (zun#3).
// * a callable stored where an `any` can reach it is wrapped with `__evBox`
// (../events/events.ts), because a bare function value does not survive
// every path through `any` (zun#17) while the box — a real object that is
// still callable and still carries its own properties — does. That is how
// `process.hrtime.bigint` and `process.memoryUsage.rss` exist at all:
// Node hangs a property off a function, and a box is the only function
// value here that keeps one.
// * `__evCall(fn, args)` rather than `fn.apply(...)`: `call`/`apply` do not
// thread a receiver (zun#1).
// * `process.env` is a plain object whose entries are **accessor**
// properties, not a `Proxy`. The `get`/`set`/`has`/`deleteProperty`/
// `defineProperty` traps all work now, but `ownKeys` never fires, so
// `Object.keys(process.env)` over a Proxy comes back empty
// (https://github.com/UrubuCode/zun/issues/6) — and `Object.keys`,
// `{ ...process.env }` and `structuredClone(process.env)` are read by
// `node:child_process`, by the harness and by Node's own corpus. Accessors
// keep enumeration exact *and* make a write to an existing variable a real
// `setenv`; what they cannot give is interception of a **new** name, which
// is what the three `test-process-env-{delete,deprecation,
// ignore-getter-setter}.js` files measure. See ../../test/process/README.md.
// * `process.config` is frozen and `process.exitCode` is a non-configurable
// accessor, and both rely on this engine throwing a `TypeError` for a write
// to a frozen object and for a `delete` of a non-configurable property even
// outside strict mode — which it does, and which is what Node's own tests
// expect from the strict-mode module they run in.
// * `process.allowedNodeEnvironmentFlags` is written as Node writes it — a
// frozen `Set` subclass whose iteration comes from an internal array — and
// is still only half-observable here: `Set.prototype.add` reads
// `undefined`, so `Set.prototype.add.call(flags, 'foo')` throws instead of
// being the no-op the test needs (zun#25, no function-prototype model).
// * `Error.captureStackTrace` does not exist in this engine, which is what
// blocks `test-process-emitwarning.js`: the test's own `CustomWarning`
// constructor calls it. Nothing in this file can work around a gap in the
// test's own code; it is recorded in ../../test/process/README.md.
import { host } from "zun:core";
// ---------------------------------------------------------------------------
// The native bridge
// ---------------------------------------------------------------------------
// The methods `src/process/native.ts` installs, or `undefined` when this bundle
// was built without the extension. One object with one method per native, for
// the reason every module surface here is object-literal methods: a method
// survives every path through `any`, a bare function value does not (zun#17).
const __processNativeState: any = { ops: undefined };
// `undefined` when there is no extension. Every caller must handle that.
function __procOps(): any {
return __processNativeState.ops;
}
// Record and unit separators of the native carrier, and the failure marker.
// The grammar is documented in src/process/mod.rs and is the mirror image of
// `__procRecords` below:
//
// result := "+" payload | "-" payload := record (RS record)*
// record := field (US field)* RS = U+001E US = U+001F
const __PROC_RS: string = String.fromCharCode(30);
const __PROC_US: string = String.fromCharCode(31);
const __PROC_FAILED: string = "-";
const __PROC_MAX_SAFE: number = 9007199254740991;
// Did the last native call fail? Then raise what Node raises.
function __procFailed(payload: any): boolean {
return payload === __PROC_FAILED;
}
// Split a successful payload into records of fields.
function __procRecords(payload: string): string[][] {
const body: string = payload.slice(1);
if (body === "") return [];
const rows: string[][] = [];
for (const record of body.split(__PROC_RS)) {
rows.push(record.split(__PROC_US));
}
return rows;
}
// The one record of a single-record payload.
function __procFields(payload: string): string[] {
const rows: string[][] = __procRecords(payload);
if (Number(rows.length) === 0) return [];
return rows[0];
}
// The whole payload of a single-field result, byte for byte.
function __procPayload(payload: string): string {
return payload.slice(1);
}
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
// Node's `uvException`/`errnoException`: the error a failed libuv call becomes
// outside `os`. `message` is `"<code>: <description>, <syscall> '<path>'"` with
// `" -> '<dest>'"` appended when the call carried two paths — which `chdir`
// does and nothing else here does — or the bare `"<syscall> <code>"` of
// `errnoException`, which is what `process.kill` raises.
//
// Every field is **declared**, as in every error class in this library: an
// undeclared key written onto a typed instance through an `any` alias poisons
// every later statically typed read of that instance
// (https://github.com/UrubuCode/zun/issues/37).
class ProcessSystemError extends NodeError {
errno: number = 0;
syscall: string = "";
path: any = undefined;
dest: any = undefined;
constructor(code: string, message: string) {
super(code, message);
}
}
// Node's `errnoException`, whose message is `"<syscall> <code>"` and no more.
function __procErrnoException(syscall: string): any {
const ops: any = __procOps();
const code: string = String(ops.errorCode());
const error: any = new ProcessSystemError(code, syscall + " " + code);
error.errno = Number(ops.errorErrno());
error.syscall = syscall;
return error;
}
// Node's `uvException` for the one call here that carries paths.
function __procUvException(): any {
const ops: any = __procOps();
const code: string = String(ops.errorCode());
const syscall: string = String(ops.errorSyscall());
const description: string = String(ops.errorMessage());
const path: string = String(ops.errorPath());
const dest: string = String(ops.errorDest());
let message: string = code + ": " + description + ", " + syscall;
if (path !== "") message = message + " '" + path + "'";
if (dest !== "") message = message + " -> '" + dest + "'";
const error: any = new ProcessSystemError(code, message);
error.errno = Number(ops.errorErrno());
error.syscall = syscall;
if (path !== "") error.path = path;
if (dest !== "") error.dest = dest;
return error;
}
// `ERR_INVALID_ARG_VALUE` with a `RangeError` name, which is Node's
// `ERR_INVALID_ARG_VALUE.RangeError` — the shape `cpuUsage` raises for a
// previous value that is a number but not a usable one.
class ERR_INVALID_ARG_VALUE_RANGE extends NodeRangeError {
constructor(name: string, value: any) {
super(
"ERR_INVALID_ARG_VALUE",
"The property '" + name + "' is invalid. Received " + inspect(value),
);
}
}
// `ERR_METHOD_NOT_IMPLEMENTED` is Node's own error for an entry point this
// build does not have, with Node's own message, and in `process` it is what a
// native-backed *action* raises when the bundle has no extension: a
// native-backed *value* can fall back to a documented substitute, while
// `chdir` and `kill` cannot, so they say so rather than lie.
//
// It is **not declared here**. Four files in this library raise it -- this one,
// `src/fs/fs.ts` (`fs.glob`, `fs.watch`, `fs.createReadStream`, ...),
// `src/stream/stream.ts` (`_read`, `_write`, `_transform`) and
// `src/child_process/child_process.ts` -- and two top-level declarations of one
// name are a compile error in a single Zun program, which a bundle of `fs` plus
// `stream` is. The one home that cannot collide is therefore the error bases
// themselves: it is declared in `src/events/events.ts`, which every bundle
// inlines ahead of this file.
// `ERR_UNKNOWN_SIGNAL`, on the other hand, *is* declared here rather than in
// `src/child_process/child_process.ts`, which resolves the same signal names
// for `killSignal` -- this file is in every bundle and that one is
// conditional, so here is where the single declaration lands. Node's message is
// `'Unknown signal: %s'`, and `%s` on a string is the string itself — so an
// unknown signal *name* is reported bare, and only a non-string is inspected.
class ERR_UNKNOWN_SIGNAL extends NodeTypeError {
constructor(signal: any) {
super(
"ERR_UNKNOWN_SIGNAL",
"Unknown signal: " + (typeof signal === "string" ? signal : inspect(signal)),
);
}
}
// `process.execve` exists on every platform in Node 25 and is usable on none
// but POSIX; this is what it raises elsewhere.
class ERR_FEATURE_UNAVAILABLE_ON_PLATFORM extends NodeTypeError {
constructor(feature: string) {
super(
"ERR_FEATURE_UNAVAILABLE_ON_PLATFORM",
"The feature " +
feature +
" is unavailable on this platform, which is being used to run Node.js",
);
}
}
class ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET extends NodeError {
constructor() {
super(
"ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET",
"`process.setupUncaughtExceptionCapture()` was called while a capture callback was already active",
);
}
}
class ERR_DLOPEN_FAILED extends NodeError {
constructor(message: string) {
super("ERR_DLOPEN_FAILED", message);
}
}
// ---------------------------------------------------------------------------
// Validators (lib/internal/validators.js, reduced to what `process` uses)
// ---------------------------------------------------------------------------
function __procValidateString(value: any, name: string): void {
if (typeof value !== "string") {
throw new ERR_INVALID_ARG_TYPE(name, "string", value);
}
}
// `validateNumber(value, name)` with neither bound — a *type* check only, which
// is what `cpuUsage` needs: an `Infinity` previous value must reach the
// `ERR_INVALID_ARG_VALUE` branch rather than being rejected as out of range.
function __procValidateNumberType(value: any, name: string): void {
if (typeof value !== "number") {
throw new ERR_INVALID_ARG_TYPE(name, "number", value);
}
}
function __procValidateUint32(value: any, name: string): void {
if (typeof value !== "number") {
throw new ERR_INVALID_ARG_TYPE(name, "number", value);
}
if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
throw new ERR_OUT_OF_RANGE(name, ">= 0 && <= 4294967295", value);
}
}
// `parseFileMode(value, name)`: a uint32, or a string of octal digits.
function __procParseFileMode(value: any, name: string): number {
let parsed: any = value;
if (typeof value === "string") {
if (!__procIsOctalDigits(value)) {
throw new ERR_INVALID_ARG_VALUE(
name,
value,
"must be a 32-bit unsigned integer or an octal string",
);
}
parsed = parseInt(value, 8);
}
__procValidateUint32(parsed, name);
return Number(parsed);
}
// `/^[0-7]+$/`, spelled with `charCodeAt` over a bounded index because a
// `charCodeAt` past the end throws here (zun#2).
function __procIsOctalDigits(text: string): boolean {
const count: number = Number(text.length);
if (count === 0) return false;
for (let i = 0; i < count; i++) {
const code: number = text.charCodeAt(i);
if (code < 48 || code > 55) return false;
}
return true;
}
// ---------------------------------------------------------------------------
// Platform, architecture and the executable
// ---------------------------------------------------------------------------
function __processCwd(): string {
return host.cwd();
}
// NO-EXT: with no native to ask, the platform is derived from the shape of
// `cwd()` — a `X:\...` drive-rooted working directory means Windows. The
// extension replaces this with `procFacts`' answer, which is the compile-time
// target rather than a guess.
function __looksWindows(): boolean {
const cwd = __processCwd();
if (cwd.length < 3) return false;
const drive = cwd.charCodeAt(0);
const isLetter =
(drive >= 65 && drive <= 90) || (drive >= 97 && drive <= 122);
if (!isLetter) return false;
if (cwd.charCodeAt(1) !== 58) return false; // ':'
const third = cwd.charCodeAt(2);
return third === 92 || third === 47; // '\' or '/'
}
const __isWindowsHost: boolean = __looksWindows();
// The raw argument vector the host was started with. For the `zun` CLI that is
// `[<zun binary>, "run", <engine options...>, <script>, <script arguments...>]`,
// which is not Node's `argv` — Node's is
// `[execPath, <main script>, <script arguments...>]`, with the interpreter's own
// options split off into `execArgv`. `__processSplitArgv` does that split.
function __processRawArgv(): string[] {
const out: string[] = [];
const count = Number(host.argCount());
for (let i = 0; i < count; i++) {
out.push(host.argAt(i));
}
return out;
}
// The engine options that take a separate value argument, so the scan below
// does not mistake one for the script path.
const __PROC_VALUE_OPTIONS: string[] = ["--ext", "-e", "--eval"];
// Split the raw vector into `argv0`, `execArgv`, the script and its arguments.
//
// The rule is the `zun` CLI's own shape: element 0 is the binary, element 1 is
// the subcommand (`run`), and from there every element that begins with `-` is
// an engine option — plus the following element when the option is one that
// takes a value. The first element that is neither is the script, and
// everything after it belongs to the script. A vector with no subcommand at all
// (the engine embedded elsewhere) degrades to "no script, no arguments", which
// is what Node reports for a REPL.
function __processSplitArgv(): any {
const raw: string[] = __processRawArgv();
const count: number = Number(raw.length);
const split: any = {
argv0: count > 0 ? raw[0] : "",
execArgv: [],
script: undefined,
rest: [],
};
let index: number = count > 1 ? 2 : count;
while (index < count) {
const entry: string = raw[index];
if (entry === "" || entry.charAt(0) !== "-") break;
split.execArgv.push(entry);
if (Number(__PROC_VALUE_OPTIONS.indexOf(entry)) !== -1 && index + 1 < count) {
split.execArgv.push(raw[index + 1]);
index = index + 2;
continue;
}
index = index + 1;
}
if (index < count) {
split.script = raw[index];
for (let i = index + 1; i < count; i++) split.rest.push(raw[i]);
}
// Under the `node`-shaped launcher (src/bin/zun-node-run.rs) the engine's
// own options are not the program's: the Node flags the launcher was given
// (`--test-reporter=tap`, `--test-only`, ...) travel in ZUN_NODE_EXEC_ARGV,
// in the ZUN_NODE_ARGV encoding, and are what `process.execArgv` reports.
if (host.envHas("ZUN_NODE_EXEC_ARGV")) {
const packed: string = String(host.envGet("ZUN_NODE_EXEC_ARGV"));
if (packed.charAt(0) === "A") {
const flags: string[] = [];
const body: string = packed.slice(1);
if (body !== "") {
for (const entry of body.split("\u001f")) flags.push(entry);
}
split.execArgv = flags;
}
}
return split;
}
const __processArgvSplit: any = __processSplitArgv();
// `process.argv`: the executable, the main script, then the script's own
// arguments. NO-EXT: `execPath` is the raw `argv[0]` until the native reports
// the resolved one.
//
// `ZUN_NODE_ARGV` is the one exception: the `zun` CLI takes no script arguments
// (`zun run [--ext <lib>] <file>`, nothing after the file), so the `node`-shaped
// launcher `src/bin/zun-node-run.rs` — which re-executes a Node test as a child
// — hands the child's `process.argv` tail over in this variable instead: `"A"`
// then the entries, `U+001F`-separated (the leading letter keeps the value
// non-empty, because Windows treats an empty variable as unset).
function __processBuildArgv(execPath: string): string[] {
const argv: string[] = [execPath];
if (host.envHas("ZUN_NODE_ARGV")) {
const packed: string = String(host.envGet("ZUN_NODE_ARGV"));
if (packed.charAt(0) === "A") {
const body: string = packed.slice(1);
if (body !== "") {
for (const entry of body.split("\u001f")) argv.push(entry);
}
return argv;
}
}
const script: any = __processArgvSplit.script;
if (script !== undefined) argv.push(String(script));
for (const entry of __processArgvSplit.rest) argv.push(String(entry));
return argv;
}
// The basename of a path, for the no-extension `process.title`.
function __processBasename(value: string): string {
let start: number = 0;
const count: number = Number(value.length);
for (let i = 0; i < count; i++) {
const code: number = value.charCodeAt(i);
if (code === 47 || code === 92) start = i + 1;
}
return value.slice(start);
}
// ---------------------------------------------------------------------------
// process.env
// ---------------------------------------------------------------------------
// The backing store every `process.env` accessor reads and writes, so a write
// through the accessor and a write through `procSetEnv` cannot drift.
const __processEnvState: any = { values: {} };
function __processEnvGet(name: string): any {
if (!host.envHas(name)) return undefined;
return host.envGet(name);
}
// NO-EXT: `zun:core` can read a variable by name but cannot enumerate the
// environment block, so without the extension `process.env` is a snapshot over
// a fixed list of names — the ones Node's own tests touch, plus the per-drive
// `=X:` cwd variables `win32.resolve` consults. `envLookup` stays available for
// a name outside the list. With the extension, `procEnviron` reports the whole
// block and this list is not used at all.
const __envNames: string[] = [
"PATH",
"Path",
"PATHEXT",
"HOME",
"HOMEDRIVE",
"HOMEPATH",
"USERPROFILE",
"USERNAME",
"TEMP",
"TMP",
"TMPDIR",
"OS",
"OSTYPE",
"ComSpec",
"SystemRoot",
"SystemDrive",
"windir",
"PWD",
"CD",
"NODE_ENV",
"NODE_OPTIONS",
"NODE_PATH",
"NODE_TEST_NO_COLORS",
"NO_COLOR",
"FORCE_COLOR",
"LANG",
"LC_ALL",
"TZ",
];
// One `process.env` entry: an accessor over `__processEnvState.values`, so a
// read is live, a write reaches the real environment, and the property is still
// an own enumerable key — which is what makes `Object.keys(process.env)`,
// `{ ...process.env }` and `structuredClone(process.env)` correct. See the note
// on the Proxy in the header.
function __processDefineEnvEntry(env: any, name: string, value: string): void {
__processEnvState.values[name] = value;
Object.defineProperty(env, name, {
configurable: true,
enumerable: true,
get(): any {
return __processEnvState.values[name];
},
set(assigned: any): void {
__processEnvAssign(name, assigned);
},
});
}
// `process.env.NAME = value`. Node coerces the value to a string (so
// `env.X = undefined` reads back as the nine characters `undefined`) and
// refuses a symbol, because a symbol has no string form.
function __processEnvAssign(name: string, value: any): void {
if (typeof value === "symbol") {
throw new TypeError("Cannot convert a Symbol value to a string");
}
const text: string = String(value);
__processEnvState.values[name] = text;
const ops: any = __procOps();
if (ops !== undefined) ops.setEnv(name, text, false);
}
// The no-extension environment: the fixed name list, as accessors.
function __processBuildEnv(): any {
const env: any = {};
for (const name of __envNames) {
if (host.envHas(name)) __processDefineEnvEntry(env, name, String(host.envGet(name)));
}
// The cmd.exe per-drive current directories: `=C:`, `=D:`, ...
for (let letter = 65; letter <= 90; letter++) {
const name = "=" + String.fromCharCode(letter) + ":";
if (host.envHas(name)) __processDefineEnvEntry(env, name, String(host.envGet(name)));
}
return env;
}
const __processEnv: any = __processBuildEnv();
// Replace the snapshot with the real environment block, which only the
// extension can enumerate. Called once from `__processInstallNative`.
function __processRebuildEnv(ops: any): void {
const payload: string = String(ops.environ());
if (__procFailed(payload)) return;
const fresh: any = {};
__processEnvState.values = {};
for (const record of __procRecords(payload)) {
if (Number(record.length) < 1) continue;
const name: string = record[0];
if (name === "") continue;
__processDefineEnvEntry(fresh, name, Number(record.length) > 1 ? record[1] : "");
}
process.env = fresh;
}
// ---------------------------------------------------------------------------
// Signals
// ---------------------------------------------------------------------------
//
// One table per platform, which `process.kill` resolves a signal *name*
// through. It lives here rather than in `src/os/os.ts` on purpose: this file is
// in every bundle and `os` is not, and in Node both `os.constants.signals` and
// `process.kill` read the one table the `constants` binding publishes — so
// `src/os/os.ts` takes `signals` from here instead of carrying a second copy.
const __processSignalsWin32: any = {
SIGHUP: 1,
SIGINT: 2,
SIGQUIT: 3,
SIGILL: 4,
SIGABRT: 22,
SIGFPE: 8,
SIGKILL: 9,
SIGSEGV: 11,
SIGTERM: 15,
SIGBREAK: 21,
SIGWINCH: 28,
};
const __processSignalsPosix: any = {
SIGHUP: 1,
SIGINT: 2,
SIGQUIT: 3,
SIGILL: 4,
SIGTRAP: 5,
SIGABRT: 6,
SIGIOT: 6,
SIGBUS: 7,
SIGFPE: 8,
SIGKILL: 9,
SIGUSR1: 10,
SIGSEGV: 11,
SIGUSR2: 12,
SIGPIPE: 13,
SIGALRM: 14,
SIGTERM: 15,
SIGCHLD: 17,
SIGSTKFLT: 16,
SIGCONT: 18,
SIGSTOP: 19,
SIGTSTP: 20,
SIGTTIN: 21,
SIGTTOU: 22,
SIGURG: 23,
SIGXCPU: 24,
SIGXFSZ: 25,
SIGVTALRM: 26,
SIGPROF: 27,
SIGWINCH: 28,
SIGIO: 29,
SIGPOLL: 29,
SIGPWR: 30,
SIGSYS: 31,
};
function __processSignalTable(): any {
return process.platform === "win32" ? __processSignalsWin32 : __processSignalsPosix;
}
// ---------------------------------------------------------------------------
// The process emitter
// ---------------------------------------------------------------------------
const __processEmitter: any = new EventEmitter();
// Node's `process` has no max-listeners warning for its own events.
__processEmitter.setMaxListeners(0);
// ---------------------------------------------------------------------------
// process.nextTick
//
// One FIFO queue drained by a single `queueMicrotask` pass; callbacks queued
// during the drain are picked up by the same pass, which is what Node does.
// `__processPendingTicks()` is what the harness epilogue watches to decide the
// loop has gone quiet.
//
// Node drains its own nextTick queue ahead of promise reactions; here the two
// share one queue, so a `nextTick` scheduled from inside a promise reaction
// runs after it rather than before. The relative order *within* the queue is
// FIFO, as in Node.
// ---------------------------------------------------------------------------
const __tickQueue: any = { items: [], scheduled: false };
// Process-wide state `process`'s own methods read and write.
const __processState: any = {
umask: __isWindowsHost ? 0 : 0o022,
title: undefined,
sourceMaps: false,
config: undefined,
features: undefined,
flags: undefined,
execveWarned: false,
loadedAt: Number(Date.now()),
// `true` inside a `worker_threads` worker (set by `__wtBootWorker`). A worker
// does not own the process state, so, as in Node's
// `lib/internal/bootstrap/switches/does_not_own_process_state.js`, the calls
// that would change it throw `ERR_WORKER_UNSUPPORTED_OPERATION`.
isWorker: false,
};
function __processPendingTicks(): number {
return Number(__tickQueue.items.length);
}
function __drainTicks(): void {
__tickQueue.scheduled = false;
while (Number(__tickQueue.items.length) > 0) {
const entry: any = __tickQueue.items.shift();
// A throw out of a tick callback is an uncaught exception in Node, not a
// rejected microtask: it reaches `process.on('uncaughtException')` and, with
// no listener, ends the process. That is what `test-process-next-tick.js`
// measures, and the reason each callback runs inside a `try`.
//
// `node:domain`: a tick belongs to the domain that was active when it was
// *scheduled*, and a throw out of it is routed to that domain rather than
// straight to `process` — which has to happen while the domain is still on
// the stack, so the hook owns the whole invocation. Both slots are `null`
// unless `src/domain/domain.ts` is in the bundle (see `__domainHooks` in
// ../events/events.ts).
const scheduledIn: any = entry.domain;
const hook: any = __domainHooks.callback;
if (
scheduledIn !== null &&
scheduledIn !== undefined &&
hook !== null &&
hook !== undefined
) {
__evCall(hook, [scheduledIn, entry.fn, entry.args]);
continue;
}
try {
__evCall(entry.fn, entry.args);
} catch (error) {
__processReportUncaught(error);
}
}
}
function __processNextTick(fn: any, ...args: any[]): void {
if (!__evIsFn(fn)) {
throw new ERR_INVALID_ARG_TYPE("callback", "function", fn);
}
const passed: any[] = [];
if (args !== undefined && args !== null) {
const count = Number(args.length);
for (let i = 0; i < count; i++) passed.push(args[i]);
}
// `domain` is the active domain at *schedule* time, which is what makes a
// tick re-enter it when it runs; `null` whenever `node:domain` is not in the
// bundle.
const entry: any = { args: passed, domain: __domainHooks.active, fn: fn };
__tickQueue.items.push(entry);
if (!__tickQueue.scheduled) {
__tickQueue.scheduled = true;
queueMicrotask(__drainTicks);
}
}
// ---------------------------------------------------------------------------
// Uncaught exceptions
// ---------------------------------------------------------------------------
//
// The engine has no "uncaught exception" hook: an error that escapes the main
// script ends the program before any JavaScript sees it. What *can* be routed
// here is every throw this library itself catches on a callback boundary — a
// `process.nextTick` callback and a timer callback — which is where Node's own
// corpus raises them. `src/timers/timers.ts` delegates to this function for
// exactly that reason, so the capture callback and the monitor event behave the
// same whichever boundary the throw crossed.
//
// `setUncaughtExceptionCaptureCallback` is therefore **best effort** and
// documented as such: it sees what this library catches, not what the engine
// swallows. `test-process-exception-capture.js` and
// `…-should-abort-on-uncaught.js` throw from the top level of the test and are
// out of reach; `…-errors.js`, which only exercises the validation, is not.
const __processUncaught: any = { callback: undefined };
// Set by src/worker_threads/worker_threads.ts in a worker process: an
// unhandled exception there is reported to the parent's `Worker` as its
// `'error'` event instead of being printed, and the worker exits 1.
const __processWorkerHook: any = { target: null };
function __processReportUncaught(error: any): void {
if (Number(__processEmitter.listenerCount("uncaughtExceptionMonitor")) > 0) {
__evEmit(__processEmitter, "uncaughtExceptionMonitor", [error, "uncaughtException"]);
}
const callback: any = __processUncaught.callback;
if (callback !== undefined && callback !== null) {
__evCall(callback, [error]);
return;
}
if (Number(__processEmitter.listenerCount("uncaughtException")) > 0) {
__evEmit(__processEmitter, "uncaughtException", [error, "uncaughtException"]);
return;
}
const worker: any = __processWorkerHook.target;
if (worker !== null && worker !== undefined) {
worker.uncaught(error);
process.exit(1);
return;
}
// Unhandled: Node prints the error and exits with code 1 (after running
// 'exit' listeners). Rethrowing is not enough here — an exception that
// escapes a macrotask is printed by the engine but the run still exits 0,
// which made tests whose assertions live in a timer or observer callback
// pass spuriously. So the crash is performed explicitly.
let text = "";
try {
const stack: any = error !== null && error !== undefined ? error.stack : undefined;
text = typeof stack === "string" && stack !== "" ? stack : String(error);
} catch (ignored) {
text = "Uncaught exception";
}
host.stderrWrite(text + "\n");
// `--abort-on-uncaught-exception` turns an unhandled exception into an
// abort, with no 'exit' event. Node's Windows build ends with `_exit(134)` in
// place of SIGABRT, and 134 is a status `common.nodeProcessAborted` accepts
// on every platform, so that is the status used here.
if (__processArgvSplit.execArgv.indexOf("--abort-on-uncaught-exception") >= 0) {
host.exitProcess(134);
return;
}
process.exit(1);
}
// ---------------------------------------------------------------------------
// process.emitWarning
// ---------------------------------------------------------------------------
// The warning a string `process.emitWarning(message, ...)` becomes. Node builds
// a plain `Error` and then assigns `name`, `code` and `detail` onto it; here
// every one of the three is a **declared field**, because writing an undeclared
// key onto a typed instance through an `any` alias poisons the instance and
// every later statically typed read of its own members — `warning.name`
// included, which is what a `process.on('warning')` listener reads
// (https://github.com/UrubuCode/zun/issues/37). `name` is a getter over
// `warningName` because `name` on an `Error` subclass cannot be assigned.
class ProcessWarning extends Error {
// `code` is `any`, not `string`, and defaults to `undefined`: Node leaves a
// warning's `code` absent unless one was passed, and
// `test-util-deprecate.js` asserts `warning.code === undefined` for a
// `util.deprecate()` with no code. A `string` field would read back `""`.
code: any = undefined;
detail: any = undefined;
warningName: string = "Warning";
constructor(message: string) {
super(message);
}
get name(): string {
return this.warningName;
}
}
// `process.emitWarning(warning[, type[, code]][, ctor])`, with Node's full
// option grammar (`lib/internal/process/warning.js`):
//
// * an object second argument carries `{ type, code, detail }`;
// * a *function* second or third argument is the `ctor` stack-trace anchor,
// which this runtime has no `captureStackTrace` to honour — it is accepted
// and ignored, which is the whole of its observable contract here;
// * `type` and `code`, when present and not a function, must be strings;
// * a non-string, non-`Error` warning is `ERR_INVALID_ARG_TYPE`.
//
// `noDeprecation` and `throwDeprecation` are consulted **synchronously**, as in
// Node, so `process.noDeprecation = true` around an `emitWarning` call
// suppresses it even though the delivery itself is deferred.
function __processEmitWarning(warning: any, type?: any, code?: any, ctor?: any): void {
let resolvedType: any = type;
let resolvedCode: any = code;
let detail: any = undefined;
const _anchor: any = ctor;
if (
resolvedType !== null &&
resolvedType !== undefined &&
typeof resolvedType === "object" &&
!Array.isArray(resolvedType)
) {
resolvedCode = resolvedType.code;
if (typeof resolvedType.detail === "string") detail = resolvedType.detail;
const named: any = resolvedType.type;
resolvedType = named === undefined || named === null || named === "" ? "Warning" : named;
} else if (__evIsFn(resolvedType)) {
resolvedCode = undefined;
resolvedType = "Warning";
}
if (resolvedType !== undefined) __procValidateString(resolvedType, "type");
if (__evIsFn(resolvedCode)) {
resolvedCode = undefined;
} else if (resolvedCode !== undefined) {
__procValidateString(resolvedCode, "code");
}
let built: any = warning;
if (typeof warning === "string") {
const made = new ProcessWarning(warning);
if (resolvedType !== undefined && resolvedType !== null) {
made.warningName = String(resolvedType);
}
if (resolvedCode !== undefined && resolvedCode !== null) made.code = String(resolvedCode);
if (detail !== undefined) made.detail = detail;
built = made;
} else if (!(warning instanceof Error)) {
throw new ERR_INVALID_ARG_TYPE("warning", ["Error", "string"], warning);
}
const warningName: any = built.name;
if (warningName === "DeprecationWarning") {
if (process.noDeprecation === true) return;
if (process.throwDeprecation === true) {
__processNextTick(__processThrowWarning, built);
return;
}
}
// A warning is delivered on the next tick in Node; the tests observe it
// through `process.on('warning')`, so the same deferral is kept.
__processNextTick(__deliverWarning, built);
}
function __processThrowWarning(warning: any): void {
throw warning;
}
function __deliverWarning(warning: any): void {
if (Number(__processEmitter.listenerCount("warning")) > 0) {
__evEmit(__processEmitter, "warning", [warning]);
return;
}
const label: any = warning.name;
host.stderrWrite(
"(zun-node) " +
(typeof label === "string" && label !== "" ? label : "Warning") +
": " +
String(warning.message) +
"\n",
);
}
// ---------------------------------------------------------------------------
// Exit
// ---------------------------------------------------------------------------
// `code` is `undefined` until something sets it, which is what `process.exit()`
// with no argument and `reallyExit` both resolve through `|| 0`.
const __exitState: any = { emitted: false, code: undefined };
function __processResolvedExitCode(): number {
const code: any = __exitState.code;
if (code === undefined || code === null) return 0;
return Number(code);
}
// `process.exitCode = code`, with Node's coercion ladder: an integral numeric
// *string* becomes the number, and anything else must already be an integer.
function __processSetExitCode(code: any): void {
if (code === undefined || code === null) {
__exitState.code = undefined;
return;
}
let value: any = code;
if (typeof code === "string" && code !== "") {
const parsed: number = Number(code);
if (Number.isInteger(parsed)) value = parsed;
}
if (typeof value !== "number") {
throw new ERR_INVALID_ARG_TYPE("code", "number", value);
}
if (!Number.isInteger(value)) {
throw new ERR_OUT_OF_RANGE("code", "an integer", value);
}
__exitState.code = value;
}
// Emit `process` 'exit' exactly once, with the resolved exit code, and answer
// the code to hand the host — read *after* the listeners have run, because an
// 'exit' listener may set `process.exitCode` and Node honours that (which is
// the whole of `test-process-exit-recursive.js`).
function __processRunExit(code?: any): number {
if (code !== undefined && code !== null) __processSetExitCode(code);
if (!__exitState.emitted) {
__exitState.emitted = true;
process._exiting = true;
__evEmit(__processEmitter, "exit", [__processResolvedExitCode()]);
}
return __processResolvedExitCode();
}