wasm-rquickjs-cli 0.4.15

Tool for wrapping JavaScript modules as WebAssembly components using the QuickJS engine
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
import assert from 'node:assert';
import { webcrypto } from 'node:crypto';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import module, { createRequire } from 'node:module';
import { inspect } from 'node:util';
import vm from 'node:vm';

const require = createRequire(import.meta.url);

export const testPrivateWeakCollectionsBypassPublicPrototypes = () => {
    const privateResourceIds = globalThis.__wasm_rquickjs_resource_ids;
    assert.ok(privateResourceIds instanceof WeakMap);
    for (const method of ['delete', 'get', 'has', 'set']) {
        const descriptor = Object.getOwnPropertyDescriptor(privateResourceIds, method);
        assert.strictEqual(typeof descriptor?.value, 'function');
        assert.strictEqual(descriptor.enumerable, false);
        assert.strictEqual(descriptor.configurable, false);
        assert.strictEqual(descriptor.writable, false);
    }

    const weakMapMethods = {
        delete: WeakMap.prototype.delete,
        get: WeakMap.prototype.get,
        has: WeakMap.prototype.has,
        set: WeakMap.prototype.set,
    };
    const weakSetMethods = {
        add: WeakSet.prototype.add,
        delete: WeakSet.prototype.delete,
        has: WeakSet.prototype.has,
    };
    const prototypeCalls = [];
    const key = {};

    for (const [name, method] of Object.entries(weakMapMethods)) {
        WeakMap.prototype[name] = function (...args) {
            prototypeCalls.push(`WeakMap.${name}`);
            return Reflect.apply(method, this, args);
        };
    }
    for (const [name, method] of Object.entries(weakSetMethods)) {
        WeakSet.prototype[name] = function (...args) {
            prototypeCalls.push(`WeakSet.${name}`);
            return Reflect.apply(method, this, args);
        };
    }

    try {
        privateResourceIds.set(key, { marker: 'private-resource-id' });
        assert.strictEqual(privateResourceIds.has(key), true);
        assert.deepStrictEqual(privateResourceIds.get(key), { marker: 'private-resource-id' });

        const event = new Event('private-cache-test');
        assert.strictEqual(event.isTrusted, false);

        const decoder = new TextDecoder();
        assert.strictEqual(decoder.decode(new Uint8Array([65])), 'A');
        assert.match(inspect(new TextEncoderStream()), /TextEncoderStream/);
        assert.match(inspect(new TextDecoderStream()), /TextDecoderStream/);

        const objectPrototypeGet = Object.getOwnPropertyDescriptor(Object.prototype, 'get');
        try {
            Object.defineProperty(Object.prototype, 'get', {
                value() {},
                configurable: true,
            });
            const cyclicActual = {};
            const cyclicExpected = {};
            cyclicActual.self = cyclicActual;
            cyclicExpected.self = cyclicExpected;
            assert.partialDeepStrictEqual(cyclicActual, cyclicExpected);
        } finally {
            if (objectPrototypeGet) {
                Object.defineProperty(Object.prototype, 'get', objectPrototypeGet);
            } else {
                delete Object.prototype.get;
            }
        }

        const url = new URL('https://example.com/?value=1');
        assert.strictEqual(url.searchParams.get('value'), '1');

        assert.match(new Error('private-error-cache').stack, /^Error: private-error-cache(?:\n|$)/);

        const context = vm.createContext({ value: 21 });
        assert.strictEqual(new vm.Script('value * 2').runInContext(context), 42);

        assert.strictEqual(webcrypto.subtle.constructor.name, 'SubtleCrypto');
        webcrypto.getRandomValues(new Uint8Array(1));

        globalThis.__wasm_rquickjs_ignore_unhandled_rejection(Promise.resolve());

        const modulePath = '/private-weak-cache.cjs';
        fs.writeFileSync(modulePath, 'module.exports = 42;');
        try {
            assert.strictEqual(require(modulePath), 42);
        } finally {
            delete require.cache[modulePath];
            fs.unlinkSync(modulePath);
        }
    } finally {
        Object.assign(WeakMap.prototype, weakMapMethods);
        Object.assign(WeakSet.prototype, weakSetMethods);
    }

    assert.deepStrictEqual(prototypeCalls, []);
    assert.doesNotMatch(
        inspect(privateResourceIds, { showHidden: true }),
        /private-resource-id/,
    );
    assert.strictEqual(privateResourceIds.delete(key), true);
    return true;
};

// Test 1: Error.captureStackTrace exists as a function
export const testCaptureStackTraceExists = () => {
    try {
        assert.strictEqual(typeof Error.captureStackTrace, 'function');
        assert.strictEqual(typeof Error.prepareStackTrace, 'function');
        assert.strictEqual(typeof Error.stackTraceLimit, 'number');
        return true;
    } catch (e) {
        console.error('testCaptureStackTraceExists FAIL:', e.message);
        return false;
    }
};

