js-confuser-vm 0.0.2 → 0.0.4

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 (39) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/LICENSE +21 -21
  3. package/README.MD +370 -190
  4. package/babel-plugin-inline-runtime.cjs +34 -0
  5. package/babel.config.json +23 -24
  6. package/index.ts +34 -28
  7. package/jest-strip-types.js +10 -10
  8. package/jest.config.js +35 -18
  9. package/package.json +50 -48
  10. package/src/build-runtime.ts +57 -0
  11. package/src/compiler.ts +2069 -1677
  12. package/src/index.ts +14 -13
  13. package/src/minify.ts +21 -21
  14. package/src/options.ts +14 -10
  15. package/src/runtime.ts +771 -645
  16. package/src/transforms/bytecode/macroOpcodes.ts +177 -0
  17. package/src/transforms/bytecode/resolveContants.ts +62 -0
  18. package/src/transforms/bytecode/resolveLabels.ts +107 -0
  19. package/src/transforms/bytecode/selfModifying.ts +121 -0
  20. package/src/transforms/bytecode/specializedOpcodes.ts +118 -0
  21. package/src/transforms/runtime/macroOpcodes.ts +111 -0
  22. package/src/transforms/runtime/minify.ts +1 -0
  23. package/src/transforms/runtime/shuffleOpcodes.ts +24 -0
  24. package/src/transforms/runtime/specializedOpcodes.ts +146 -0
  25. package/src/transforms/utils/op-utils.ts +26 -0
  26. package/src/{random.ts → transforms/utils/random-utils.ts} +31 -31
  27. package/src/types.ts +33 -0
  28. package/src/utilts.ts +3 -3
  29. package/tsconfig.json +12 -12
  30. package/dist/compiler.js +0 -1505
  31. package/dist/index.js +0 -9
  32. package/dist/minify.js +0 -18
  33. package/dist/minify_empty_externs.js +0 -4
  34. package/dist/options.js +0 -1
  35. package/dist/random.js +0 -27
  36. package/dist/runtime.js +0 -620
  37. package/dist/runtimeObf.js +0 -36
  38. package/dist/utilts.js +0 -3
  39. package/src/runtimeObf.ts +0 -48
