-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemnapi-core.js
More file actions
8602 lines (8581 loc) · 432 KB
/
emnapi-core.js
File metadata and controls
8602 lines (8581 loc) · 432 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.emnapiCore = {}));
})(this, (function (exports) {
/* eslint-disable no-undef */
var _WebAssembly$1 = typeof WebAssembly !== 'undefined'
? WebAssembly
: typeof WXWebAssembly !== 'undefined'
? WXWebAssembly
: undefined;
function validateImports(imports) {
if (imports && typeof imports !== 'object') {
throw new TypeError('imports must be an object or undefined');
}
return true;
}
function load(wasmInput, imports) {
if (!wasmInput)
throw new TypeError('Invalid wasm source');
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
// Promise<string | URL | Response | BufferSource | WebAssembly.Module>
try {
var then = typeof wasmInput === 'object' && wasmInput !== null && 'then' in wasmInput ? wasmInput.then : undefined;
if (typeof then === 'function') {
return then.call(wasmInput, function (input) { return load(input, imports); });
}
}
catch (_) { }
// BufferSource
if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) {
return _WebAssembly$1.instantiate(wasmInput, imports);
}
// WebAssembly.Module
if (wasmInput instanceof _WebAssembly$1.Module) {
return _WebAssembly$1.instantiate(wasmInput, imports).then(function (instance) {
return { instance: instance, module: wasmInput };
});
}
// Response
if (typeof Response !== 'undefined' && wasmInput instanceof Response) {
return wasmInput.arrayBuffer().then(function (buffer) {
return _WebAssembly$1.instantiate(buffer, imports);
});
}
// string | URL
var inputIsString = typeof wasmInput === 'string';
if (inputIsString || (typeof URL !== 'undefined' && wasmInput instanceof URL)) {
if (inputIsString && typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') {
return _WebAssembly$1.instantiate(wasmInput, imports);
}
if (typeof fetch !== 'function') {
throw new TypeError('wasm source can not be a string or URL in this environment');
}
if (typeof _WebAssembly$1.instantiateStreaming === 'function') {
try {
return _WebAssembly$1.instantiateStreaming(fetch(wasmInput), imports).catch(function () {
return load(fetch(wasmInput), imports);
});
}
catch (_) {
return load(fetch(wasmInput), imports);
}
}
else {
return load(fetch(wasmInput), imports);
}
}
throw new TypeError('Invalid wasm source');
}
function loadSync(wasmInput, imports) {
if (!wasmInput)
throw new TypeError('Invalid wasm source');
validateImports(imports);
imports = imports !== null && imports !== void 0 ? imports : {};
var module;
if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) {
module = new _WebAssembly$1.Module(wasmInput);
}
else if (wasmInput instanceof WebAssembly.Module) {
module = wasmInput;
}
else {
throw new TypeError('Invalid wasm source');
}
var instance = new _WebAssembly$1.Instance(module, imports);
var source = { instance: instance, module: module };
return source;
}
var _WebAssembly = typeof WebAssembly !== 'undefined'
? WebAssembly
: typeof WXWebAssembly !== 'undefined'
? WXWebAssembly
: undefined;
var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null &&
typeof process.versions === 'object' && process.versions !== null &&
typeof process.versions.node === 'string';
function getPostMessage(options) {
return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function'
? options.postMessage
: typeof postMessage === 'function'
? postMessage
: undefined;
}
function serizeErrorToBuffer(sab, code, error) {
var i32array = new Int32Array(sab);
Atomics.store(i32array, 0, code);
if (code > 1 && error) {
var name_1 = error.name;
var message = error.message;
var stack = error.stack;
var nameBuffer = new TextEncoder().encode(name_1);
var messageBuffer = new TextEncoder().encode(message);
var stackBuffer = new TextEncoder().encode(stack);
Atomics.store(i32array, 1, nameBuffer.length);
Atomics.store(i32array, 2, messageBuffer.length);
Atomics.store(i32array, 3, stackBuffer.length);
var buffer = new Uint8Array(sab);
buffer.set(nameBuffer, 16);
buffer.set(messageBuffer, 16 + nameBuffer.length);
buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length);
}
}
function deserizeErrorFromBuffer(sab) {
var _a, _b;
var i32array = new Int32Array(sab);
var status = Atomics.load(i32array, 0);
if (status <= 1) {
return null;
}
var nameLength = Atomics.load(i32array, 1);
var messageLength = Atomics.load(i32array, 2);
var stackLength = Atomics.load(i32array, 3);
var buffer = new Uint8Array(sab);
var nameBuffer = buffer.slice(16, 16 + nameLength);
var messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength);
var stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength);
var name = new TextDecoder().decode(nameBuffer);
var message = new TextDecoder().decode(messageBuffer);
var stack = new TextDecoder().decode(stackBuffer);
var ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error);
var error = new ErrorConstructor(message);
Object.defineProperty(error, 'stack', {
value: stack,
writable: true,
enumerable: false,
configurable: true
});
return error;
}
/** @public */
function isSharedArrayBuffer(value) {
return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) ||
(Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'));
}
/** @public */
function isTrapError(e) {
try {
return e instanceof _WebAssembly.RuntimeError;
}
catch (_) {
return false;
}
}
function createMessage(type, payload) {
return {
__emnapi__: {
type: type,
payload: payload
}
};
}
var WASI_THREADS_MAX_TID = 0x1FFFFFFF;
function checkSharedWasmMemory(wasmMemory) {
if (wasmMemory) {
if (!isSharedArrayBuffer(wasmMemory.buffer)) {
throw new Error('Multithread features require shared wasm memory. ' +
'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' +
'then create WebAssembly.Memory with `shared: true` option');
}
}
else {
if (typeof SharedArrayBuffer === 'undefined') {
throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!');
}
}
}
function getReuseWorker(value) {
var _a;
if (typeof value === 'boolean') {
return value ? { size: 0, strict: false } : false;
}
if (typeof value === 'number') {
if (!(value >= 0)) {
throw new RangeError('reuseWorker: size must be a non-negative integer');
}
return { size: value, strict: false };
}
if (!value) {
return false;
}
var size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0;
var strict = Boolean(value.strict);
if (!(size > 0) && strict) {
throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true');
}
return { size: size, strict: strict };
}
var nextWorkerID = 0;
/** @public */
var ThreadManager = /*#__PURE__*/ (function () {
function ThreadManager(options) {
var _a;
this.unusedWorkers = [];
this.runningWorkers = [];
this.pthreads = Object.create(null);
this.wasmModule = null;
this.wasmMemory = null;
this.messageEvents = new WeakMap();
if (!options) {
throw new TypeError('ThreadManager(): options is not provided');
}
if ('childThread' in options) {
this._childThread = Boolean(options.childThread);
}
else {
this._childThread = false;
}
if (this._childThread) {
this._onCreateWorker = undefined;
this._reuseWorker = false;
this._beforeLoad = undefined;
}
else {
this._onCreateWorker = options.onCreateWorker;
this._reuseWorker = getReuseWorker(options.reuseWorker);
this._beforeLoad = options.beforeLoad;
}
this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console);
}
Object.defineProperty(ThreadManager.prototype, "nextWorkerID", {
get: function () { return nextWorkerID; },
enumerable: false,
configurable: true
});
ThreadManager.prototype.init = function () {
if (!this._childThread) {
this.initMainThread();
}
};
ThreadManager.prototype.initMainThread = function () {
this.preparePool();
};
ThreadManager.prototype.preparePool = function () {
if (this._reuseWorker) {
if (this._reuseWorker.size) {
var pthreadPoolSize = this._reuseWorker.size;
while (pthreadPoolSize--) {
var worker = this.allocateUnusedWorker();
if (ENVIRONMENT_IS_NODE) {
// https://github.com/nodejs/node/issues/53036
worker.once('message', function () { });
worker.unref();
}
}
}
}
};
ThreadManager.prototype.shouldPreloadWorkers = function () {
return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0;
};
ThreadManager.prototype.loadWasmModuleToAllWorkers = function () {
var _this_1 = this;
var promises = Array(this.unusedWorkers.length);
var _loop_1 = function (i) {
var worker = this_1.unusedWorkers[i];
if (ENVIRONMENT_IS_NODE)
worker.ref();
promises[i] = this_1.loadWasmModuleToWorker(worker).then(function (w) {
if (ENVIRONMENT_IS_NODE)
worker.unref();
return w;
}, function (e) {
if (ENVIRONMENT_IS_NODE)
worker.unref();
throw e;
});
};
var this_1 = this;
for (var i = 0; i < this.unusedWorkers.length; ++i) {
_loop_1(i);
}
return Promise.all(promises).catch(function (err) {
_this_1.terminateAllThreads();
throw err;
});
};
ThreadManager.prototype.preloadWorkers = function () {
if (this.shouldPreloadWorkers()) {
return this.loadWasmModuleToAllWorkers();
}
return Promise.resolve([]);
};
ThreadManager.prototype.setup = function (wasmModule, wasmMemory) {
this.wasmModule = wasmModule;
this.wasmMemory = wasmMemory;
};
ThreadManager.prototype.markId = function (worker) {
if (worker.__emnapi_tid)
return worker.__emnapi_tid;
var tid = nextWorkerID + 43;
nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42);
this.pthreads[tid] = worker;
worker.__emnapi_tid = tid;
return tid;
};
ThreadManager.prototype.returnWorkerToPool = function (worker) {
var tid = worker.__emnapi_tid;
if (tid !== undefined) {
delete this.pthreads[tid];
}
this.unusedWorkers.push(worker);
this.runningWorkers.splice(this.runningWorkers.indexOf(worker), 1);
delete worker.__emnapi_tid;
if (ENVIRONMENT_IS_NODE) {
worker.unref();
}
};
ThreadManager.prototype.loadWasmModuleToWorker = function (worker, sab) {
var _this_1 = this;
if (worker.whenLoaded)
return worker.whenLoaded;
var err = this.printErr;
var beforeLoad = this._beforeLoad;
// eslint-disable-next-line @typescript-eslint/no-this-alias
var _this = this;
worker.whenLoaded = new Promise(function (resolve, reject) {
var handleError = function (e) {
var message = 'worker sent an error!';
if (worker.__emnapi_tid !== undefined) {
message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!';
}
if ('message' in e) {
err(message + ' ' + e.message);
if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) {
try {
_this.terminateAllThreads();
}
catch (_) { }
}
}
else {
err(message);
}
reject(e);
throw e;
};
var handleMessage = function (data) {
if (data.__emnapi__) {
var type = data.__emnapi__.type;
var payload = data.__emnapi__.payload;
if (type === 'loaded') {
worker.loaded = true;
if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) {
worker.unref();
}
resolve(worker);
// if (payload.err) {
// err('failed to load in child thread: ' + (payload.err.message || payload.err))
// }
}
else if (type === 'cleanup-thread') {
if (payload.tid in _this_1.pthreads) {
_this_1.cleanThread(worker, payload.tid);
}
}
}
};
worker.onmessage = function (e) {
handleMessage(e.data);
_this_1.fireMessageEvent(worker, e);
};
worker.onerror = handleError;
if (ENVIRONMENT_IS_NODE) {
worker.on('message', function (data) {
var _a, _b;
(_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, {
data: data
});
});
worker.on('error', function (e) {
var _a, _b;
(_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e);
});
worker.on('detachedExit', function () { });
}
if (typeof beforeLoad === 'function') {
beforeLoad(worker);
}
try {
worker.postMessage(createMessage('load', {
wasmModule: _this_1.wasmModule,
wasmMemory: _this_1.wasmMemory,
sab: sab
}));
}
catch (err) {
checkSharedWasmMemory(_this_1.wasmMemory);
throw err;
}
});
return worker.whenLoaded;
};
ThreadManager.prototype.allocateUnusedWorker = function () {
var _onCreateWorker = this._onCreateWorker;
if (typeof _onCreateWorker !== 'function') {
throw new TypeError('`options.onCreateWorker` is not provided');
}
var worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' });
this.unusedWorkers.push(worker);
return worker;
};
ThreadManager.prototype.getNewWorker = function (sab) {
if (this._reuseWorker) {
if (this.unusedWorkers.length === 0) {
if (this._reuseWorker.strict) {
if (!ENVIRONMENT_IS_NODE) {
var err = this.printErr;
err('Tried to spawn a new thread, but the thread pool is exhausted.\n' +
'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.');
return;
}
}
var worker_1 = this.allocateUnusedWorker();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.loadWasmModuleToWorker(worker_1, sab);
}
return this.unusedWorkers.pop();
}
var worker = this.allocateUnusedWorker();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.loadWasmModuleToWorker(worker, sab);
return this.unusedWorkers.pop();
};
ThreadManager.prototype.cleanThread = function (worker, tid, force) {
if (!force && this._reuseWorker) {
this.returnWorkerToPool(worker);
}
else {
delete this.pthreads[tid];
var index = this.runningWorkers.indexOf(worker);
if (index !== -1) {
this.runningWorkers.splice(index, 1);
}
this.terminateWorker(worker);
delete worker.__emnapi_tid;
}
};
ThreadManager.prototype.terminateWorker = function (worker) {
var _this_1 = this;
var _a;
var tid = worker.__emnapi_tid;
// eslint-disable-next-line @typescript-eslint/no-floating-promises
worker.terminate();
(_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear();
this.messageEvents.delete(worker);
worker.onmessage = function (e) {
if (e.data.__emnapi__) {
var err = _this_1.printErr;
err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid);
}
};
};
ThreadManager.prototype.terminateAllThreads = function () {
for (var i = 0; i < this.runningWorkers.length; ++i) {
this.terminateWorker(this.runningWorkers[i]);
}
for (var i = 0; i < this.unusedWorkers.length; ++i) {
this.terminateWorker(this.unusedWorkers[i]);
}
this.unusedWorkers = [];
this.runningWorkers = [];
this.pthreads = Object.create(null);
this.preparePool();
};
ThreadManager.prototype.addMessageEventListener = function (worker, onMessage) {
var listeners = this.messageEvents.get(worker);
if (!listeners) {
listeners = new Set();
this.messageEvents.set(worker, listeners);
}
listeners.add(onMessage);
return function () {
listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage);
};
};
ThreadManager.prototype.fireMessageEvent = function (worker, e) {
var listeners = this.messageEvents.get(worker);
if (!listeners)
return;
var err = this.printErr;
listeners.forEach(function (listener) {
try {
listener(e);
}
catch (e) {
err(e.stack);
}
});
};
return ThreadManager;
}());
var kIsProxy = Symbol('kIsProxy');
/** @public */
function createInstanceProxy(instance, memory) {
if (instance[kIsProxy])
return instance;
// https://github.com/nodejs/help/issues/4102
var originalExports = instance.exports;
var createHandler = function (target) {
var handlers = [
'apply',
'construct',
'defineProperty',
'deleteProperty',
'get',
'getOwnPropertyDescriptor',
'getPrototypeOf',
'has',
'isExtensible',
'ownKeys',
'preventExtensions',
'set',
'setPrototypeOf'
];
var handler = {};
var _loop_1 = function (i) {
var name_1 = handlers[i];
handler[name_1] = function () {
var args = Array.prototype.slice.call(arguments, 1);
args.unshift(target);
return Reflect[name_1].apply(Reflect, args);
};
};
for (var i = 0; i < handlers.length; i++) {
_loop_1(i);
}
return handler;
};
var handler = createHandler(originalExports);
var _initialize = function () { };
var _start = function () { return 0; };
handler.get = function (_target, p, receiver) {
var _a;
if (p === 'memory') {
return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver);
}
if (p === '_initialize') {
return p in originalExports ? _initialize : undefined;
}
if (p === '_start') {
return p in originalExports ? _start : undefined;
}
return Reflect.get(originalExports, p, receiver);
};
handler.has = function (_target, p) {
if (p === 'memory')
return true;
return Reflect.has(originalExports, p);
};
var exportsProxy = new Proxy(Object.create(null), handler);
return new Proxy(instance, {
get: function (target, p, receiver) {
if (p === 'exports') {
return exportsProxy;
}
if (p === kIsProxy) {
return true;
}
return Reflect.get(target, p, receiver);
}
});
}
var patchedWasiInstances = new WeakMap();
/** @public */
var WASIThreads = /*#__PURE__*/ (function () {
function WASIThreads(options) {
var _this_1 = this;
if (!options) {
throw new TypeError('WASIThreads(): options is not provided');
}
if (!options.wasi) {
throw new TypeError('WASIThreads(): options.wasi is not provided');
}
patchedWasiInstances.set(this, new WeakSet());
var wasi = options.wasi;
patchWasiInstance(this, wasi);
this.wasi = wasi;
if ('childThread' in options) {
this.childThread = Boolean(options.childThread);
}
else {
this.childThread = false;
}
this.PThread = undefined;
if ('threadManager' in options) {
if (typeof options.threadManager === 'function') {
this.PThread = options.threadManager();
}
else {
this.PThread = options.threadManager;
}
}
else {
if (!this.childThread) {
this.PThread = new ThreadManager(options);
this.PThread.init();
}
}
var waitThreadStart = false;
if ('waitThreadStart' in options) {
waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart);
}
var postMessage = getPostMessage(options);
if (this.childThread && typeof postMessage !== 'function') {
throw new TypeError('options.postMessage is not a function');
}
this.postMessage = postMessage;
var wasm64 = Boolean(options.wasm64);
var onMessage = function (e) {
if (e.data.__emnapi__) {
var type = e.data.__emnapi__.type;
var payload = e.data.__emnapi__.payload;
if (type === 'spawn-thread') {
threadSpawn(payload.startArg, payload.errorOrTid);
}
else if (type === 'terminate-all-threads') {
_this_1.terminateAllThreads();
}
}
};
var threadSpawn = function (startArg, errorOrTid) {
var _a;
var EAGAIN = 6;
var isNewABI = errorOrTid !== undefined;
try {
checkSharedWasmMemory(_this_1.wasmMemory);
}
catch (err) {
(_a = _this_1.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack);
if (isNewABI) {
var struct_1 = new Int32Array(_this_1.wasmMemory.buffer, errorOrTid, 2);
Atomics.store(struct_1, 0, 1);
Atomics.store(struct_1, 1, EAGAIN);
Atomics.notify(struct_1, 1);
return 1;
}
else {
return -EAGAIN;
}
}
if (!isNewABI) {
var malloc = _this_1.wasmInstance.exports.malloc;
errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : malloc(8);
if (!errorOrTid) {
return -48; /* ENOMEM */
}
}
var _free = _this_1.wasmInstance.exports.free;
var free = wasm64 ? function (ptr) { _free(BigInt(ptr)); } : _free;
var struct = new Int32Array(_this_1.wasmMemory.buffer, errorOrTid, 2);
Atomics.store(struct, 0, 0);
Atomics.store(struct, 1, 0);
if (_this_1.childThread) {
postMessage(createMessage('spawn-thread', {
startArg: startArg,
errorOrTid: errorOrTid
}));
Atomics.wait(struct, 1, 0);
var isError = Atomics.load(struct, 0);
var result = Atomics.load(struct, 1);
if (isNewABI) {
return isError;
}
free(errorOrTid);
return isError ? -result : result;
}
var shouldWait = waitThreadStart || (waitThreadStart === 0);
var sab;
if (shouldWait) {
sab = new Int32Array(new SharedArrayBuffer(16 + 8192));
Atomics.store(sab, 0, 0);
}
var worker;
var tid;
var PThread = _this_1.PThread;
try {
worker = PThread.getNewWorker(sab);
if (!worker) {
throw new Error('failed to get new worker');
}
PThread.addMessageEventListener(worker, onMessage);
tid = PThread.markId(worker);
if (ENVIRONMENT_IS_NODE) {
worker.ref();
}
worker.postMessage(createMessage('start', {
tid: tid,
arg: startArg,
sab: sab
}));
if (shouldWait) {
if (typeof waitThreadStart === 'number') {
var waitResult = Atomics.wait(sab, 0, 0, waitThreadStart);
if (waitResult === 'timed-out') {
try {
PThread.cleanThread(worker, tid, true);
}
catch (_) { }
throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.');
}
}
else {
Atomics.wait(sab, 0, 0);
}
var r = Atomics.load(sab, 0);
if (r > 1) {
try {
PThread.cleanThread(worker, tid, true);
}
catch (_) { }
throw deserizeErrorFromBuffer(sab.buffer);
}
}
}
catch (e) {
Atomics.store(struct, 0, 1);
Atomics.store(struct, 1, EAGAIN);
Atomics.notify(struct, 1);
PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack);
if (isNewABI) {
return 1;
}
free(errorOrTid);
return -EAGAIN;
}
Atomics.store(struct, 0, 0);
Atomics.store(struct, 1, tid);
Atomics.notify(struct, 1);
PThread.runningWorkers.push(worker);
if (!shouldWait) {
worker.whenLoaded.catch(function (err) {
delete worker.whenLoaded;
PThread.cleanThread(worker, tid, true);
throw err;
});
}
if (isNewABI) {
return 0;
}
free(errorOrTid);
return tid;
};
this.threadSpawn = threadSpawn;
}
WASIThreads.prototype.getImportObject = function () {
return {
wasi: {
'thread-spawn': this.threadSpawn
}
};
};
WASIThreads.prototype.setup = function (wasmInstance, wasmModule, wasmMemory) {
wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory);
this.wasmInstance = wasmInstance;
this.wasmMemory = wasmMemory;
if (this.PThread) {
this.PThread.setup(wasmModule, wasmMemory);
}
};
WASIThreads.prototype.preloadWorkers = function () {
if (this.PThread) {
return this.PThread.preloadWorkers();
}
return Promise.resolve([]);
};
/**
* It's ok to call this method to a WASI command module.
*
* in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module
*
* @returns A proxied WebAssembly instance if in child thread, other wise the original instance
*/
WASIThreads.prototype.initialize = function (instance, module, memory) {
var exports$1 = instance.exports;
memory !== null && memory !== void 0 ? memory : (memory = exports$1.memory);
if (this.childThread) {
instance = createInstanceProxy(instance, memory);
}
this.setup(instance, module, memory);
var wasi = this.wasi;
if (('_start' in exports$1) && (typeof exports$1._start === 'function')) {
if (this.childThread) {
wasi.start(instance);
try {
var kStarted = getWasiSymbol(wasi, 'kStarted');
wasi[kStarted] = false;
}
catch (_) { }
}
else {
setupInstance(wasi, instance);
}
}
else {
wasi.initialize(instance);
}
return instance;
};
/**
* Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start}
* ```js
* this.initialize(instance, module, memory)
* this.wasi.start(instance)
* ```
*/
WASIThreads.prototype.start = function (instance, module, memory) {
var exports$1 = instance.exports;
memory !== null && memory !== void 0 ? memory : (memory = exports$1.memory);
if (this.childThread) {
instance = createInstanceProxy(instance, memory);
}
this.setup(instance, module, memory);
var exitCode = this.wasi.start(instance);
return { exitCode: exitCode, instance: instance };
};
WASIThreads.prototype.terminateAllThreads = function () {
var _a;
if (!this.childThread) {
(_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads();
}
else {
this.postMessage(createMessage('terminate-all-threads', {}));
}
};
return WASIThreads;
}());
function patchWasiInstance(wasiThreads, wasi) {
var patched = patchedWasiInstances.get(wasiThreads);
if (patched.has(wasi)) {
return;
}
var _this = wasiThreads;
var wasiImport = wasi.wasiImport;
if (wasiImport) {
var proc_exit_1 = wasiImport.proc_exit;
wasiImport.proc_exit = function (code) {
_this.terminateAllThreads();
return proc_exit_1.call(this, code);
};
}
if (!_this.childThread) {
var start_1 = wasi.start;
if (typeof start_1 === 'function') {
wasi.start = function (instance) {
try {
return start_1.call(this, instance);
}
catch (err) {
if (isTrapError(err)) {
_this.terminateAllThreads();
}
throw err;
}
};
}
}
patched.add(wasi);
}
function getWasiSymbol(wasi, description) {
var symbols = Object.getOwnPropertySymbols(wasi);
var selectDescription = function (description) { return function (s) {
if (s.description) {
return s.description === description;
}
return s.toString() === "Symbol(".concat(description, ")");
}; };
if (Array.isArray(description)) {
return description.map(function (d) { return symbols.filter(selectDescription(d))[0]; });
}
return symbols.filter(selectDescription(description))[0];
}
function setupInstance(wasi, instance) {
var _a = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']), kInstance = _a[0], kSetMemory = _a[1];
wasi[kInstance] = instance;
wasi[kSetMemory](instance.exports.memory);
}
/** @public */
var ThreadMessageHandler = /*#__PURE__*/ (function () {
function ThreadMessageHandler(options) {
var postMsg = getPostMessage(options);
if (typeof postMsg !== 'function') {
throw new TypeError('options.postMessage is not a function');
}
this.postMessage = postMsg;
this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad;
this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : function (_type, err) { throw err; };
this.instance = undefined;
// this.module = undefined
this.messagesBeforeLoad = [];
}
/** @virtual */
ThreadMessageHandler.prototype.instantiate = function (data) {
if (typeof this.onLoad === 'function') {
return this.onLoad(data);
}
throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented');
};
/** @virtual */
ThreadMessageHandler.prototype.handle = function (e) {
var _this = this;
var _a;
if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) {
var type = e.data.__emnapi__.type;
var payload_1 = e.data.__emnapi__.payload;
try {
if (type === 'load') {
this._load(payload_1);
}
else if (type === 'start') {
this.handleAfterLoad(e, function () {
_this._start(payload_1);
});
}
}
catch (err) {
this.onError(err, type);
}
}
};
ThreadMessageHandler.prototype._load = function (payload) {
var _this = this;
if (this.instance !== undefined)
return;
var source;
try {
source = this.instantiate(payload);
}
catch (err) {
this._loaded(err, null, payload);
return;
}
var then = source && 'then' in source ? source.then : undefined;
if (typeof then === 'function') {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
then.call(source, function (source) { _this._loaded(null, source, payload); }, function (err) { _this._loaded(err, null, payload); });
}
else {
this._loaded(null, source, payload);
}
};
ThreadMessageHandler.prototype._start = function (payload) {
var wasi_thread_start = this.instance.exports.wasi_thread_start;
if (typeof wasi_thread_start !== 'function') {
var err = new TypeError('wasi_thread_start is not exported');
notifyPthreadCreateResult(payload.sab, 2, err);
throw err;
}
var postMessage = this.postMessage;
var tid = payload.tid;
var startArg = payload.arg;
notifyPthreadCreateResult(payload.sab, 1);
try {
wasi_thread_start(tid, startArg);
}
catch (err) {
if (err !== 'unwind') {
throw err;
}
else {
return;
}
}
postMessage(createMessage('cleanup-thread', { tid: tid }));
};
ThreadMessageHandler.prototype._loaded = function (err, source, payload) {
if (err) {
notifyPthreadCreateResult(payload.sab, 2, err);
throw err;
}
if (source == null) {
var err_1 = new TypeError('onLoad should return an object');
notifyPthreadCreateResult(payload.sab, 2, err_1);