export const benchmarkErrorStack = (path, iterations) => {
    function throwAtDepth(depth, valueFactory) {
        if (depth === 0) throw valueFactory();
        return throwAtDepth(depth - 1, valueFactory);
    }

    let checksum = 0;
    if (path === 'construction') {
        for (let index = 0; index < iterations; index++) {
            checksum += new Error('benchmark').message.length;
        }
    } else if (path === 'first-read') {
        for (let index = 0; index < iterations; index++) {
            checksum += new Error('benchmark').stack.length;
        }
    } else if (path === 'repeated-read') {
        const error = new Error('benchmark');
        error.stack;
        for (let index = 0; index < iterations; index++) {
            checksum += error.stack.length;
        }
    } else if (path === 'throw-catch') {
        for (let index = 0; index < iterations; index++) {
            try {
                throwAtDepth(4, () => new Error('benchmark'));
            } catch (error) {
                checksum += error.message.length;
            }
        }
    } else if (path === 'throw-plain') {
        for (let index = 0; index < iterations; index++) {
            try {
                throwAtDepth(4, () => ({ message: 'benchmark' }));
            } catch (error) {
                checksum += error.message.length;
            }
        }
    } else if (path === 'capture-first-read') {
        for (let index = 0; index < iterations; index++) {
            const target = {};
            Error.captureStackTrace(target);
            checksum += target.stack.length;
        }
    } else if (path === 'custom-first-read') {
        const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
        try {
            Error.prepareStackTrace = (_error, callSites) => `custom:${callSites.length}`;
            for (let index = 0; index < iterations; index++) {
                checksum += new Error('benchmark').stack.length;
            }
        } finally {
            if (descriptor) Object.defineProperty(Error, 'prepareStackTrace', descriptor);
            else delete Error.prepareStackTrace;
        }
    } else {
        throw new RangeError(`unknown Error stack benchmark path: ${path}`);
    }
    return checksum >>> 0;
};

async function checkPreparedStackCacheLifetime(customStack) {
    const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
    let hookCalls = 0;
    try {
        assert.strictEqual(typeof globalThis.gc, 'function');
        if (customStack) {
            Error.prepareStackTrace = error => {
                hookCalls++;
                // Exercise the weak-key/value-to-key cycle as well as strings.
                return { error, message: error.message };
            };
        }
        const held = Array.from({ length: 8 }, (_, i) => new Error(`held-${i}`));
        const heldStacks = held.map(error => error.stack);
        const unreadHeld = customStack
            ? []
            : Array.from({ length: 8 }, (_, i) => new Error(`unread-held-${i}`));
        function discardedErrors() {
            return Array.from({ length: 64 }, (_, index) => {
                const error = new Error('discarded');
                error.self = error;
                if ((index & 1) === 0) void error.stack;
                return new WeakRef(error);
            });
        }
        function discardedPlainCycles() {
            return Array.from({ length: 64 }, () => {
                const object = {};
                object.self = object;
                return new WeakRef(object);
            });
        }
        function discardedPublicWeakEntries() {
            const refs = [];
            for (let i = 0; i < 32; i++) {
                const mapKey = { marker: `public-map-key-${i}` };
                const mapValue = { mapKey };
                const setValue = { marker: `public-set-value-${i}` };
                setValue.self = setValue;
                publicWeakMap.set(mapKey, mapValue);
                publicWeakSet.add(setValue);
                refs.push(new WeakRef(mapKey), new WeakRef(setValue));
            }
            assert.match(inspect(publicWeakMap, { showHidden: true }), /public-map-key/);
            assert.match(inspect(publicWeakSet, { showHidden: true }), /public-set-value/);
            return refs;
        }
        const publicWeakMap = new WeakMap();
        const publicWeakSet = new WeakSet();
        const liveMapKey = { marker: 'live-map-key' };
        const readdedMapKey = { marker: 'readded-map-key' };
        const currentMapValue = { marker: 'current-map-value' };
        const currentReaddedMapValue = { marker: 'current-readded-map-value' };
        const liveSetValue = { marker: 'live-set-value' };
        const readdedSetValue = { marker: 'readded-set-value' };
        publicWeakMap.set(liveMapKey, { marker: 'stale-map-value' });
        publicWeakMap.set(liveMapKey, currentMapValue);
        publicWeakMap.set(readdedMapKey, { marker: 'stale-readded-map-value' });
        publicWeakMap.delete(readdedMapKey);
        publicWeakMap.set(readdedMapKey, currentReaddedMapValue);
        publicWeakSet.add(liveSetValue);
        publicWeakSet.add(liveSetValue);
        publicWeakSet.add(readdedSetValue);
        publicWeakSet.delete(readdedSetValue);
        publicWeakSet.add(readdedSetValue);
        const errors = discardedErrors();
        const plain = discardedPlainCycles();
        const publicWeakEntries = discardedPublicWeakEntries();
        const callsBeforeGc = hookCalls;
        const tick = () => new Promise(resolve => setTimeout(resolve, 0));
        // End the allocation job before collecting. The runtime defers its
        // native collector to a timer, keeping it off async-generator stacks.
        await tick();
        for (let i = 0; i < 3; i++) {
            globalThis.gc();
            await tick();
            await tick();
        }
        assert.strictEqual(plain.filter(ref => ref.deref() === undefined).length, 64,
            'GC positive control must collect plain cycles');
        assert.strictEqual(errors.filter(ref => ref.deref() === undefined).length, 64,
            customStack
                ? 'custom prepared stack cycles must remain collectable'
                : 'private prepared-stack cache must not retain discarded errors');
        assert.strictEqual(publicWeakEntries.filter(ref => ref.deref() === undefined).length, 64,
            'inspection bookkeeping must not retain public weak entries');
        assert.strictEqual(publicWeakMap.get(liveMapKey), currentMapValue);
        assert.strictEqual(publicWeakMap.get(readdedMapKey), currentReaddedMapValue);
        assert.strictEqual(publicWeakSet.has(liveSetValue), true);
        assert.strictEqual(publicWeakSet.has(readdedSetValue), true);
        const inspectedWeakMap = inspect(publicWeakMap, { showHidden: true });
        const inspectedWeakSet = inspect(publicWeakSet, { showHidden: true });
        assert.doesNotMatch(inspectedWeakMap, /public-map-key/);
        assert.doesNotMatch(inspectedWeakSet, /public-set-value/);
        assert.match(inspectedWeakMap, /current-map-value/);
        assert.match(inspectedWeakMap, /current-readded-map-value/);
        assert.doesNotMatch(inspectedWeakMap, /stale-map-value/);
        assert.doesNotMatch(inspectedWeakMap, /stale-readded-map-value/);
        assert.strictEqual(inspectedWeakMap.match(/live-map-key/g)?.length, 1);
        assert.strictEqual(inspectedWeakMap.match(/readded-map-key/g)?.length, 1);
        assert.strictEqual(inspectedWeakSet.match(/live-set-value/g)?.length, 1);
        assert.strictEqual(inspectedWeakSet.match(/readded-set-value/g)?.length, 1);
        for (let i = 0; i < held.length; i++) {
            assert.strictEqual(held[i].stack, heldStacks[i]);
            if (customStack) assert.strictEqual(held[i].stack.error, held[i]);
            else assert(held[i].stack.includes(`held-${i}`));
        }
        for (let i = 0; i < unreadHeld.length; i++) {
            unreadHeld[i].name = 404;
            assert.match(inspect(unreadHeld[i]),
                new RegExp(`^404 \\[Error\\]: unread-held-${i}(?:\\n|$)`));
        }
        assert.strictEqual(hookCalls, callsBeforeGc, 'held stacks remain cached across GC');
        return true;
    } finally {
        if (descriptor) Object.defineProperty(Error, 'prepareStackTrace', descriptor);
        else delete Error.prepareStackTrace;
    }
}

