@emnapi/wasi-threads 1.2.1 → 2.0.0

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