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