export async function testPreparedStackCacheDoesNotRetainErrors() {
    return await checkPreparedStackCacheLifetime(false);
}

export async function testPreparedStackCacheDoesNotRetainCustomCycles() {
    return await checkPreparedStackCacheLifetime(true);
}

// Test 2: Basic Error.captureStackTrace usage — sets .stack on target
export const testCaptureStackTraceBasic = () => {
    try {
        const obj = {};
        Error.captureStackTrace(obj);
        assert.strictEqual(typeof obj.stack, 'string');
        assert(obj.stack.length > 0, 'stack should be non-empty');
        assert.throws(
            () => Error.captureStackTrace(Object.freeze({})),
            TypeError,
        );
        const existingStack = Object.preventExtensions(Object.defineProperty({}, 'stack', {
            value: 'existing',
            writable: true,
            configurable: true,
        }));
        assert.throws(() => Error.captureStackTrace(existingStack), TypeError);
        assert.throws(
            () => Error.captureStackTrace(Object.preventExtensions(new Error('fixed'))),
            TypeError,
        );
        return true;
    } catch (e) {
        console.error('testCaptureStackTraceBasic FAIL:', e.message);
        return false;
    }
};

// Test 3: Error.prepareStackTrace receives CallSite objects
export const testPrepareStackTrace = () => {
    try {
        let receivedCallSites = null;
        const origPrepare = Error.prepareStackTrace;

        Error.prepareStackTrace = function (error, callSites) {
            receivedCallSites = callSites;
            return callSites;
        };

        const obj = {};
        Error.captureStackTrace(obj);
        // Access .stack to trigger prepareStackTrace
        const stack = obj.stack;

        Error.prepareStackTrace = origPrepare;

        assert(Array.isArray(receivedCallSites), 'callSites should be an array');
        assert(receivedCallSites.length > 0, 'callSites should be non-empty');

        // Each call site should have V8-compatible methods
        const site = receivedCallSites[0];
        assert.strictEqual(typeof site.getFileName, 'function');
        assert.strictEqual(typeof site.getLineNumber, 'function');
        assert.strictEqual(typeof site.getColumnNumber, 'function');
        assert.strictEqual(typeof site.getFunctionName, 'function');

        return true;
    } catch (e) {
        console.error('testPrepareStackTrace FAIL:', e.message);
        return false;
    }
};