package/src/runtime.ts CHANGED
@@ -1,645 +1,771 @@
1
- import { OP_ORIGINAL as OP } from "./compiler.ts";
2
- const BYTECODE = [];
3
- const MAIN_START_PC = 0;
4
- const CONSTANTS = [];
5
- const ENCODE_BYTECODE = false;
6
- const TIMING_CHECKS = false;
7
- // The text above is not included in the compiled output - for type intellisense only
8
- // @START
9
-
10
- function decodeBytecode(s) {
11
- if (!ENCODE_BYTECODE) return s;
12
-
13
- var b =
14
- typeof Buffer !== "undefined"
15
- ? Buffer.from(s, "base64")
16
- : Uint8Array.from(atob(s), function (c) {
17
- return c.charCodeAt(0);
18
- });
19
- var r = new Int32Array(b.length / 4);
20
- for (var i = 0; i < r.length; i++)
21
- r[i] =
22
- b[i * 4] |
23
- (b[i * 4 + 1] << 8) |
24
- (b[i * 4 + 2] << 16) |
25
- (b[i * 4 + 3] << 24);
26
- return r;
27
- }
28
-
29
- // Closure symbol
30
- // Used to tag shell functions so the VM can fast-path back to the
31
- // inner Closure instead of going through a sub-VM on internal calls.
32
- var CLOSURE_SYM = Symbol(); // Nameless for obfuscation
33
-
34
- // Upvalue
35
- // While the outer frame is alive: reads/writes go to frame.locals[slot].
36
- // After the outer frame returns (closed): reads/writes hit this.value.
37
- function Upvalue(frame, slot) {
38
- this.frame = frame;
39
- this.slot = slot;
40
- this._closed = false;
41
- this._value = undefined;
42
- }
43
- Upvalue.prototype.read = function () {
44
- return this._closed ? this._value : this.frame.locals[this.slot];
45
- };
46
- Upvalue.prototype.write = function (v) {
47
- if (this._closed) this._value = v;
48
- else this.frame.locals[this.slot] = v;
49
- };
50
- Upvalue.prototype.close = function () {
51
- this._value = this.frame.locals[this.slot];
52
- this._closed = true;
53
- };
54
-
55
- // Closure & Frame
56
- function Closure(fn) {
57
- this.fn = fn;
58
- this.upvalues = [];
59
- this.prototype = {}; // <- default prototype object for \`new\`
60
- }
61
-
62
- function Frame(closure, returnPc, parent, thisVal?) {
63
- this.closure = closure;
64
- this.locals = new Array(closure.fn.localCount).fill(undefined);
65
- this.pc = closure.fn.startPc; // <- initialize from fn descriptor
66
- this.returnPc = returnPc; // pc to resume in parent frame after RETURN
67
- this.parent = parent;
68
- this.thisVal = thisVal !== undefined ? thisVal : undefined;
69
- this._newObj = null; // <- set by NEW so RETURN can see it
70
- }
71
-
72
- // VM
73
- function VM(bytecode, mainStartPc, constants, globals) {
74
- this.bytecode = bytecode;
75
- this.constants = constants;
76
- this.globals = globals;
77
- this._stack = [];
78
- this.frameStack = [];
79
- this.openUpvalues = []; // all currently open Upvalue objects across all frames
80
-
81
- var mainFn = {
82
- paramCount: 0,
83
- localCount: 0,
84
- startPc: mainStartPc, // <- where main begins
85
- };
86
- this.currentFrame = new Frame(new Closure(mainFn), null, null);
87
- }
88
-
89
- VM.prototype._push = function (v) {
90
- this._stack.push(v);
91
- };
92
- VM.prototype._pop = function () {
93
- return this._stack.pop();
94
- };
95
- VM.prototype.peek = function () {
96
- return this._stack[this._stack.length - 1];
97
- };
98
-
99
- VM.prototype.captureUpvalue = function (frame, slot) {
100
- // Reuse existing open upvalue for this frame+slot if one exists.
101
- // This is what makes two closures share the same mutable cell.
102
- for (var i = 0; i < this.openUpvalues.length; i++) {
103
- var uv = this.openUpvalues[i];
104
- if (uv.frame === frame && uv.slot === slot) return uv;
105
- }
106
- var uv = new Upvalue(frame, slot);
107
- this.openUpvalues.push(uv);
108
- return uv;
109
- };
110
-
111
- VM.prototype.closeUpvaluesFor = function (frame) {
112
- // Called on RETURN - close every upvalue that was pointing into this frame.
113
- // After this, closures that captured from the frame read from upvalue.value.
114
- this.openUpvalues = this.openUpvalues.filter(function (uv) {
115
- if (uv.frame === frame) {
116
- uv.close();
117
- return false;
118
- }
119
- return true;
120
- });
121
- };
122
-
123
- VM.prototype.run = function () {
124
- var now = () => {
125
- return performance.now();
126
- };
127
-
128
- var t = now();
129
-
130
- while (true) {
131
- var frame = this.currentFrame;
132
- var bc = this.bytecode;
133
- if (frame.pc >= bc.length) break;
134
-
135
- var op, operand;
136
- var word = bc[frame.pc++];
137
-
138
- if (ENCODE_BYTECODE) {
139
- op = word & 0xff;
140
- operand = word >>> 8;
141
- } else {
142
- op = word[0];
143
- operand = word[1];
144
- }
145
-
146
- // console.log(frame.pc - 1, op, operand);
147
-
148
- // Debugging protection
149
- if (TIMING_CHECKS) {
150
- var t2 = now();
151
- var isTamper = t2 - t > 1000;
152
- t = t2;
153
- if (isTamper) {
154
- op = OP.POP;
155
- }
156
- }
157
-
158
- /* @SWITCH */
159
- switch (op) {
160
- case OP.LOAD_CONST:
161
- this._push(this.constants[operand]);
162
- break;
163
-
164
- case OP.LOAD_LOCAL:
165
- this._push(frame.locals[operand]);
166
- break;
167
-
168
- case OP.STORE_LOCAL:
169
- frame.locals[operand] = this._pop();
170
- break;
171
-
172
- case OP.LOAD_GLOBAL:
173
- this._push(this.globals[this.constants[operand]]);
174
- break;
175
-
176
- case OP.STORE_GLOBAL:
177
- this.globals[this.constants[operand]] = this._pop();
178
- break;
179
-
180
- case OP.GET_PROP: {
181
- // Stack: [..., obj, key] -> [..., obj, obj[key]]
182
- // obj is PEEKED (not popped) - CALL_METHOD needs it as receiver
183
- var key = this._pop();
184
- var obj = this.peek();
185
- this._push(obj[key]);
186
- break;
187
- }
188
-
189
- case OP.ADD: {
190
- var b = this._pop();
191
- this._push(this._pop() + b);
192
- break;
193
- }
194
- case OP.SUB: {
195
- var b = this._pop();
196
- this._push(this._pop() - b);
197
- break;
198
- }
199
- case OP.MUL: {
200
- var b = this._pop();
201
- this._push(this._pop() * b);
202
- break;
203
- }
204
- case OP.DIV: {
205
- var b = this._pop();
206
- this._push(this._pop() / b);
207
- break;
208
- }
209
- case OP.MOD: {
210
- var b = this._pop();
211
- this._push(this._pop() % b);
212
- break;
213
- }
214
- case OP.BAND: {
215
- var b = this._pop();
216
- this._push(this._pop() & b);
217
- break;
218
- }
219
- case OP.BOR: {
220
- var b = this._pop();
221
- this._push(this._pop() | b);
222
- break;
223
- }
224
- case OP.BXOR: {
225
- var b = this._pop();
226
- this._push(this._pop() ^ b);
227
- break;
228
- }
229
- case OP.SHL: {
230
- var b = this._pop();
231
- this._push(this._pop() << b);
232
- break;
233
- }
234
- case OP.SHR: {
235
- var b = this._pop();
236
- this._push(this._pop() >> b);
237
- break;
238
- }
239
- case OP.USHR: {
240
- var b = this._pop();
241
- this._push(this._pop() >>> b);
242
- break;
243
- }
244
-
245
- case OP.LT: {
246
- var b = this._pop();
247
- this._push(this._pop() < b);
248
- break;
249
- }
250
- case OP.GT: {
251
- var b = this._pop();
252
- this._push(this._pop() > b);
253
- break;
254
- }
255
- case OP.EQ: {
256
- var b = this._pop();
257
- this._push(this._pop() === b);
258
- break;
259
- }
260
-
261
- case OP.LTE: {
262
- var b = this._pop();
263
- this._push(this._pop() <= b);
264
- break;
265
- }
266
- case OP.GTE: {
267
- var b = this._pop();
268
- this._push(this._pop() >= b);
269
- break;
270
- }
271
- case OP.NEQ: {
272
- var b = this._pop();
273
- this._push(this._pop() !== b);
274
- break;
275
- }
276
- case OP.LOOSE_EQ: {
277
- var b = this._pop();
278
- this._push(this._pop() == b);
279
- break;
280
- }
281
- case OP.LOOSE_NEQ: {
282
- var b = this._pop();
283
- this._push(this._pop() != b);
284
- break;
285
- }
286
-
287
- case OP.IN: {
288
- var b = this._pop();
289
- this._push(this._pop() in b);
290
- break;
291
- }
292
-
293
- case OP.INSTANCEOF: {
294
- var ctor = this._pop();
295
- var obj = this._pop();
296
- if (typeof ctor === "function") {
297
- // Native constructor (e.g. Array, Date) - native instanceof is fine
298
- this._push(obj instanceof ctor);
299
- } else {
300
- // VM Closure - ctor.prototype was set by MAKE_CLOSURE / user assignment.
301
- // Walk obj's prototype chain looking for identity with ctor.prototype.
302
- var proto = ctor.prototype; // the .prototype property on the Closure
303
- var target = Object.getPrototypeOf(obj);
304
- var result = false;
305
- while (target !== null) {
306
- if (target === proto) {
307
- result = true;
308
- break;
309
- }
310
- target = Object.getPrototypeOf(target);
311
- }
312
- this._push(result);
313
- }
314
- break;
315
- }
316
-
317
- case OP.UNARY_NEG:
318
- this._push(-this._pop());
319
- break;
320
- case OP.UNARY_POS:
321
- this._push(this._pop());
322
- break;
323
- case OP.UNARY_NOT:
324
- this._push(!this._pop());
325
- break;
326
- case OP.UNARY_BITNOT:
327
- this._push(~this._pop());
328
- break;
329
- case OP.TYPEOF:
330
- this._push(typeof this._pop());
331
- break;
332
- case OP.VOID:
333
- this._pop();
334
- this._push(undefined);
335
- break;
336
-
337
- case OP.TYPEOF_SAFE: {
338
- // operand is a const index holding the variable name string.
339
- // Mimics JS semantics: typeof undeclaredVar === "undefined" (no throw).
340
- var name = this._pop(); // LOAD_CONST pushed the name - consume it
341
- var val = Object.prototype.hasOwnProperty.call(this.globals, name)
342
- ? this.globals[name]
343
- : undefined;
344
- this._push(typeof val);
345
- break;
346
- }
347
-
348
- case OP.JUMP:
349
- frame.pc = operand;
350
- break;
351
-
352
- case OP.JUMP_IF_FALSE:
353
- if (!this._pop()) frame.pc = operand;
354
- break;
355
-
356
- case OP.JUMP_IF_TRUE_OR_POP:
357
- // || semantics: if truthy, we're done - leave value, jump over RHS.
358
- // If falsy, discard it and fall through to evaluate RHS.
359
- if (this.peek()) {
360
- frame.pc = operand;
361
- } else {
362
- this._pop();
363
- }
364
- break;
365
-
366
- case OP.JUMP_IF_FALSE_OR_POP:
367
- // && semantics: if falsy, we're done - leave value, jump over RHS.
368
- // If truthy, discard it and fall through to evaluate RHS.
369
- if (!this.peek()) {
370
- frame.pc = operand;
371
- } else {
372
- this._pop();
373
- }
374
- break;
375
-
376
- case OP.MAKE_CLOSURE: {
377
- var fn = this.constants[operand];
378
- var closure = new Closure(fn);
379
- for (var i = 0; i < fn.upvalueDescriptors.length; i++) {
380
- var desc = fn.upvalueDescriptors[i];
381
- if (desc.isLocal) {
382
- // Capture directly from current frame's local slot
383
- closure.upvalues.push(this.captureUpvalue(frame, desc._index));
384
- } else {
385
- // Relay - take upvalue from the enclosing closure's list
386
- closure.upvalues.push(frame.closure.upvalues[desc._index]);
387
- }
388
- }
389
- // Wrap in a native callable shell so host code (array methods,
390
- // test assertions, setTimeout, etc.) can invoke VM closures.
391
- // CLOSURE_SYM lets VM-internal CALL/NEW bypass the sub-VM entirely.
392
- var self = this;
393
- var shell = (function (c) {
394
- return function () {
395
- var args = Array.prototype.slice.call(arguments);
396
- var sub = new VM(self.bytecode, 0, self.constants, self.globals);
397
- // Sloppy-mode: null/undefined thisArg global object
398
- var f = new Frame(
399
- c,
400
- null,
401
- null,
402
- this == null ? self.globals : this,
403
- );
404
- for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
405
- f.locals[c.fn.paramCount] = args;
406
- sub.currentFrame = f;
407
- return sub.run();
408
- };
409
- })(closure);
410
- shell[CLOSURE_SYM] = closure;
411
- shell.prototype = closure.prototype; // unified prototype for new/instanceof
412
- this._push(shell);
413
- break;
414
- }
415
-
416
- case OP.LOAD_UPVALUE:
417
- this._push(frame.closure.upvalues[operand].read());
418
- break;
419
-
420
- case OP.STORE_UPVALUE:
421
- frame.closure.upvalues[operand].write(this._pop());
422
- break;
423
-
424
- case OP.BUILD_ARRAY: {
425
- // Pop \`operand\` values off the stack in reverse, assemble array.
426
- var elems = this._stack.splice(this._stack.length - operand);
427
- this._push(elems);
428
- break;
429
- }
430
-
431
- case OP.BUILD_OBJECT: {
432
- // Stack has: key0, val0, key1, val1 ... keyN, valN (pushed left->right)
433
- // Pop all pairs and build the object.
434
- var pairs = this._stack.splice(this._stack.length - operand * 2);
435
- var o = {};
436
- for (var i = 0; i < pairs.length; i += 2) {
437
- o[pairs[i]] = pairs[i + 1]; // key at even index, val at odd
438
- }
439
- this._push(o);
440
- break;
441
- }
442
- case OP.SET_PROP: {
443
- // Stack: [..., obj, key, val]
444
- // Leaves val on stack - assignment is an expression in JS.
445
- var val = this._pop();
446
- var key = this._pop();
447
- var obj = this._pop();
448
- // Reflect.set performs [[Set]] without throwing on failure,
449
- // correctly simulating sloppy-mode assignment from a strict-mode host
450
- // (output.js is an ES module). This also properly invokes inherited
451
- // or prototype-chain setter functions.
452
- Reflect.set(obj, key, val);
453
- this._push(val); // assignment expression evaluates to the assigned value
454
- break;
455
- }
456
- case OP.GET_PROP_COMPUTED: {
457
- // Stack: [..., obj, key] - key is a runtime value (nums[i])
458
- // Mirrors GET_PROP but pops the key that was pushed dynamically.
459
- var key = this._pop();
460
- var obj = this._pop();
461
- this._push(obj[key]);
462
- break;
463
- }
464
- case OP.DELETE_PROP: {
465
- var key = this._pop();
466
- var obj = this._pop();
467
- this._push(delete obj[key]);
468
- break;
469
- }
470
-
471
- case OP.CALL: {
472
- var args = this._stack.splice(this._stack.length - operand);
473
- var callee = this._pop();
474
- if (callee && callee[CLOSURE_SYM]) {
475
- // VM closure - run directly in this VM, no sub-VM overhead
476
- var c = callee[CLOSURE_SYM];
477
- // Sloppy-mode: plain function call → global object as this
478
- var f = new Frame(c, frame.pc, frame, this.globals);
479
- for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
480
- f.locals[c.fn.paramCount] = args;
481
- this.frameStack.push(this.currentFrame);
482
- this.currentFrame = f;
483
- } else {
484
- // Native function
485
- this._push(callee.apply(null, args));
486
- }
487
- break;
488
- }
489
-
490
- case OP.CALL_METHOD: {
491
- var args = this._stack.splice(this._stack.length - operand);
492
- var callee = this._pop();
493
- var receiver = this._pop(); // left on stack by GET_PROP
494
- if (callee && callee[CLOSURE_SYM]) {
495
- // VM closure - run directly in this VM with receiver as this
496
- var c = callee[CLOSURE_SYM];
497
- var f = new Frame(c, frame.pc, frame, receiver);
498
- for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
499
- f.locals[c.fn.paramCount] = args;
500
- this.frameStack.push(this.currentFrame);
501
- this.currentFrame = f;
502
- } else {
503
- // Native method
504
- this._push(callee.apply(receiver, args));
505
- }
506
- break;
507
- }
508
-
509
- case OP.LOAD_THIS:
510
- this._push(frame.thisVal);
511
- break;
512
-
513
- case OP.NEW: {
514
- var args = this._stack.splice(this._stack.length - operand);
515
- var callee = this._pop();
516
- if (callee && callee[CLOSURE_SYM]) {
517
- // VM closure constructor - prototype is unified via shell.prototype = closure.prototype
518
- var c = callee[CLOSURE_SYM];
519
- var newObj = Object.create(c.prototype || null);
520
- var f = new Frame(c, frame.pc, frame, newObj);
521
- f._newObj = newObj;
522
- for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
523
- f.locals[c.fn.paramCount] = args;
524
- this.frameStack.push(this.currentFrame);
525
- this.currentFrame = f;
526
- } else {
527
- // Native constructor (e.g. new Error(), new Date()).
528
- // Reflect.construct is required - Object.create+apply does NOT set
529
- // internal slots ([[NumberData]], [[StringData]], etc.) for built-ins.
530
- this._push(Reflect.construct(callee, args));
531
- }
532
- break;
533
- }
534
-
535
- case OP.RETURN: {
536
- var retVal = this._pop();
537
- this.closeUpvaluesFor(frame); // must happen before frame is abandoned
538
- if (this.frameStack.length === 0) return retVal;
539
-
540
- // new-call rule: primitive return -> discard, use the constructed object instead
541
- if (frame._newObj !== null) {
542
- if (typeof retVal !== "object" || retVal === null)
543
- retVal = frame._newObj;
544
- }
545
-
546
- this.currentFrame = this.frameStack.pop();
547
- this._push(retVal);
548
- break;
549
- }
550
-
551
- case OP.POP:
552
- this._pop();
553
- break;
554
-
555
- case OP.DUP:
556
- this._push(this.peek());
557
- break;
558
-
559
- case OP.THROW:
560
- throw this._pop();
561
-
562
- case OP.FOR_IN_SETUP: {
563
- // Pop the object; build an ordered list of all enumerable own+inherited
564
- // string keys by walking the prototype chain manually.
565
- // Uses getOwnPropertyNames (includes non-enumerable) + descriptor check,
566
- // so we never rely on Object.keys() and we handle inheritance correctly.
567
- var obj = this._pop();
568
- var keys = [];
569
- if (obj !== null && obj !== undefined) {
570
- var seen = Object.create(null);
571
- var cur = Object(obj); // box primitives
572
- while (cur !== null) {
573
- var ownNames = Object.getOwnPropertyNames(cur);
574
- for (var i = 0; i < ownNames.length; i++) {
575
- var k = ownNames[i];
576
- if (!(k in seen)) {
577
- seen[k] = true;
578
- var propDesc = Object.getOwnPropertyDescriptor(cur, k);
579
- if (propDesc && propDesc.enumerable) {
580
- keys.push(k);
581
- }
582
- }
583
- }
584
- cur = Object.getPrototypeOf(cur);
585
- }
586
- }
587
- this._push({ keys: keys, i: 0 });
588
- break;
589
- }
590
-
591
- case OP.FOR_IN_NEXT: {
592
- // operand = jump target for the done case.
593
- // Pop the iterator; if exhausted jump to exit, otherwise push next key.
594
- var iter = this._pop();
595
- if (iter.i >= iter.keys.length) {
596
- frame.pc = operand;
597
- } else {
598
- this._push(iter.keys[iter.i++]);
599
- }
600
- break;
601
- }
602
-
603
- case OP.PATCH: {
604
- // Pop destination PC, then write constants[operand] (packed word array)
605
- // directly into this.bytecode starting at that PC.
606
- var destPc = this._pop();
607
- var words = this.constants[operand];
608
-
609
- if (ENCODE_BYTECODE) {
610
- words = decodeBytecode(words);
611
- }
612
-
613
- for (var i = 0; i < words.length; i++) {
614
- this.bytecode[destPc + i] = words[i];
615
- }
616
- break;
617
- }
618
-
619
- default:
620
- throw new Error("Unknown opcode: " + op + " at pc " + (frame.pc - 1));
621
- }
622
- }
623
- };
624
-
625
- // Boot
626
- var globals: any = {}; // global object for globals
627
-
628
- // Always pull built-ins from globalThis so eval() scoping can't shadow them
629
- // with a local `window` variable (e.g. the test harness fake window).
630
- for (var k of Object.getOwnPropertyNames(globalThis)) {
631
- globals[k] = globalThis[k];
632
- }
633
- // If a window object is in scope (browser or test harness), capture it
634
- // explicitly so VM code can read/write window.TEST_OUTPUT etc.
635
- if (typeof window !== "undefined") {
636
- globals["window"] = window;
637
- }
638
-
639
- // Transfer common primitives
640
- globals.undefined = undefined;
641
- globals.Infinity = Infinity;
642
- globals.NaN = NaN;
643
-
644
- var vm = new VM(decodeBytecode(BYTECODE), MAIN_START_PC, CONSTANTS, globals);
645
- vm.run();
1
+ import { OP_ORIGINAL as OP } from "./compiler.ts";
2
+ const BYTECODE = [];
3
+ const MAIN_START_PC = 0;
4
+ const CONSTANTS = [];
5
+ const ENCODE_BYTECODE = false;
6
+ const TIMING_CHECKS = false;
7
+ // The text above is not included in the compiled output - for type intellisense only
8
+ // @START
9
+
10
+ function decodeBytecode(s) {
11
+ if (!ENCODE_BYTECODE) return s;
12
+
13
+ var b =
14
+ typeof Buffer !== "undefined"
15
+ ? Buffer.from(s, "base64")
16
+ : Uint8Array.from(atob(s), function (c) {
17
+ return c.charCodeAt(0);
18
+ });
19
+ // Each slot is a u16 stored as 2 little-endian bytes.
20
+ var r = new Uint16Array(b.length / 2);
21
+ for (var i = 0; i < r.length; i++) r[i] = b[i * 2] | (b[i * 2 + 1] << 8);
22
+ return r;
23
+ }
24
+
25
+ // Closure symbol
26
+ // Used to tag shell functions so the VM can fast-path back to the
27
+ // inner Closure instead of going through a sub-VM on internal calls.
28
+ var CLOSURE_SYM = Symbol(); // Nameless for obfuscation
29
+
30
+ // Upvalue
31
+ // While the outer frame is alive: reads/writes go to frame.locals[slot].
32
+ // After the outer frame returns (closed): reads/writes hit this.value.
33
+ function Upvalue(frame, slot) {
34
+ this._frame = frame;
35
+ this._slot = slot;
36
+ this._closed = false;
37
+ this._value = undefined;
38
+ }
39
+ Upvalue.prototype._read = function () {
40
+ return this._closed ? this._value : this._frame.locals[this._slot];
41
+ };
42
+ Upvalue.prototype._write = function (v) {
43
+ if (this._closed) this._value = v;
44
+ else this._frame.locals[this._slot] = v;
45
+ };
46
+ Upvalue.prototype._close = function () {
47
+ this._value = this._frame.locals[this._slot];
48
+ this._closed = true;
49
+ };
50
+
51
+ // Closure & Frame
52
+ function Closure(fn) {
53
+ this.fn = fn;
54
+ this.upvalues = [];
55
+ this.prototype = {}; // <- default prototype object for \`new\`
56
+ }
57
+
58
+ function Frame(closure, returnPc, parent, thisVal?) {
59
+ this.closure = closure;
60
+ this.locals = new Array(closure.fn.localCount).fill(undefined);
61
+ this._pc = closure.fn.startPc; // <- initialize from fn descriptor
62
+ this._returnPc = returnPc; // pc to resume in parent frame after RETURN
63
+ this._parent = parent;
64
+ this.thisVal = thisVal !== undefined ? thisVal : undefined;
65
+ this._newObj = null; // <- set by NEW so RETURN can see it
66
+ this._handlerStack = []; // <- exception handlers pushed by TRY_SETUP
67
+ }
68
+
69
+ // VM
70
+ function VM(bytecode, mainStartPc, constants, globals) {
71
+ this.bytecode = bytecode;
72
+ this.constants = constants;
73
+ this.globals = globals;
74
+ this._stack = [];
75
+ this._frameStack = [];
76
+ this._openUpvalues = []; // all currently open Upvalue objects across all frames
77
+
78
+ var mainFn = {
79
+ paramCount: 0,
80
+ localCount: 0,
81
+ startPc: mainStartPc, // <- where main begins
82
+ };
83
+ this._currentFrame = new Frame(new Closure(mainFn), null, null);
84
+ }
85
+
86
+ VM.prototype._push = function (v) {
87
+ this._stack.push(v);
88
+ };
89
+ VM.prototype._pop = function () {
90
+ return this._stack.pop();
91
+ };
92
+ VM.prototype.peek = function () {
93
+ return this._stack[this._stack.length - 1];
94
+ };
95
+
96
+ // Consume the next slot from the flat bytecode stream and advance the PC.
97
+ // Called by opcode handlers to read each of their operands in order.
98
+ VM.prototype._operand = function () {
99
+ return this.bytecode[this._currentFrame._pc++];
100
+ };
101
+
102
+ VM.prototype.captureUpvalue = function (frame, slot) {
103
+ // Reuse existing open upvalue for this frame+slot if one exists.
104
+ // This is what makes two closures share the same mutable cell.
105
+ for (var i = 0; i < this._openUpvalues.length; i++) {
106
+ var uv = this._openUpvalues[i];
107
+ if (uv._frame === frame && uv._slot === slot) return uv;
108
+ }
109
+ var uv = new Upvalue(frame, slot);
110
+ this._openUpvalues.push(uv);
111
+ return uv;
112
+ };
113
+
114
+ VM.prototype._closeUpvaluesFor = function (frame) {
115
+ // Called on RETURN - close every upvalue that was pointing into this frame.
116
+ // After this, closures that captured from the frame read from upvalue.value.
117
+ this._openUpvalues = this._openUpvalues.filter(function (uv) {
118
+ if (uv._frame === frame) {
119
+ uv._close();
120
+ return false;
121
+ }
122
+ return true;
123
+ });
124
+ };
125
+
126
+ VM.prototype.run = function () {
127
+ var now = () => {
128
+ return performance.now();
129
+ };
130
+
131
+ var lastTime = now();
132
+
133
+ while (true) {
134
+ var frame = this._currentFrame;
135
+ var bc = this.bytecode;
136
+ if (frame._pc >= bc.length) break;
137
+
138
+ var op = this.bytecode[frame._pc++];
139
+
140
+ // console.log(frame._pc - 1, op);
141
+
142
+ // Debugging protection: Detects debugger by checking for >1s pauses which can only happen from debugger; or extremely slow sync tasks
143
+ if (TIMING_CHECKS) {
144
+ var currentTime = now();
145
+ var isTamper = currentTime - lastTime > 1000;
146
+ lastTime = currentTime;
147
+ if (isTamper) {
148
+ // Poison the bytecode
149
+ for (var i = 0; i < this.bytecode.length; i++) this.bytecode[i] = 0;
150
+ // Break the current state
151
+ op = OP.POP;
152
+ this._stack = [];
153
+ }
154
+ }
155
+
156
+ try {
157
+ /* @SWITCH */
158
+ switch (op) {
159
+ case OP.LOAD_CONST:
160
+ this._push(this.constants[this._operand()]);
161
+ break;
162
+
163
+ case OP.LOAD_INT:
164
+ this._push(this._operand());
165
+ break;
166
+
167
+ case OP.LOAD_LOCAL:
168
+ this._push(frame.locals[this._operand()]);
169
+ break;
170
+
171
+ case OP.STORE_LOCAL:
172
+ frame.locals[this._operand()] = this._pop();
173
+ break;
174
+
175
+ case OP.LOAD_GLOBAL:
176
+ this._push(this.globals[this.constants[this._operand()]]);
177
+ break;
178
+
179
+ case OP.STORE_GLOBAL:
180
+ this.globals[this.constants[this._operand()]] = this._pop();
181
+ break;
182
+
183
+ case OP.GET_PROP: {
184
+ // Stack: [..., obj, key] -> [..., obj, obj[key]]
185
+ // obj is PEEKED (not popped) - CALL_METHOD needs it as receiver
186
+ var key = this._pop();
187
+ var obj = this.peek();
188
+ this._push(obj[key]);
189
+ break;
190
+ }
191
+
192
+ case OP.ADD: {
193
+ var b = this._pop();
194
+ this._push(this._pop() + b);
195
+ break;
196
+ }
197
+ case OP.SUB: {
198
+ var b = this._pop();
199
+ this._push(this._pop() - b);
200
+ break;
201
+ }
202
+ case OP.MUL: {
203
+ var b = this._pop();
204
+ this._push(this._pop() * b);
205
+ break;
206
+ }
207
+ case OP.DIV: {
208
+ var b = this._pop();
209
+ this._push(this._pop() / b);
210
+ break;
211
+ }
212
+ case OP.MOD: {
213
+ var b = this._pop();
214
+ this._push(this._pop() % b);
215
+ break;
216
+ }
217
+ case OP.BAND: {
218
+ var b = this._pop();
219
+ this._push(this._pop() & b);
220
+ break;
221
+ }
222
+ case OP.BOR: {
223
+ var b = this._pop();
224
+ this._push(this._pop() | b);
225
+ break;
226
+ }
227
+ case OP.BXOR: {
228
+ var b = this._pop();
229
+ this._push(this._pop() ^ b);
230
+ break;
231
+ }
232
+ case OP.SHL: {
233
+ var b = this._pop();
234
+ this._push(this._pop() << b);
235
+ break;
236
+ }
237
+ case OP.SHR: {
238
+ var b = this._pop();
239
+ this._push(this._pop() >> b);
240
+ break;
241
+ }
242
+ case OP.USHR: {
243
+ var b = this._pop();
244
+ this._push(this._pop() >>> b);
245
+ break;
246
+ }
247
+
248
+ case OP.LT: {
249
+ var b = this._pop();
250
+ this._push(this._pop() < b);
251
+ break;
252
+ }
253
+ case OP.GT: {
254
+ var b = this._pop();
255
+ this._push(this._pop() > b);
256
+ break;
257
+ }
258
+ case OP.EQ: {
259
+ var b = this._pop();
260
+ this._push(this._pop() === b);
261
+ break;
262
+ }
263
+
264
+ case OP.LTE: {
265
+ var b = this._pop();
266
+ this._push(this._pop() <= b);
267
+ break;
268
+ }
269
+ case OP.GTE: {
270
+ var b = this._pop();
271
+ this._push(this._pop() >= b);
272
+ break;
273
+ }
274
+ case OP.NEQ: {
275
+ var b = this._pop();
276
+ this._push(this._pop() !== b);
277
+ break;
278
+ }
279
+ case OP.LOOSE_EQ: {
280
+ var b = this._pop();
281
+ this._push(this._pop() == b);
282
+ break;
283
+ }
284
+ case OP.LOOSE_NEQ: {
285
+ var b = this._pop();
286
+ this._push(this._pop() != b);
287
+ break;
288
+ }
289
+
290
+ case OP.IN: {
291
+ var b = this._pop();
292
+ this._push(this._pop() in b);
293
+ break;
294
+ }
295
+
296
+ case OP.INSTANCEOF: {
297
+ var ctor = this._pop();
298
+ var obj = this._pop();
299
+ if (typeof ctor === "function") {
300
+ // Native constructor (e.g. Array, Date) - native instanceof is fine
301
+ this._push(obj instanceof ctor);
302
+ } else {
303
+ // VM Closure - ctor.prototype was set by MAKE_CLOSURE / user assignment.
304
+ // Walk obj's prototype chain looking for identity with ctor.prototype.
305
+ var proto = ctor.prototype; // the .prototype property on the Closure
306
+ var target = Object.getPrototypeOf(obj);
307
+ var result = false;
308
+ while (target !== null) {
309
+ if (target === proto) {
310
+ result = true;
311
+ break;
312
+ }
313
+ target = Object.getPrototypeOf(target);
314
+ }
315
+ this._push(result);
316
+ }
317
+ break;
318
+ }
319
+
320
+ case OP.UNARY_NEG:
321
+ this._push(-this._pop());
322
+ break;
323
+ case OP.UNARY_POS:
324
+ this._push(this._pop());
325
+ break;
326
+ case OP.UNARY_NOT:
327
+ this._push(!this._pop());
328
+ break;
329
+ case OP.UNARY_BITNOT:
330
+ this._push(~this._pop());
331
+ break;
332
+ case OP.TYPEOF:
333
+ this._push(typeof this._pop());
334
+ break;
335
+ case OP.VOID:
336
+ this._pop();
337
+ this._push(undefined);
338
+ break;
339
+
340
+ case OP.TYPEOF_SAFE: {
341
+ // operand is a const index holding the variable name string.
342
+ // Mimics JS semantics: typeof undeclaredVar === "undefined" (no throw).
343
+ var name = this._pop(); // LOAD_CONST pushed the name - consume it
344
+ var val = Object.prototype.hasOwnProperty.call(this.globals, name)
345
+ ? this.globals[name]
346
+ : undefined;
347
+ this._push(typeof val);
348
+ break;
349
+ }
350
+
351
+ case OP.JUMP:
352
+ frame._pc = this._operand();
353
+ break;
354
+
355
+ case OP.JUMP_IF_FALSE: {
356
+ var target = this._operand();
357
+ if (!this._pop()) frame._pc = target;
358
+ break;
359
+ }
360
+
361
+ case OP.JUMP_IF_TRUE_OR_POP: {
362
+ // || semantics: if truthy, we're done - leave value, jump over RHS.
363
+ // If falsy, discard it and fall through to evaluate RHS.
364
+ var target = this._operand();
365
+ if (this.peek()) {
366
+ frame._pc = target;
367
+ } else {
368
+ this._pop();
369
+ }
370
+ break;
371
+ }
372
+
373
+ case OP.JUMP_IF_FALSE_OR_POP: {
374
+ // && semantics: if falsy, we're done - leave value, jump over RHS.
375
+ // If truthy, discard it and fall through to evaluate RHS.
376
+ var target = this._operand();
377
+ if (!this.peek()) {
378
+ frame._pc = target;
379
+ } else {
380
+ this._pop();
381
+ }
382
+ break;
383
+ }
384
+
385
+ case OP.MAKE_CLOSURE: {
386
+ // Inline operands: startPc, paramCount, localCount, uvCount,
387
+ // [isLocal_0, idx_0, isLocal_1, idx_1, ...]
388
+ var startPc = this._operand();
389
+ var paramCount = this._operand();
390
+ var localCount = this._operand();
391
+ var uvCount = this._operand();
392
+
393
+ var uvDescs = new Array(uvCount);
394
+ for (var i = 0; i < uvCount; i++) {
395
+ var isLocalRaw = this._operand();
396
+ var uvIndex = this._operand();
397
+ uvDescs[i] = { isLocal: isLocalRaw, _index: uvIndex };
398
+ }
399
+
400
+ var fn = {
401
+ paramCount: paramCount,
402
+ localCount: localCount,
403
+ startPc: startPc,
404
+ upvalueDescriptors: uvDescs,
405
+ };
406
+
407
+ var closure = new Closure(fn);
408
+ for (var i = 0; i < uvDescs.length; i++) {
409
+ var uvd = uvDescs[i];
410
+ if (uvd.isLocal) {
411
+ // Capture directly from current frame's local slot
412
+ closure.upvalues.push(this.captureUpvalue(frame, uvd._index));
413
+ } else {
414
+ // Relay - take upvalue from the enclosing closure's list
415
+ closure.upvalues.push(frame.closure.upvalues[uvd._index]);
416
+ }
417
+ }
418
+ // Wrap in a native callable shell so host code (array methods,
419
+ // test assertions, setTimeout, etc.) can invoke VM closures.
420
+ // CLOSURE_SYM lets VM-internal CALL/NEW bypass the sub-VM entirely.
421
+ var self = this;
422
+ var shell = (function (c) {
423
+ return function () {
424
+ var args = Array.prototype.slice.call(arguments);
425
+ var sub = new VM(self.bytecode, 0, self.constants, self.globals);
426
+ // Sloppy-mode: null/undefined thisArg global object
427
+ var f = new Frame(
428
+ c,
429
+ null,
430
+ null,
431
+ this == null ? self.globals : this,
432
+ );
433
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
434
+ f.locals[c.fn.paramCount] = args;
435
+ sub._currentFrame = f;
436
+ return sub.run();
437
+ };
438
+ })(closure);
439
+ shell[CLOSURE_SYM] = closure;
440
+ shell.prototype = closure.prototype; // unified prototype for new/instanceof
441
+ this._push(shell);
442
+ break;
443
+ }
444
+
445
+ case OP.LOAD_UPVALUE:
446
+ this._push(frame.closure.upvalues[this._operand()]._read());
447
+ break;
448
+
449
+ case OP.STORE_UPVALUE:
450
+ frame.closure.upvalues[this._operand()]._write(this._pop());
451
+ break;
452
+
453
+ case OP.BUILD_ARRAY: {
454
+ var elems = this._stack.splice(this._stack.length - this._operand());
455
+ this._push(elems);
456
+ break;
457
+ }
458
+
459
+ case OP.BUILD_OBJECT: {
460
+ // Stack has: key0, val0, key1, val1 ... keyN, valN (pushed left->right)
461
+ // Pop all pairs and build the object.
462
+ var pairs = this._stack.splice(
463
+ this._stack.length - this._operand() * 2,
464
+ );
465
+ var o = {};
466
+ for (var i = 0; i < pairs.length; i += 2) {
467
+ o[pairs[i]] = pairs[i + 1]; // key at even index, val at odd
468
+ }
469
+ this._push(o);
470
+ break;
471
+ }
472
+ case OP.SET_PROP: {
473
+ // Stack: [..., obj, key, val]
474
+ // Leaves val on stack - assignment is an expression in JS.
475
+ var val = this._pop();
476
+ var key = this._pop();
477
+ var obj = this._pop();
478
+ // Reflect.set performs [[Set]] without throwing on failure,
479
+ // correctly simulating sloppy-mode assignment from a strict-mode host
480
+ // (output.js is an ES module). This also properly invokes inherited
481
+ // or prototype-chain setter functions.
482
+ Reflect.set(obj, key, val);
483
+ this._push(val); // assignment expression evaluates to the assigned value
484
+ break;
485
+ }
486
+ case OP.GET_PROP_COMPUTED: {
487
+ // Stack: [..., obj, key] - key is a runtime value (nums[i])
488
+ // Mirrors GET_PROP but pops the key that was pushed dynamically.
489
+ var key = this._pop();
490
+ var obj = this._pop();
491
+ this._push(obj[key]);
492
+ break;
493
+ }
494
+ case OP.DELETE_PROP: {
495
+ var key = this._pop();
496
+ var obj = this._pop();
497
+ this._push(delete obj[key]);
498
+ break;
499
+ }
500
+
501
+ case OP.CALL: {
502
+ var args = this._stack.splice(this._stack.length - this._operand());
503
+ var callee = this._pop();
504
+ if (callee && callee[CLOSURE_SYM]) {
505
+ // VM closure - run directly in this VM, no sub-VM overhead
506
+ var c = callee[CLOSURE_SYM];
507
+ // Sloppy-mode: plain function call → global object as this
508
+ var f = new Frame(c, frame._pc, frame, this.globals);
509
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
510
+ f.locals[c.fn.paramCount] = args;
511
+ this._frameStack.push(this._currentFrame);
512
+ this._currentFrame = f;
513
+ } else {
514
+ // Native function
515
+ this._push(callee.apply(null, args));
516
+ }
517
+ break;
518
+ }
519
+
520
+ case OP.CALL_METHOD: {
521
+ var args = this._stack.splice(this._stack.length - this._operand());
522
+ var callee = this._pop();
523
+ var receiver = this._pop(); // left on stack by GET_PROP
524
+ if (callee && callee[CLOSURE_SYM]) {
525
+ // VM closure - run directly in this VM with receiver as this
526
+ var c = callee[CLOSURE_SYM];
527
+ var f = new Frame(c, frame._pc, frame, receiver);
528
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
529
+ f.locals[c.fn.paramCount] = args;
530
+ this._frameStack.push(this._currentFrame);
531
+ this._currentFrame = f;
532
+ } else {
533
+ // Native method
534
+ this._push(callee.apply(receiver, args));
535
+ }
536
+ break;
537
+ }
538
+
539
+ case OP.LOAD_THIS:
540
+ this._push(frame.thisVal);
541
+ break;
542
+
543
+ case OP.NEW: {
544
+ var args = this._stack.splice(this._stack.length - this._operand());
545
+ var callee = this._pop();
546
+ if (callee && callee[CLOSURE_SYM]) {
547
+ // VM closure constructor - prototype is unified via shell.prototype = closure.prototype
548
+ var c = callee[CLOSURE_SYM];
549
+ var newObj = Object.create(c.prototype || null);
550
+ var f = new Frame(c, frame._pc, frame, newObj);
551
+ f._newObj = newObj;
552
+ for (var i = 0; i < args.length; i++) f.locals[i] = args[i];
553
+ f.locals[c.fn.paramCount] = args;
554
+ this._frameStack.push(this._currentFrame);
555
+ this._currentFrame = f;
556
+ } else {
557
+ // Native constructor (e.g. new Error(), new Date()).
558
+ // Reflect.construct is required - Object.create+apply does NOT set
559
+ // internal slots ([[NumberData]], [[StringData]], etc.) for built-ins.
560
+ this._push(Reflect.construct(callee, args));
561
+ }
562
+ break;
563
+ }
564
+
565
+ case OP.RETURN: {
566
+ var retVal = this._pop();
567
+ this._closeUpvaluesFor(frame); // must happen before frame is abandoned
568
+ if (this._frameStack.length === 0) return retVal;
569
+
570
+ // new-call rule: primitive return -> discard, use the constructed object instead
571
+ if (frame._newObj !== null) {
572
+ if (typeof retVal !== "object" || retVal === null)
573
+ retVal = frame._newObj;
574
+ }
575
+
576
+ this._currentFrame = this._frameStack.pop();
577
+ this._push(retVal);
578
+ break;
579
+ }
580
+
581
+ case OP.POP:
582
+ this._pop();
583
+ break;
584
+
585
+ case OP.DUP:
586
+ this._push(this.peek());
587
+ break;
588
+
589
+ case OP.THROW:
590
+ throw this._pop();
591
+
592
+ case OP.FOR_IN_SETUP: {
593
+ // Pop the object; build an ordered list of all enumerable own+inherited
594
+ // string keys by walking the prototype chain manually.
595
+ // Uses getOwnPropertyNames (includes non-enumerable) + descriptor check,
596
+ // so we never rely on Object.keys() and we handle inheritance correctly.
597
+ var obj = this._pop();
598
+ var keys = [];
599
+ if (obj !== null && obj !== undefined) {
600
+ var seen = Object.create(null);
601
+ var cur = Object(obj); // box primitives
602
+ while (cur !== null) {
603
+ var ownNames = Object.getOwnPropertyNames(cur);
604
+ for (var i = 0; i < ownNames.length; i++) {
605
+ var k = ownNames[i];
606
+ if (!(k in seen)) {
607
+ seen[k] = true;
608
+ var propDesc = Object.getOwnPropertyDescriptor(cur, k);
609
+ if (propDesc && propDesc.enumerable) {
610
+ keys.push(k);
611
+ }
612
+ }
613
+ }
614
+ cur = Object.getPrototypeOf(cur);
615
+ }
616
+ }
617
+ this._push({ _keys: keys, i: 0 });
618
+ break;
619
+ }
620
+
621
+ case OP.FOR_IN_NEXT: {
622
+ // Operand = jump target for the done case. Must be read before the
623
+ // conditional so the PC stays correctly aligned either way.
624
+ var target = this._operand();
625
+ var iter = this._pop();
626
+ if (iter.i >= iter._keys.length) {
627
+ frame._pc = target;
628
+ } else {
629
+ this._push(iter._keys[iter.i++]);
630
+ }
631
+ break;
632
+ }
633
+
634
+ case OP.PATCH: {
635
+ // Inline operands: destPc, sliceStart, sliceEnd
636
+ // Copies bytecode[sliceStart..sliceEnd) flat u16 slots to destPc.
637
+ var destPc = this._operand();
638
+ var sliceStart = this._operand();
639
+ var sliceEnd = this._operand();
640
+
641
+ for (var pi = sliceStart; pi < sliceEnd; pi++) {
642
+ this.bytecode[destPc + (pi - sliceStart)] = this.bytecode[pi];
643
+ }
644
+ break;
645
+ }
646
+
647
+ case OP.TRY_SETUP: {
648
+ // Push an exception handler record onto the current frame.
649
+ // Saves: catch PC (operand), current stack depth, current frame-stack depth.
650
+ // If an exception is thrown before TRY_END fires, the VM jumps here.
651
+ frame._handlerStack.push({
652
+ handlerPc: this._operand(),
653
+ stackDepth: this._stack.length,
654
+ frameStackDepth: this._frameStack.length,
655
+ });
656
+ break;
657
+ }
658
+
659
+ case OP.TRY_END: {
660
+ // Normal exit from a try block — disarm the exception handler.
661
+ frame._handlerStack.pop();
662
+ break;
663
+ }
664
+
665
+ case OP.DEFINE_GETTER: {
666
+ // Stack: [..., obj, key, getterFn]
667
+ // Pops all three; defines an enumerable, configurable getter on obj.
668
+ // If a setter was already defined for this key, it is preserved.
669
+ var getterFn = this._pop();
670
+ var key = this._pop();
671
+ var obj = this._pop();
672
+ var existingDesc = Object.getOwnPropertyDescriptor(obj, key);
673
+ var getDesc: PropertyDescriptor = {
674
+ get: getterFn,
675
+ configurable: true,
676
+ enumerable: true,
677
+ };
678
+ if (existingDesc && typeof existingDesc.set === "function") {
679
+ getDesc.set = existingDesc.set;
680
+ }
681
+ Object.defineProperty(obj, key, getDesc);
682
+ break;
683
+ }
684
+
685
+ case OP.DEFINE_SETTER: {
686
+ // Stack: [..., obj, key, setterFn]
687
+ // Pops all three; defines an enumerable, configurable setter on obj.
688
+ // If a getter was already defined for this key, it is preserved.
689
+ var setterFn = this._pop();
690
+ var key = this._pop();
691
+ var obj = this._pop();
692
+ var existingDesc = Object.getOwnPropertyDescriptor(obj, key);
693
+ var setDesc: PropertyDescriptor = {
694
+ set: setterFn,
695
+ configurable: true,
696
+ enumerable: true,
697
+ };
698
+ if (existingDesc && typeof existingDesc.get === "function") {
699
+ setDesc.get = existingDesc.get;
700
+ }
701
+ Object.defineProperty(obj, key, setDesc);
702
+ break;
703
+ }
704
+
705
+ case OP.DEBUGGER: {
706
+ debugger;
707
+ break;
708
+ }
709
+
710
+ default:
711
+ throw new Error(
712
+ "Unknown opcode: " + op + " at pc " + (frame._pc - 1),
713
+ );
714
+ }
715
+ } catch (err) {
716
+ // Exception handler unwinding (CPython-style frame walk, Lua-style upvalue close).
717
+ // Walk from the current frame upward until we find a frame that has an open
718
+ // exception handler (TRY_SETUP without a matching TRY_END).
719
+ // For every frame we abandon along the way, close its captured upvalues.
720
+ var handledFrame = null;
721
+ var searchFrame = this._currentFrame;
722
+ while (true) {
723
+ if (searchFrame._handlerStack.length > 0) {
724
+ handledFrame = searchFrame;
725
+ break;
726
+ }
727
+ // No handler in this frame — abandon it and walk up.
728
+ this._closeUpvaluesFor(searchFrame);
729
+ if (this._frameStack.length === 0) break;
730
+ searchFrame = this._frameStack.pop();
731
+ this._currentFrame = searchFrame;
732
+ }
733
+
734
+ if (!handledFrame) throw err; // no handler anywhere — propagate to host
735
+
736
+ var h = handledFrame._handlerStack.pop();
737
+ // Restore the VM value stack to the depth recorded at TRY_SETUP time,
738
+ // then push the caught exception so the catch binding can store it.
739
+ this._stack.length = h.stackDepth;
740
+ this._push(err);
741
+ // Discard any call-frames that were pushed inside the try body
742
+ // (functions called from within the try block that are still live).
743
+ this._frameStack.length = h.frameStackDepth;
744
+ // Jump to the catch block.
745
+ handledFrame._pc = h.handlerPc;
746
+ this._currentFrame = handledFrame;
747
+ }
748
+ }
749
+ };
750
+
751
+ // Boot
752
+ var globals: any = {}; // global object for globals
753
+
754
+ // Always pull built-ins from globalThis so eval() scoping can't shadow them
755
+ // with a local `window` variable (e.g. the test harness fake window).
756
+ for (var k of Object.getOwnPropertyNames(globalThis)) {
757
+ globals[k] = globalThis[k];
758
+ }
759
+ // If a window object is in scope (browser or test harness), capture it
760
+ // explicitly so VM code can read/write window.TEST_OUTPUT etc.
761
+ if (typeof window !== "undefined") {
762
+ globals["window"] = window;
763
+ }
764
+
765
+ // Transfer common primitives
766
+ globals.undefined = undefined;
767
+ globals.Infinity = Infinity;
768
+ globals.NaN = NaN;
769
+
770
+ var vm = new VM(decodeBytecode(BYTECODE), MAIN_START_PC, CONSTANTS, globals);
771
+ vm.run();