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
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
// tsrun Raw WASM API Wrapper
//
// This module provides a JavaScript wrapper around the raw WASM FFI exports.
// It implements the host functions and provides a TsRunner-like API.
// Step status constants (matching TsRunStepStatus in Rust)
export const STEP_CONTINUE = 0;
export const STEP_COMPLETE = 1;
export const STEP_NEED_IMPORTS = 2;
export const STEP_SUSPENDED = 3;
export const STEP_DONE = 4;
export const STEP_ERROR = 5;
// Value type constants (matching TsRunType in Rust)
export const TYPE_UNDEFINED = 0;
export const TYPE_NULL = 1;
export const TYPE_BOOLEAN = 2;
export const TYPE_NUMBER = 3;
export const TYPE_STRING = 4;
export const TYPE_OBJECT = 5;
export const TYPE_SYMBOL = 6;
// Console level constants
export const CONSOLE_LOG = 0;
export const CONSOLE_INFO = 1;
export const CONSOLE_DEBUG = 2;
export const CONSOLE_WARN = 3;
export const CONSOLE_ERROR = 4;
// Private symbols for internal state
const _wasm = Symbol('wasm');
const _memory = Symbol('memory');
const _context = Symbol('context');
const _consoleBuffer = Symbol('consoleBuffer');
const _pendingOrders = Symbol('pendingOrders');
const _importRequests = Symbol('importRequests');
// RegExp handle storage for host-side regex objects
const regexHandles = new Map();
let nextRegexHandle = 1;
/**
* Initialize the tsrun WASM module.
* @param {string|URL|Request} [wasmPath] - Path to the WASM file (defaults to 'tsrun.wasm')
* @returns {Promise<typeof TsRunner>} - The TsRunner class ready to use
*/
export async function init(wasmPath = 'tsrun.wasm') {
// Performance timer state (per-instance would be better but simplified here)
const timerStart = performance.now();
// Console buffer for current TsRunner instance (set during instantiation)
let activeConsoleBuffer = null;
// Host imports that the WASM module expects
const hostImports = {
tsrun_host: {
// Get current time in milliseconds since Unix epoch
host_time_now() {
return BigInt(Date.now());
},
// Start a performance timer (returns opaque handle)
host_time_start_timer() {
return BigInt(Math.floor(performance.now() * 1e6)); // Convert to nanoseconds as u64
},
// Get elapsed milliseconds since timer start
host_time_elapsed(start) {
const startMs = Number(start) / 1e6;
const elapsed = performance.now() - startMs;
return BigInt(Math.floor(elapsed));
},
// Generate random float in [0, 1)
host_random() {
return Math.random();
},
// Write to console
host_console_write(level, ptr, len) {
if (!wasmInstance) return;
const memory = wasmInstance.exports.memory;
const bytes = new Uint8Array(memory.buffer, ptr, len);
const message = textDecoder.decode(bytes);
const levelName = ['log', 'info', 'debug', 'warn', 'error'][level] || 'log';
// Always log to browser console for debugging
console[levelName]('[WASM]', message);
// Also buffer for result if buffer is active
if (activeConsoleBuffer) {
activeConsoleBuffer.push({ level: levelName, message });
}
},
// Clear console
host_console_clear() {
if (activeConsoleBuffer) {
activeConsoleBuffer.push({ level: 'clear', message: '--- Console cleared ---' });
}
},
// ================================================================
// RegExp Host Functions
// ================================================================
// Compile a regex pattern with flags
host_regex_compile(patternPtr, patternLen, flagsPtr, flagsLen, errorPtrOut, errorLenOut) {
const memory = wasmInstance.exports.memory;
const pattern = textDecoder.decode(new Uint8Array(memory.buffer, patternPtr, patternLen));
const flags = textDecoder.decode(new Uint8Array(memory.buffer, flagsPtr, flagsLen));
try {
const regex = new RegExp(pattern, flags);
const handle = nextRegexHandle++;
regexHandles.set(handle, { regex, pattern, flags });
return handle;
} catch (e) {
// Write error to WASM memory
const errorMsg = textEncoder.encode(e.message);
const errorPtr = wasmInstance.exports.tsrun_alloc(errorMsg.length);
// Get fresh buffer reference after allocation (memory may have grown)
new Uint8Array(wasmInstance.exports.memory.buffer, errorPtr, errorMsg.length).set(errorMsg);
const view = new DataView(wasmInstance.exports.memory.buffer);
view.setUint32(errorPtrOut, errorPtr, true);
view.setUint32(errorLenOut, errorMsg.length, true);
return 0;
}
},
// Free a compiled regex handle
host_regex_free(handle) {
regexHandles.delete(handle);
},
// Test if regex matches input string
host_regex_test(handle, inputPtr, inputLen) {
try {
const entry = regexHandles.get(handle);
if (!entry) return 0;
const memory = wasmInstance.exports.memory;
const input = textDecoder.decode(new Uint8Array(memory.buffer, inputPtr, inputLen));
// Reset lastIndex for consistent behavior
entry.regex.lastIndex = 0;
return entry.regex.test(input) ? 1 : 0;
} catch (e) {
console.error('[host_regex_test] Error:', e);
return 0;
}
},
// Execute regex and return match info via binary protocol
host_regex_exec(handle, inputPtr, inputLen, startPos, matchStartOut, matchEndOut, capturesPtrOut, capturesCountOut) {
try {
const entry = regexHandles.get(handle);
if (!entry) return 0;
const memory = wasmInstance.exports.memory;
const fullInput = textDecoder.decode(new Uint8Array(memory.buffer, inputPtr, inputLen));
// Search from startPos
const inputFromStart = fullInput.slice(startPos);
// Create a non-global regex for single match
const searchRegex = new RegExp(entry.pattern, entry.flags.replace('g', ''));
const match = searchRegex.exec(inputFromStart);
if (!match) {
return 0; // Not found
}
// Calculate offsets
const matchStart = startPos + match.index;
const matchEnd = matchStart + match[0].length;
// Build captures array: pairs of i32 (start, end), -1 for non-participating
const capturesCount = match.length;
const capturesBytes = capturesCount * 2 * 4; // pairs of i32
// IMPORTANT: Allocate FIRST, then get fresh DataView
// Memory might grow during allocation, invalidating any previous views
const capturesPtr = wasmInstance.exports.tsrun_alloc(capturesBytes);
// Get fresh view AFTER allocation (memory may have grown)
let view = new DataView(wasmInstance.exports.memory.buffer);
// NOW write all output parameters with the fresh view
view.setUint32(matchStartOut, matchStart, true);
view.setUint32(matchEndOut, matchEnd, true);
for (let i = 0; i < capturesCount; i++) {
const offset = capturesPtr + i * 8;
if (match[i] === undefined) {
view.setInt32(offset, -1, true);
view.setInt32(offset + 4, -1, true);
} else if (i === 0) {
view.setInt32(offset, matchStart, true);
view.setInt32(offset + 4, matchEnd, true);
} else {
// For capture groups, find their position
const groupText = match[i];
const groupIdx = inputFromStart.indexOf(groupText, match.index);
if (groupIdx >= 0) {
view.setInt32(offset, startPos + groupIdx, true);
view.setInt32(offset + 4, startPos + groupIdx + groupText.length, true);
} else {
view.setInt32(offset, -1, true);
view.setInt32(offset + 4, -1, true);
}
}
}
view.setUint32(capturesPtrOut, capturesPtr, true);
view.setUint32(capturesCountOut, capturesCount, true);
return 1; // Found
} catch (e) {
console.error('[host_regex_exec] Error:', e);
return 0;
}
},
// Free captures array
host_free_captures(ptr, count) {
if (ptr !== 0 && count > 0) {
wasmInstance.exports.tsrun_dealloc(ptr, count * 2 * 4);
}
},
// Replace matches with replacement string
host_regex_replace(handle, inputPtr, inputLen, replPtr, replLen, global, resultPtrOut, resultLenOut) {
try {
const entry = regexHandles.get(handle);
if (!entry) return 0;
const memory = wasmInstance.exports.memory;
const input = textDecoder.decode(new Uint8Array(memory.buffer, inputPtr, inputLen));
const replacement = textDecoder.decode(new Uint8Array(memory.buffer, replPtr, replLen));
// Build regex with correct flags
let flags = entry.flags;
if (global && !flags.includes('g')) {
flags += 'g';
} else if (!global) {
flags = flags.replace('g', '');
}
const replaceRegex = new RegExp(entry.pattern, flags);
const result = input.replace(replaceRegex, replacement);
const bytes = textEncoder.encode(result);
const ptr = wasmInstance.exports.tsrun_alloc(bytes.length);
new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes);
new DataView(wasmInstance.exports.memory.buffer).setUint32(resultPtrOut, ptr, true);
new DataView(wasmInstance.exports.memory.buffer).setUint32(resultLenOut, bytes.length, true);
return 1;
} catch (e) {
console.error('[host_regex_replace] Error:', e);
return 0;
}
},
// Split input by regex matches - returns binary array of (ptr, len) pairs
host_regex_split(handle, inputPtr, inputLen, partsPtrOut, partsCountOut) {
try {
const entry = regexHandles.get(handle);
if (!entry) return 0;
const memory = wasmInstance.exports.memory;
const input = textDecoder.decode(new Uint8Array(memory.buffer, inputPtr, inputLen));
const parts = input.split(entry.regex);
const partsCount = parts.length;
// Allocate array of (ptr: u32, len: u32) pairs
const arrayBytes = partsCount * 2 * 4;
const arrayPtr = wasmInstance.exports.tsrun_alloc(arrayBytes);
let view = new DataView(wasmInstance.exports.memory.buffer);
// Allocate each string and write to array
for (let i = 0; i < partsCount; i++) {
const bytes = textEncoder.encode(parts[i]);
const strPtr = wasmInstance.exports.tsrun_alloc(bytes.length || 1); // At least 1 byte
if (bytes.length > 0) {
new Uint8Array(wasmInstance.exports.memory.buffer, strPtr, bytes.length).set(bytes);
}
// Write (ptr, len) pair - get fresh view after each alloc
view = new DataView(wasmInstance.exports.memory.buffer);
view.setUint32(arrayPtr + i * 8, strPtr, true);
view.setUint32(arrayPtr + i * 8 + 4, bytes.length, true);
}
view = new DataView(wasmInstance.exports.memory.buffer);
view.setUint32(partsPtrOut, arrayPtr, true);
view.setUint32(partsCountOut, partsCount, true);
return 1;
} catch (e) {
console.error('[host_regex_split] Error:', e);
return 0;
}
},
// Free split result: the parts array and all strings within it
host_free_split_result(partsPtr, partsCount) {
if (partsPtr === 0 || partsCount === 0) return;
const view = new DataView(wasmInstance.exports.memory.buffer);
// Free each string
for (let i = 0; i < partsCount; i++) {
const strPtr = view.getUint32(partsPtr + i * 8, true);
const strLen = view.getUint32(partsPtr + i * 8 + 4, true);
if (strPtr !== 0) {
wasmInstance.exports.tsrun_dealloc(strPtr, strLen || 1);
}
}
// Free the array itself
wasmInstance.exports.tsrun_dealloc(partsPtr, partsCount * 2 * 4);
},
// Free a host-allocated string
host_free_string(ptr, len) {
if (ptr !== 0 && len > 0) {
wasmInstance.exports.tsrun_dealloc(ptr, len);
}
}
}
};
// Load and instantiate the WASM module
const wasmResponse = await fetch(wasmPath);
const wasmBytes = await wasmResponse.arrayBuffer();
const { instance } = await WebAssembly.instantiate(wasmBytes, hostImports);
const wasmInstance = instance;
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
/**
* Allocate memory in WASM and write a string to it.
* @param {string} str - The string to allocate
* @returns {{ptr: number, len: number}} - Pointer and length (excluding null terminator)
*/
function allocString(str) {
const bytes = textEncoder.encode(str);
const len = bytes.length;
const ptr = wasmInstance.exports.tsrun_alloc(len + 1); // +1 for null terminator
if (ptr === 0) throw new Error('Failed to allocate memory for string');
const memory = new Uint8Array(wasmInstance.exports.memory.buffer);
memory.set(bytes, ptr);
memory[ptr + len] = 0; // null terminator
return { ptr, len };
}
/**
* Deallocate memory in WASM.
* @param {number} ptr - Pointer to free
* @param {number} size - Size of allocation
*/
function deallocString(ptr, size) {
if (ptr !== 0 && size > 0) {
wasmInstance.exports.tsrun_dealloc(ptr, size);
}
}
/**
* Read a null-terminated string from WASM memory.
* @param {number} ptr - Pointer to string
* @returns {string}
*/
function readString(ptr) {
if (ptr === 0) return '';
const memory = new Uint8Array(wasmInstance.exports.memory.buffer);
let end = ptr;
while (memory[end] !== 0) end++;
return textDecoder.decode(memory.slice(ptr, end));
}
/**
* Read a DataView from WASM memory.
* @param {number} ptr - Start pointer
* @param {number} len - Length in bytes
* @returns {DataView}
*/
function getDataView(ptr, len) {
return new DataView(wasmInstance.exports.memory.buffer, ptr, len);
}
/**
* TsRunner class - wraps the raw WASM FFI.
*/
class TsRunner {
constructor() {
this[_wasm] = wasmInstance;
this[_memory] = wasmInstance.exports.memory;
this[_consoleBuffer] = [];
this[_pendingOrders] = [];
this[_importRequests] = [];
// Create interpreter context using WASM-specific constructor
this[_context] = wasmInstance.exports.tsrun_wasm_new();
if (this[_context] === 0) {
throw new Error('Failed to create tsrun context');
}
}
/**
* Free the context and release resources.
*/
free() {
if (this[_context] !== 0) {
this[_wasm].exports.tsrun_free(this[_context]);
this[_context] = 0;
}
// Clean up all regex handles to prevent memory leaks across TsRunner instances
regexHandles.clear();
nextRegexHandle = 1;
}
/**
* Prepare code for execution.
* @param {string} code - TypeScript/JavaScript source code
* @param {string} [filename] - Optional filename for error messages
* @returns {{status: number, error?: string, console_output: Array}}
*/
prepare(code, filename = 'script.ts') {
// Set active console buffer for host callbacks
activeConsoleBuffer = this[_consoleBuffer];
this[_consoleBuffer] = [];
this[_pendingOrders] = [];
this[_importRequests] = [];
try {
const codeAlloc = allocString(code);
const filenameAlloc = filename ? allocString(filename) : { ptr: 0, len: 0 };
// Allocate result struct: TsRunResult = { ok: i32, error: i32 } = 8 bytes
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
if (resultPtr === 0) throw new Error('Failed to allocate result memory');
try {
// Call tsrun_prepare(sret, ctx, code, path)
this[_wasm].exports.tsrun_prepare(resultPtr, this[_context], codeAlloc.ptr, filenameAlloc.ptr);
// Parse result
const view = getDataView(resultPtr, 8);
const ok = view.getUint32(0, true);
const errorPtr = view.getUint32(4, true);
if (ok === 0) {
const error = readString(errorPtr);
return {
status: STEP_ERROR,
error: `Parse error: ${error}`,
console_output: this[_consoleBuffer].splice(0)
};
}
return {
status: STEP_CONTINUE,
console_output: this[_consoleBuffer].splice(0)
};
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
deallocString(codeAlloc.ptr, codeAlloc.len + 1);
if (filenameAlloc.ptr) deallocString(filenameAlloc.ptr, filenameAlloc.len + 1);
}
} finally {
activeConsoleBuffer = null;
}
}
/**
* Execute one step.
* @returns {{status: number, value_handle?: number, error?: string, console_output: Array}}
*/
step() {
activeConsoleBuffer = this[_consoleBuffer];
try {
// Allocate TsRunStepResult: 36 bytes
const resultPtr = this[_wasm].exports.tsrun_alloc(36);
if (resultPtr === 0) throw new Error('Failed to allocate step result memory');
try {
this[_wasm].exports.tsrun_step(resultPtr, this[_context]);
return this._parseStepResult(resultPtr);
} finally {
// Free internal arrays but not value
this[_wasm].exports.tsrun_step_result_free(resultPtr);
this[_wasm].exports.tsrun_dealloc(resultPtr, 36);
}
} finally {
activeConsoleBuffer = null;
}
}
/**
* Execute until completion, needing imports, or suspension.
* @returns {{status: number, value_handle?: number, error?: string, console_output: Array}}
*/
run() {
activeConsoleBuffer = this[_consoleBuffer];
try {
const resultPtr = this[_wasm].exports.tsrun_alloc(36);
if (resultPtr === 0) throw new Error('Failed to allocate run result memory');
try {
this[_wasm].exports.tsrun_run(resultPtr, this[_context]);
return this._parseStepResult(resultPtr);
} finally {
this[_wasm].exports.tsrun_step_result_free(resultPtr);
this[_wasm].exports.tsrun_dealloc(resultPtr, 36);
}
} finally {
activeConsoleBuffer = null;
}
}
/**
* Parse TsRunStepResult from memory.
* @private
*/
_parseStepResult(resultPtr) {
// TsRunStepResult layout (wasm32):
// offset 0: status (i32)
// offset 4: value (i32 pointer)
// offset 8: imports (i32 pointer)
// offset 12: import_count (i32)
// offset 16: pending_orders (i32 pointer)
// offset 20: pending_count (i32)
// offset 24: cancelled_orders (i32 pointer)
// offset 28: cancelled_count (i32)
// offset 32: error (i32 pointer)
const view = getDataView(resultPtr, 36);
const status = view.getUint32(0, true);
const valuePtr = view.getUint32(4, true);
const importsPtr = view.getUint32(8, true);
const importCount = view.getUint32(12, true);
const pendingPtr = view.getUint32(16, true);
const pendingCount = view.getUint32(20, true);
const cancelledPtr = view.getUint32(24, true);
const cancelledCount = view.getUint32(28, true);
const errorPtr = view.getUint32(32, true);
const result = {
status,
value_handle: 0,
console_output: this[_consoleBuffer].splice(0)
};
switch (status) {
case STEP_COMPLETE:
result.value_handle = valuePtr;
break;
case STEP_ERROR:
result.error = readString(errorPtr);
break;
case STEP_NEED_IMPORTS:
this[_importRequests] = this._parseImportRequests(importsPtr, importCount);
break;
case STEP_SUSPENDED:
this[_pendingOrders] = this._parsePendingOrders(pendingPtr, pendingCount);
break;
}
return result;
}
/**
* Parse import requests from memory.
* @private
*/
_parseImportRequests(ptr, count) {
if (ptr === 0 || count === 0) return [];
// TsRunImportRequest: { specifier: i32, resolved_path: i32, importer: i32 } = 12 bytes
const requests = [];
for (let i = 0; i < count; i++) {
const view = getDataView(ptr + i * 12, 12);
const specifierPtr = view.getUint32(0, true);
const resolvedPtr = view.getUint32(4, true);
const importerPtr = view.getUint32(8, true);
requests.push({
specifier: readString(specifierPtr),
resolved_path: readString(resolvedPtr),
importer: readString(importerPtr)
});
}
return requests;
}
/**
* Parse pending orders from memory.
* @private
*/
_parsePendingOrders(ptr, count) {
if (ptr === 0 || count === 0) return [];
// TsRunOrder: { id: u64, payload: i32 } = 12 bytes (8 + 4 on wasm32)
const orders = [];
for (let i = 0; i < count; i++) {
const view = getDataView(ptr + i * 12, 12);
const id = view.getBigUint64(0, true);
const payloadPtr = view.getUint32(8, true);
orders.push({
id: Number(id),
payload_handle: payloadPtr
});
}
return orders;
}
// ═══════════════════════════════════════════════════════════════════════════════
// Order/Import API
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Get pending order IDs (after STEP_SUSPENDED).
* @returns {number[]}
*/
get_pending_order_ids() {
return this[_pendingOrders].map(o => o.id);
}
/**
* Get the payload handle for a pending order.
* @param {number} orderId
* @returns {number}
*/
get_order_payload(orderId) {
const order = this[_pendingOrders].find(o => o.id === orderId);
return order ? order.payload_handle : 0;
}
/**
* Get import request specifiers (after STEP_NEED_IMPORTS).
* @returns {string[]}
*/
get_import_requests() {
return this[_importRequests].map(r => r.specifier);
}
/**
* Fulfill orders with values.
* @param {Array<{id: number, value?: number, error?: string}>} responses
*/
fulfill_orders(responses) {
// Build array of TsRunOrderResponse structs
// TsRunOrderResponse: { id: u64, value: i32, error: i32 } = 16 bytes
const count = responses.length;
if (count === 0) return;
const arrayPtr = this[_wasm].exports.tsrun_alloc(count * 16);
if (arrayPtr === 0) throw new Error('Failed to allocate order responses');
const allocatedErrors = [];
try {
for (let i = 0; i < count; i++) {
const resp = responses[i];
const offset = arrayPtr + i * 16;
// Get fresh DataView after any potential memory growth
const memory = new DataView(this[_wasm].exports.memory.buffer);
// Write id as u64
memory.setBigUint64(offset, BigInt(resp.id), true);
// Write value pointer
memory.setUint32(offset + 8, resp.value || 0, true);
// Write error pointer
let errorPtr = 0;
if (resp.error) {
const alloc = allocString(resp.error);
errorPtr = alloc.ptr;
allocatedErrors.push(alloc);
}
// Get fresh DataView after potential memory growth from allocString
new DataView(this[_wasm].exports.memory.buffer).setUint32(offset + 12, errorPtr, true);
}
// Allocate result struct for sret
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
if (resultPtr === 0) throw new Error('Failed to allocate result');
try {
this[_wasm].exports.tsrun_fulfill_orders(resultPtr, this[_context], arrayPtr, count);
// Check result
const view = getDataView(resultPtr, 8);
const ok = view.getUint32(0, true);
if (ok === 0) {
const errPtr = view.getUint32(4, true);
throw new Error(`fulfill_orders failed: ${readString(errPtr)}`);
}
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
} finally {
this[_wasm].exports.tsrun_dealloc(arrayPtr, count * 16);
for (const alloc of allocatedErrors) {
deallocString(alloc.ptr, alloc.len + 1);
}
}
this[_pendingOrders] = [];
}
/**
* Set result for a single order (queued until commit_fulfillments).
* @param {number} orderId
* @param {number} resultHandle
*/
set_order_result(orderId, resultHandle) {
this._queuedFulfillments = this._queuedFulfillments || [];
this._queuedFulfillments.push({ id: orderId, value: resultHandle });
}
/**
* Set error for a single order (queued until commit_fulfillments).
* @param {number} orderId
* @param {string} errorMsg
*/
set_order_error(orderId, errorMsg) {
this._queuedFulfillments = this._queuedFulfillments || [];
this._queuedFulfillments.push({ id: orderId, error: errorMsg });
}
/**
* Commit queued fulfillments.
*/
commit_fulfillments() {
if (!this._queuedFulfillments || this._queuedFulfillments.length === 0) return;
this.fulfill_orders(this._queuedFulfillments);
this._queuedFulfillments = [];
}
/**
* Provide a module source.
* @param {string} path - Module path
* @param {string} source - Module source code
*/
provide_module(path, source) {
const pathAlloc = allocString(path);
const sourceAlloc = allocString(source);
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_provide_module(resultPtr, this[_context], pathAlloc.ptr, sourceAlloc.ptr);
const view = getDataView(resultPtr, 8);
const ok = view.getUint32(0, true);
if (ok === 0) {
const errPtr = view.getUint32(4, true);
throw new Error(`provide_module failed: ${readString(errPtr)}`);
}
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
deallocString(pathAlloc.ptr, pathAlloc.len + 1);
deallocString(sourceAlloc.ptr, sourceAlloc.len + 1);
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Promise API
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Create an unresolved Promise.
* @returns {number} Promise handle
*/
create_promise() {
// Allocate result struct: TsRunValueResult = { value: i32, error: i32 } = 8 bytes
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
if (resultPtr === 0) throw new Error('Failed to allocate result');
try {
this[_wasm].exports.tsrun_create_order_promise(resultPtr, this[_context], BigInt(0));
const view = getDataView(resultPtr, 8);
const valuePtr = view.getUint32(0, true);
const errorPtr = view.getUint32(4, true);
if (valuePtr === 0 && errorPtr !== 0) {
throw new Error(`create_promise failed: ${readString(errorPtr)}`);
}
return valuePtr;
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
}
/**
* Resolve a Promise with a value.
* @param {number} promiseHandle
* @param {number} valueHandle
*/
resolve_promise(promiseHandle, valueHandle) {
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
if (resultPtr === 0) throw new Error('Failed to allocate result');
try {
this[_wasm].exports.tsrun_resolve_promise(resultPtr, this[_context], promiseHandle, valueHandle);
const view = getDataView(resultPtr, 8);
const ok = view.getUint32(0, true);
if (ok === 0) {
const errPtr = view.getUint32(4, true);
throw new Error(`resolve_promise failed: ${readString(errPtr)}`);
}
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
}
/**
* Reject a Promise with an error.
* @param {number} promiseHandle
* @param {string} errorMsg
*/
reject_promise(promiseHandle, errorMsg) {
const errorAlloc = allocString(errorMsg);
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_reject_promise(resultPtr, this[_context], promiseHandle, errorAlloc.ptr);
const view = getDataView(resultPtr, 8);
const ok = view.getUint32(0, true);
if (ok === 0) {
const errPtr = view.getUint32(4, true);
throw new Error(`reject_promise failed: ${readString(errPtr)}`);
}
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
deallocString(errorAlloc.ptr, errorAlloc.len + 1);
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Value Creation
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Create a number value.
* @param {number} n
* @returns {number} Value handle
*/
create_number(n) {
return this[_wasm].exports.tsrun_number(this[_context], n);
}
/**
* Create a string value.
* @param {string} s
* @returns {number} Value handle
*/
create_string(s) {
const alloc = allocString(s);
try {
return this[_wasm].exports.tsrun_string(this[_context], alloc.ptr);
} finally {
deallocString(alloc.ptr, alloc.len + 1);
}
}
/**
* Create a boolean value.
* @param {boolean} b
* @returns {number} Value handle
*/
create_bool(b) {
return this[_wasm].exports.tsrun_boolean(this[_context], b ? 1 : 0);
}
/**
* Create null value.
* @returns {number} Value handle
*/
create_null() {
return this[_wasm].exports.tsrun_null(this[_context]);
}
/**
* Create undefined value.
* @returns {number} Value handle
*/
create_undefined() {
return this[_wasm].exports.tsrun_undefined(this[_context]);
}
/**
* Create an empty object.
* @returns {number} Value handle
*/
create_object() {
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
if (resultPtr === 0) throw new Error('Failed to allocate result');
try {
this[_wasm].exports.tsrun_object_new(resultPtr, this[_context]);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true);
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
}
/**
* Create an empty array.
* @returns {number} Value handle
*/
create_array() {
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
if (resultPtr === 0) throw new Error('Failed to allocate result');
try {
this[_wasm].exports.tsrun_array_new(resultPtr, this[_context]);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true);
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Value Inspection
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Get the type of a value.
* @param {number} handle
* @returns {string}
*/
get_value_type(handle) {
if (handle === 0) return 'undefined';
const type = this[_wasm].exports.tsrun_typeof(handle);
return ['undefined', 'null', 'boolean', 'number', 'string', 'object', 'symbol'][type] || 'undefined';
}
/**
* Get value as number.
* @param {number} handle
* @returns {number}
*/
value_as_number(handle) {
if (handle === 0) return NaN;
return this[_wasm].exports.tsrun_get_number(handle);
}
/**
* Get value as string.
* @param {number} handle
* @returns {string|undefined}
*/
value_as_string(handle) {
if (handle === 0) return undefined;
const ptr = this[_wasm].exports.tsrun_get_string(handle);
if (ptr === 0) return undefined;
return readString(ptr);
}
/**
* Get value as boolean.
* @param {number} handle
* @returns {boolean|undefined}
*/
value_as_bool(handle) {
if (handle === 0) return undefined;
if (!this[_wasm].exports.tsrun_is_boolean(handle)) return undefined;
return this[_wasm].exports.tsrun_get_bool(handle) !== 0;
}
/**
* Check if value is null.
* @param {number} handle
* @returns {boolean}
*/
value_is_null(handle) {
return handle !== 0 && this[_wasm].exports.tsrun_is_null(handle) !== 0;
}
/**
* Check if value is undefined.
* @param {number} handle
* @returns {boolean}
*/
value_is_undefined(handle) {
return handle === 0 || this[_wasm].exports.tsrun_is_undefined(handle) !== 0;
}
/**
* Check if value is an array.
* @param {number} handle
* @returns {boolean}
*/
value_is_array(handle) {
return handle !== 0 && this[_wasm].exports.tsrun_is_array(handle) !== 0;
}
/**
* Check if value is a function.
* @param {number} handle
* @returns {boolean}
*/
value_is_function(handle) {
return handle !== 0 && this[_wasm].exports.tsrun_is_function(handle) !== 0;
}
// ═══════════════════════════════════════════════════════════════════════════════
// Object Operations
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Get a property from an object.
* @param {number} objHandle
* @param {string} key
* @returns {number} Value handle
*/
get_property(objHandle, key) {
const keyAlloc = allocString(key);
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_get(resultPtr, this[_context], objHandle, keyAlloc.ptr);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true);
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
deallocString(keyAlloc.ptr, keyAlloc.len + 1);
}
}
/**
* Set a property on an object.
* @param {number} objHandle
* @param {string} key
* @param {number} valueHandle
* @returns {boolean}
*/
set_property(objHandle, key, valueHandle) {
const keyAlloc = allocString(key);
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_set(resultPtr, this[_context], objHandle, keyAlloc.ptr, valueHandle);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true) !== 0;
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
deallocString(keyAlloc.ptr, keyAlloc.len + 1);
}
}
/**
* Get all property keys of an object.
* @param {number} objHandle
* @returns {string[]}
*/
get_keys(objHandle) {
// tsrun_keys returns pointer to array of C strings + count via out params
// For simplicity, use JSON stringify then parse to get keys
const json = this.json_stringify(objHandle);
if (!json) return [];
try {
const obj = JSON.parse(json);
return Object.keys(obj);
} catch {
return [];
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Array Operations
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Get array length.
* @param {number} arrHandle
* @returns {number}
*/
array_length(arrHandle) {
if (arrHandle === 0) return 0;
return this[_wasm].exports.tsrun_array_len(arrHandle);
}
/**
* Get array element by index.
* @param {number} arrHandle
* @param {number} index
* @returns {number} Value handle
*/
get_index(arrHandle, index) {
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_array_get(resultPtr, this[_context], arrHandle, index);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true);
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
}
/**
* Push a value onto an array.
* @param {number} arrHandle
* @param {number} valueHandle
* @returns {boolean}
*/
push(arrHandle, valueHandle) {
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_array_push(resultPtr, this[_context], arrHandle, valueHandle);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true) !== 0;
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// JSON Operations
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Parse JSON string into a value.
* @param {string} json
* @returns {number} Value handle
*/
json_parse(json) {
const jsonAlloc = allocString(json);
const resultPtr = this[_wasm].exports.tsrun_alloc(8);
try {
this[_wasm].exports.tsrun_json_parse(resultPtr, this[_context], jsonAlloc.ptr);
const view = getDataView(resultPtr, 8);
return view.getUint32(0, true);
} finally {
this[_wasm].exports.tsrun_dealloc(resultPtr, 8);
deallocString(jsonAlloc.ptr, jsonAlloc.len + 1);
}
}
/**
* Stringify a value to JSON.
* @param {number} handle
* @returns {string|null}
*/
json_stringify(handle) {
const ptr = this[_wasm].exports.tsrun_json_stringify(this[_context], handle);
if (ptr === 0) return null;
const result = readString(ptr);
this[_wasm].exports.tsrun_free_string(ptr);
return result;
}
// ═══════════════════════════════════════════════════════════════════════════════
// Value Memory Management
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Free a value handle.
* @param {number} handle
*/
release_handle(handle) {
if (handle !== 0) {
this[_wasm].exports.tsrun_value_free(handle);
}
}
}
return TsRunner;
}
// Default export for convenience
export default init;