// Test 4: CallSite methods return correct types
export const testCallSiteMethods = () => {
    try {
        let callSites = null;
        const origPrepare = Error.prepareStackTrace;

        Error.prepareStackTrace = function (error, sites) {
            // Only capture the CallSites from our captureStackTrace call,
            // not from internal Error construction in the ErrorShim.
            if (callSites === null) {
                callSites = sites;
            }
            return 'custom-stack';
        };

        const obj = {};
        Error.captureStackTrace(obj);
        void obj.stack;

        Error.prepareStackTrace = origPrepare;

        assert(Array.isArray(callSites), 'callSites should be an array');
        assert(callSites.length > 0, 'callSites should be non-empty');

        const site = callSites[0];

        // Check all critical methods
        const methods = [
            'getThis', 'getTypeName', 'getFunction', 'getFunctionName',
            'getMethodName', 'getFileName', 'getLineNumber', 'getColumnNumber',
            'getEvalOrigin', 'isToplevel', 'isEval', 'isNative', 'isConstructor',
            'isAsync', 'isPromiseAll', 'getPromiseIndex', 'getScriptNameOrSourceURL',
            'toString'
        ];

        for (const m of methods) {
            assert.strictEqual(typeof site[m], 'function', `CallSite.${m} should be a function`);
        }

        // Verify return types
        assert(site.getFileName() === null || typeof site.getFileName() === 'string');
        assert.strictEqual(typeof site.getLineNumber(), 'number');
        assert.strictEqual(typeof site.getColumnNumber(), 'number');
        assert.strictEqual(typeof site.isEval(), 'boolean');
        assert.strictEqual(typeof site.isNative(), 'boolean');
        assert.strictEqual(typeof site.isConstructor(), 'boolean');
        assert.strictEqual(typeof site.isToplevel(), 'boolean');
        assert.strictEqual(typeof site.toString(), 'string');

        return true;
    } catch (e) {
        console.error('testCallSiteMethods FAIL:', e.message);
        return false;
    }
};

export const testLatePrepareStackTrace = () => {
    const originalPrepare = Error.prepareStackTrace;
    try {
        Error.prepareStackTrace = undefined;
        const lateTarget = {};
        Error.captureStackTrace(lateTarget);
        Error.prepareStackTrace = () => 'late-prepare';
        assert.strictEqual(lateTarget.stack, 'late-prepare');

        Error.prepareStackTrace = undefined;
        const lateError = new Error('late-error');
        let ordinaryCalls = 0;
        Error.prepareStackTrace = function(error) {
            ordinaryCalls++;
            assert.strictEqual(this, Error);
            return `late:${error.message}`;
        };
        assert.strictEqual(ordinaryCalls, 0);
        assert.strictEqual(lateError.stack, 'late:late-error');
        assert.strictEqual(ordinaryCalls, 1);

        let recursiveCalls = 0;
        Error.prepareStackTrace = error => {
            recursiveCalls++;
            return error.stack;
        };
        assert.match(new Error('recursive').stack, /^Error: recursive(?:\n|$)/);
        assert.strictEqual(recursiveCalls, 1);

        let crossErrorCalls = 0;
        let nestedError;
        Error.prepareStackTrace = error => {
            crossErrorCalls++;
            if (error.message === 'outer') {
                nestedError = new Error('inner');
                return `${nestedError.stack}!`;
            }
            return `unexpected:${error.message}`;
        };
        const crossErrorStack = new Error('outer').stack;
        assert.match(crossErrorStack, /^Error: inner(?:\n|$)/);
        assert.match(crossErrorStack, /!$/);
        assert.strictEqual(crossErrorCalls, 1);
        assert.strictEqual(nestedError.stack, crossErrorStack.slice(0, -1));

        const intrinsicError = Error;
        const replacementTarget = new intrinsicError('replacement-target');
        function ReplacementError() {}
        ReplacementError.prepareStackTrace = () => 'replacement-prepare';
        globalThis.Error = ReplacementError;
        try {
            assert.strictEqual(replacementTarget.stack, 'replacement-prepare');
        } finally {
            globalThis.Error = intrinsicError;
        }

        Error.prepareStackTrace = () => 'intrinsic-fallback';
        const fallbackTarget = new Error('fallback-target');
        globalThis.Error = function ReplacementWithoutHook() {};
        try {
            assert.strictEqual(fallbackTarget.stack, 'intrinsic-fallback');
        } finally {
            globalThis.Error = intrinsicError;
        }

        Error.prepareStackTrace = error => {
            error.stack = 'assigned-in-hook';
            return error.stack;
        };
        assert.strictEqual(new Error('assigned').stack, 'assigned-in-hook');

        Error.prepareStackTrace = () => 'capture-time-prepare';
        const removedTarget = {};
        Error.captureStackTrace(removedTarget);
        Error.prepareStackTrace = undefined;
        assert.strictEqual(typeof removedTarget.stack, 'string');
        assert.notStrictEqual(removedTarget.stack, 'capture-time-prepare');
        return true;
    } catch (e) {
        console.error('testLatePrepareStackTrace FAIL:', e.message);
        return false;
    } finally {
        Error.prepareStackTrace = originalPrepare;
    }
};

export const testDefaultErrorStackHeaders = () => {
    const originalPrepare = Error.prepareStackTrace;
    try {
        Error.prepareStackTrace = undefined;
        assert.match(new Error('base').stack, /^Error: base(?:\n|$)/);
        assert.match(new TypeError('native').stack, /^TypeError: native(?:\n|$)/);
        assert.match(new Error().stack, /^Error(?:\n|$)/);
        class CustomError extends Error {}
        CustomError.prototype.name = 'CustomError';
        assert.match(new CustomError('custom').stack, /^CustomError: custom(?:\n|$)/);
        class EmptyNameError extends Error {}
        EmptyNameError.prototype.name = '';
        assert.match(new EmptyNameError('message-only').stack, /^message-only(?:\n|$)/);
        const originalToString = Error.prototype.toString;
        Error.prototype.toString = () => 'POISON';
        const protectedHeader = new Error('protected').stack;
        Error.prototype.toString = originalToString;
        assert.match(protectedHeader, /^Error: protected(?:\n|$)/);
        function captureNamedFrame() {
            return new Error('named-frame').stack;
        }
        assert.match(captureNamedFrame().split('\n')[1], /^\s*at captureNamedFrame \(.+:\d+:\d+\)$/);
        const originalObjectToString = Object.prototype.toString;
        let protectedCallSiteStack;
        try {
            Object.prototype.toString = () => 'FAKE';
            protectedCallSiteStack = new Error('protected-call-site').stack;
        } finally {
            Object.prototype.toString = originalObjectToString;
        }
        assert.doesNotMatch(protectedCallSiteStack, /FAKE/);
        assert.match(protectedCallSiteStack.split('\n')[1], /^\s*at .+:\d+:\d+/);
        return true;
    } catch (e) {
        console.error('testDefaultErrorStackHeaders FAIL:', e.message);
        return false;
    } finally {
        Error.prepareStackTrace = originalPrepare;
    }
};

export const testErrorInspectUsesCurrentName = () => {
    try {
        const error = new RangeError('foo');
        error.name = 404;
        assert.match(error.stack, /^404: foo(?:\n|$)/);
        assert.match(inspect(error), /^404 \[RangeError\]: foo(?:\n|$)/);

        const readBeforeRename = new RangeError('fixed');
        const unreadDescriptor = Object.getOwnPropertyDescriptor(readBeforeRename, 'stack');
        assert.strictEqual(typeof unreadDescriptor.get, 'function');
        assert.strictEqual(unreadDescriptor.enumerable, false);
        assert.strictEqual(unreadDescriptor.configurable, true);
        assert.match(readBeforeRename.stack, /^RangeError: fixed(?:\n|$)/);
        const materializedDescriptor = Object.getOwnPropertyDescriptor(readBeforeRename, 'stack');
        assert.strictEqual(materializedDescriptor.get, unreadDescriptor.get);
        assert.strictEqual(materializedDescriptor.set, unreadDescriptor.set);
        assert.strictEqual('value' in materializedDescriptor, false);
        readBeforeRename.name = 404;
        assert.match(readBeforeRename.stack, /^RangeError: fixed(?:\n|$)/);
        assert.match(inspect(readBeforeRename), /^RangeError: fixed(?:\n|$)/);

        const messageBeforeRead = new Error('before');
        messageBeforeRead.message = 'after';
        assert.match(messageBeforeRead.stack, /^Error: after(?:\n|$)/);
        const messageAfterRead = new Error('before');
        assert.match(messageAfterRead.stack, /^Error: before(?:\n|$)/);
        messageAfterRead.message = 'after';
        assert.match(messageAfterRead.stack, /^Error: before(?:\n|$)/);

        const frameLikeMessage = new Error('before\n    at message');
        frameLikeMessage.message = 'after\n    at message';
        assert.match(frameLikeMessage.stack, /^Error: after\n    at message\n    at /);

        const internalFrameMessage = new Error('before\n    at construct (native)');
        internalFrameMessage.message = 'after\n    at construct (native)';
        assert.match(
            internalFrameMessage.stack,
            /^Error: after\n    at construct \(native\)\n    at /,
        );

        const inheritedBase = new Error('inherited');
        const inherited = Object.create(inheritedBase);
        assert.strictEqual(inherited.stack, inheritedBase.stack);
        assert.strictEqual(Object.hasOwn(inherited, 'stack'), false);
        inherited.stack = 'child-manual';
        assert.strictEqual(inherited.stack, 'child-manual');
        assert.strictEqual(Object.hasOwn(inherited, 'stack'), false);
        assert.strictEqual(inheritedBase.stack, 'child-manual');

        const detachedStack = {};
        Object.defineProperty(detachedStack, 'stack', unreadDescriptor);
        detachedStack.stack = 'ignored';
        assert.strictEqual(detachedStack.stack, undefined);

        const unreadInheritedBase = new Error('unread-inherited');
        const unreadInherited = Object.create(unreadInheritedBase);
        unreadInherited.name = 'ChildName';
        assert.match(unreadInherited.stack, /^Error: unread-inherited(?:\n|$)/);

        function LegacyError(message) {
            this.message = message;
            this.stack = new Error(message).stack;
        }
        LegacyError.prototype = new Error('legacy-prototype');
        const firstLegacyError = new LegacyError('first-legacy');
        assert.match(firstLegacyError.stack, /^Error: first-legacy(?:\n|$)/);
        assert.strictEqual(Object.hasOwn(firstLegacyError, 'stack'), false);
        const secondLegacyError = new LegacyError('second-legacy');
        assert.match(firstLegacyError.stack, /^Error: second-legacy(?:\n|$)/);
        assert.strictEqual(secondLegacyError.stack, firstLegacyError.stack);
        assert.strictEqual(LegacyError.prototype.stack, firstLegacyError.stack);
        assert.strictEqual(Object.hasOwn(secondLegacyError, 'stack'), false);

        const originalDefineProperty = Object.defineProperty;
        try {
            Object.defineProperty = () => { throw 1; };
            const definePropertyPoisoned = new Error('old');
            definePropertyPoisoned.name = 'Renamed';
            assert.match(definePropertyPoisoned.stack, /^Renamed: old(?:\n|$)/);
        } finally {
            Object.defineProperty = originalDefineProperty;
        }

        try {
            Object.prototype.value = 'poisoned';
            const descriptorPolluted = new Error('old');
            descriptorPolluted.name = 'Renamed';
            assert.match(descriptorPolluted.stack, /^Renamed: old(?:\n|$)/);
        } finally {
            delete Object.prototype.value;
        }

        const originalFunctionCall = Function.prototype.call;
        const originalArrayIsArray = Array.isArray;
        const originalArrayJoin = Array.prototype.join;
        const originalArrayPush = Array.prototype.push;
        const originalArraySplice = Array.prototype.splice;
        const originalArrayConstructor = Array.prototype.constructor;
        const originalArrayIndexOne = Object.getOwnPropertyDescriptor(Array.prototype, '1');
        const originalRegExpExec = RegExp.prototype.exec;
        const originalStringLastIndexOf = String.prototype.lastIndexOf;
        const originalStringSlice = String.prototype.slice;
        const originalStringSplit = String.prototype.split;
        const originalParseInt = globalThis.parseInt;
        let intrinsicPoisonedStack;
        try {
            Function.prototype.call = () => { throw 1; };
            Array.isArray = () => { throw 1; };
            Array.prototype.join = () => { throw 1; };
            Array.prototype.push = () => { throw 1; };
            Array.prototype.splice = () => { throw 1; };
            Array.prototype.constructor = {
                get [Symbol.species]() { throw 1; },
            };
            Object.defineProperty(Array.prototype, '1', {
                get() { return undefined; },
                set() { throw 1; },
                configurable: true,
            });
            RegExp.prototype.exec = () => { throw 1; };
            String.prototype.lastIndexOf = () => { throw 1; };
            String.prototype.slice = () => { throw 1; };
            String.prototype.split = () => { throw 1; };
            globalThis.parseInt = () => { throw 1; };
            const intrinsicPoisoned = new Error('old');
            intrinsicPoisoned.name = 'Renamed';
            intrinsicPoisonedStack = intrinsicPoisoned.stack;
        } finally {
            Function.prototype.call = originalFunctionCall;
            Array.isArray = originalArrayIsArray;
            Array.prototype.join = originalArrayJoin;
            Array.prototype.push = originalArrayPush;
            Array.prototype.splice = originalArraySplice;
            Array.prototype.constructor = originalArrayConstructor;
            if (originalArrayIndexOne) {
                Object.defineProperty(Array.prototype, '1', originalArrayIndexOne);
            } else {
                delete Array.prototype[1];
            }
            RegExp.prototype.exec = originalRegExpExec;
            String.prototype.lastIndexOf = originalStringLastIndexOf;
            String.prototype.slice = originalStringSlice;
            String.prototype.split = originalStringSplit;
            globalThis.parseInt = originalParseInt;
        }
        assert.match(intrinsicPoisonedStack, /^Renamed: old(?:\n|$)/);

        const thrownWithStack = { stack: 'remote-stack', message: 'remote' };
        try {
            throw thrownWithStack;
        } catch (error) {
            assert.strictEqual(error.stack, 'remote-stack');
            assert.strictEqual(Object.hasOwn(error, 'stack'), true);
        }
        const thrownWithoutStack = { code: 'plain' };
        try {
            throw thrownWithoutStack;
        } catch (error) {
            assert.strictEqual(error.stack, undefined);
            assert.strictEqual(Object.hasOwn(error, 'stack'), false);
        }

        const originalStackTraceLimit = Error.stackTraceLimit;
        try {
            Error.stackTraceLimit = 0;
            const noFrames = new Error('no-frames');
            noFrames.name = 'Renamed';
            assert.strictEqual(noFrames.stack, 'Renamed: no-frames');
            noFrames.name = 'AfterRead';
            assert.strictEqual(noFrames.stack, 'Renamed: no-frames');
        } finally {
            Error.stackTraceLimit = originalStackTraceLimit;
        }

        const sealedError = new Error('sealed');
        sealedError.name = 'Initial';
        Object.seal(sealedError);
        sealedError.name = 'BeforeRead';
        const sealedStack = sealedError.stack;
        assert.match(sealedStack, /^BeforeRead: sealed(?:\n|$)/);
        sealedError.name = 'AfterRead';
        assert.strictEqual(sealedError.stack, sealedStack);

        const symbolName = new Error('symbol-name');
        symbolName.name = Symbol('invalid');
        assert.throws(() => symbolName.stack, TypeError);
        symbolName.name = 'Recovered';
        assert.match(symbolName.stack, /^Recovered: symbol-name(?:\n|$)/);

        const manualStackError = new RangeError('foo');
        manualStackError.stack = 'RangeError: foo\n    at manual (x.js:1:2)';
        manualStackError.name = 404;
        assert.strictEqual(
            inspect(manualStackError),
            'RangeError: foo\n    at manual (x.js:1:2)',
        );

        return true;
    } catch (e) {
        console.error('testErrorInspectUsesCurrentName FAIL:', e.message);
        return false;
    }
};

export const testAssertionListenerStackFrame = () => {
    const emitter = new EventEmitter();
    emitter.on('failure', assert);
    try {
        emitter.emit('failure', false);
    } catch (error) {
        return String(error.stack).split('\n')[1] || '';
    }
    return '';
};

export const testCjsCallSiteLineOffset = () => {
    const originalPrepare = Error.prepareStackTrace;
    const filename = '/v8-call-site-line-offset.cjs';
    const mapFilename = '/v8-call-site-line-offset.cjs.map';
    try {
        module.setSourceMapsSupport(true);
        Error.prepareStackTrace = (_error, sites) => sites[0];
        fs.writeFileSync(filename, [
            'function branch() {',
            "    throw Error('site');",
            '}',
            'branch();',
            '//# sourceMappingURL=v8-call-site-line-offset.cjs.map',
        ].join('\n'));
        fs.writeFileSync(mapFilename, JSON.stringify({
            version: 3,
            sources: ['v8-call-site-line-offset.ts'],
            names: [],
            mappings: 'AAAA;AACA;AACA;AACA',
        }));
        try {
            require(filename);
        } catch (error) {
            return String(error.stack.getLineNumber());
        }
        return '';
    } finally {
        delete require.cache[filename];
        Error.prepareStackTrace = originalPrepare;
    }
};

export const testPrepareStackTraceDescriptors = () => {
    try {
        const customPrepare = () => 'custom-prepare';
        Error.prepareStackTrace = customPrepare;
        Object.defineProperty(Error, 'prepareStackTrace', { enumerable: false });
        assert.strictEqual(Error.prepareStackTrace, customPrepare);
        const customPrepared = new Error('partial-descriptor');
        assert.strictEqual(customPrepared.stack, 'custom-prepare');
        const customPreparedDescriptor = Object.getOwnPropertyDescriptor(customPrepared, 'stack');
        assert.strictEqual(typeof customPreparedDescriptor.get, 'function');
        assert.strictEqual(typeof customPreparedDescriptor.set, 'function');
        assert.strictEqual('value' in customPreparedDescriptor, false);
        assert.strictEqual(customPreparedDescriptor.enumerable, false);
        assert.strictEqual(customPreparedDescriptor.configurable, true);

        let getterCalls = 0;
        Object.defineProperty(Error, 'prepareStackTrace', {
            get() {
                getterCalls++;
                return customPrepare;
            },
            configurable: true,
        });
        assert.strictEqual(getterCalls, 0);
        const accessorPrepared = new TypeError('accessor');
        assert.strictEqual(getterCalls, 0);
        assert.strictEqual(accessorPrepared.stack, 'custom-prepare');
        assert.strictEqual(getterCalls, 2);

        let undefinedPrepareCalls = 0;
        Object.defineProperty(Error, 'prepareStackTrace', {
            value: error => {
                if (error?.message === 'undefined-prepare') undefinedPrepareCalls++;
                return undefined;
            },
            writable: true,
            configurable: true,
        });
        const undefinedPrepared = new Error('undefined-prepare');
        try {
            throw 0;
        } catch {
            // QuickJS clears its current backtrace marker on every catch.
        }
        try {
            throw undefinedPrepared;
        } catch (error) {
            assert.strictEqual(error, undefinedPrepared);
        }
        assert.strictEqual(undefinedPrepared.stack, undefined);
        assert.strictEqual(undefinedPrepared.stack, undefined);
        assert.strictEqual(undefinedPrepareCalls, 1,
            'an undefined custom result must still be cached');

        let stringPrepareCalls = 0;
        Error.prepareStackTrace = error => {
            if (error?.message === 'string-prepare') stringPrepareCalls++;
            return `prepared:${error?.message}`;
        };
        const stringPrepared = new Error('string-prepare');
        const stringPreparedValue = stringPrepared.stack;
        try {
            throw 0;
        } catch {
            // QuickJS clears its current backtrace marker on every catch.
        }
        try {
            throw stringPrepared;
        } catch (error) {
            assert.strictEqual(error, stringPrepared);
        }
        assert.strictEqual(stringPrepared.stack, stringPreparedValue);
        assert.strictEqual(stringPrepareCalls, 1,
            'a non-undefined custom result must remain cached after rethrow');

        delete Error.prepareStackTrace;
        assert.match(new Error('deleted').stack, /^Error: deleted(?:\n|$)/);

        const objectPrototypeCustom = Object.getOwnPropertyDescriptor(Object.prototype, 'custom');
        try {
            Object.defineProperty(Object.prototype, 'custom', {
                value: true,
                configurable: true,
            });
            assert.match(new Error('polluted-state').stack, /^Error: polluted-state(?:\n|$)/);
        } finally {
            if (objectPrototypeCustom) {
                Object.defineProperty(Object.prototype, 'custom', objectPrototypeCustom);
            } else {
                delete Object.prototype.custom;
            }
        }

        Object.defineProperty(Error, 'prepareStackTrace', {
            value: customPrepare,
            writable: true,
            configurable: true,
        });
        Object.freeze(Error);
        const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
        assert.strictEqual(descriptor.writable, false);
        assert.strictEqual(descriptor.configurable, false);
        assert.strictEqual(new Error('frozen').stack, 'custom-prepare');
        return true;
    } catch (e) {
        console.error('testPrepareStackTraceDescriptors FAIL:', e.message);
        return false;
    }
};

// Node 22 returns undefined for both proxy reads below without invoking the
// getPrototypeOf trap. QuickJS does not expose a trap-free way for JavaScript
// to recover the private stack holder through a Proxy, so retain the exact
// engine boundary until holder lookup can move into the native layer.
export const testProxyStackHolderEngineBoundary = () => {
    const originalPrepare = Error.prepareStackTrace;
    try {
        Error.prepareStackTrace = undefined;

        const errorTarget = new Error('proxy-error');
        let errorTrapCalls = 0;
        const errorProxy = new Proxy(errorTarget, {
            getPrototypeOf(target) {
                errorTrapCalls++;
                return Reflect.getPrototypeOf(target);
            },
        });
        assert.strictEqual(errorProxy.stack, undefined);
        assert.strictEqual(errorTrapCalls, 1);

        const capturedTarget = {};
        Error.captureStackTrace(capturedTarget);
        let capturedTrapCalls = 0;
        const capturedProxy = new Proxy(capturedTarget, {
            getPrototypeOf(target) {
                capturedTrapCalls++;
                return Reflect.getPrototypeOf(target);
            },
        });
        assert.strictEqual(capturedProxy.stack, undefined);
        assert.strictEqual(capturedTrapCalls, 1);
        return true;
    } catch (e) {
        console.error('testProxyStackHolderEngineBoundary FAIL:', e.message);
        return false;
    } finally {
        Error.prepareStackTrace = originalPrepare;
    }
};

// Test 5: constructorOpt parameter strips frames
export const testConstructorOpt = () => {
    try {
        let callSites = null;
        const origPrepare = Error.prepareStackTrace;

        Error.prepareStackTrace = function (error, sites) {
            callSites = sites;
            return sites;
        };

        function MyError(message) {
            Error.captureStackTrace(this, MyError);
            this.message = message;
        }

        function callerFunction() {
            return new MyError('test');
        }

        const err = callerFunction();
        // Access .stack to trigger prepareStackTrace
        const stack = err.stack;

        Error.prepareStackTrace = origPrepare;

        assert(Array.isArray(callSites) && callSites.length > 0);

        // The first frame should NOT be MyError (it should be stripped)
        const firstFn = callSites[0].getFunctionName();
        assert.notStrictEqual(firstFn, 'MyError',
            'constructorOpt should strip frames including the constructor');

        return true;
    } catch (e) {
        console.error('testConstructorOpt FAIL:', e.message);
        return false;
    }
};

// Test 6: Error.stackTraceLimit is readable/writable
export const testStackTraceLimit = () => {
    try {
        const origLimit = Error.stackTraceLimit;

        assert.strictEqual(typeof Error.stackTraceLimit, 'number');

        Error.stackTraceLimit = 42;
        assert.strictEqual(Error.stackTraceLimit, 42);

        Error.stackTraceLimit = origLimit;
        return true;
    } catch (e) {
        console.error('testStackTraceLimit FAIL:', e.message);
        return false;
    }
};

// Test 7: The exact depd pattern — the real-world use case this fix enables
export const testDepdPattern = () => {
    try {
        // This is exactly what depd does:
        function prepareObjectStackTrace(obj, stack) {
            return stack;
        }

        function getStack() {
            var limit = Error.stackTraceLimit;
            var obj = {};
            var prep = Error.prepareStackTrace;

            Error.prepareStackTrace = prepareObjectStackTrace;
            Error.stackTraceLimit = Math.max(10, limit);

            Error.captureStackTrace(obj);

            var stack = obj.stack.slice(1);

            Error.prepareStackTrace = prep;
            Error.stackTraceLimit = limit;

            return stack;
        }

        function callSiteLocation(callSite) {
            var file = callSite.getFileName() || '<anonymous>';
            var line = callSite.getLineNumber();
            var colm = callSite.getColumnNumber();

            var site = [file, line, colm];
            site.callSite = callSite;
            site.name = callSite.getFunctionName();

            return site;
        }

        function depd(namespace) {
            var stack = getStack();
            var site = callSiteLocation(stack[1]);
            var file = site[0];
            return { file, namespace };
        }

        // This call should NOT throw — it's the exact pattern that was failing
        const result = depd('test-namespace');
        assert.strictEqual(result.namespace, 'test-namespace');
        assert.strictEqual(typeof result.file, 'string');

        return true;
    } catch (e) {
        console.error('testDepdPattern FAIL:', e.message);
        return false;
    }
};