@medicomind/rolldown-compression-wasm32-wasi 2.5.3 → 2.6.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.
@@ -2,6 +2,56 @@
2
2
  /* eslint-disable */
3
3
  /* auto-generated by NAPI-RS */
4
4
 
5
+ const __napiBindingTarget = 'wasm32-wasi'
6
+ function __napiStampBindingTarget(exportsObject, target) {
7
+ if (
8
+ Object.prototype.hasOwnProperty.call(exportsObject, '__napiBindingTarget')
9
+ ) {
10
+ if (exportsObject.__napiBindingTarget === target) {
11
+ // Already ours: the root entry aliases the object it loaded, so a WASI
12
+ // fallback candidate — or a `NAPI_RS_NATIVE_LIBRARY_PATH` override that
13
+ // is a generated loader — arrives already stamped with this same value.
14
+ return target
15
+ }
16
+ const error = new Error(
17
+ '`__napiBindingTarget` is reserved by the generated binding loader, but the loaded binding already exports it. Rename the export, e.g. #[napi(js_name = "...")].',
18
+ )
19
+ error.code = 'ERR_NAPI_BINDING_TARGET_CONFLICT'
20
+ throw error
21
+ }
22
+ if (!Object.isExtensible(exportsObject)) {
23
+ // A `#[napi(module_exports)]` hook may seal or freeze this object
24
+ // (`Object::seal` / `Object::freeze`). Reporting the artifact is metadata,
25
+ // never a reason to fail an otherwise successful load, so the stamp is
26
+ // skipped. What a consumer still sees then follows the entry point: the
27
+ // browser and deferred loaders declare `__napiBindingTarget` at module
28
+ // level and go on reporting it, while the CommonJS entries hand back this
29
+ // very object as `module.exports`, so there the value is absent.
30
+ return target
31
+ }
32
+ try {
33
+ // [[Define]], not [[Set]]: an ordinary assignment walks the prototype
34
+ // chain, so an inherited accessor could swallow the value or throw and
35
+ // fail an otherwise successful load. The descriptor is what a successful
36
+ // assignment would have produced.
37
+ Object.defineProperty(exportsObject, '__napiBindingTarget', {
38
+ configurable: true,
39
+ enumerable: true,
40
+ value: target,
41
+ writable: true,
42
+ })
43
+ } catch {
44
+ // Same rule as the non-extensible skip above: reporting the artifact is
45
+ // metadata, never a reason to fail an otherwise successful load. An exotic
46
+ // object (a Proxy whose defineProperty trap refuses) is skipped, not
47
+ // thrown over.
48
+ }
49
+ // The CommonJS loaders assign this return value so `cjs-module-lexer` — and
50
+ // therefore Node's CJS -> ESM named export detection — can see
51
+ // `__napiBindingTarget` statically.
52
+ return target
53
+ }
54
+
5
55
  const __nodeFs = require('node:fs')
6
56
  const __nodePath = require('node:path')
7
57
  const { WASI: __nodeWASI } = require('node:wasi')
@@ -89,7 +139,13 @@ function __createWasiWorker(filename) {
89
139
  return new Worker(filename, {
90
140
  env: process.env,
91
141
  execArgv: __workerExecArgv,
92
- workerData: { hostRoot: __hostRoot, rootDir: __rootDir },
142
+ workerData: {
143
+ hostRoot: __hostRoot,
144
+ rootDir: __rootDir,
145
+ crashFlag: __wasiThreadCrashFlag,
146
+ crashReport: __wasiThreadCrashReport,
147
+ addonCrashFlag: __wasiAddonCrashFlag,
148
+ },
93
149
  })
94
150
  } catch (error) {
95
151
  if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
@@ -105,6 +161,454 @@ function __createWasiWorker(filename) {
105
161
  }
106
162
  }
107
163
 
164
+ // Set to 1 by a pool worker (see wasi-worker.mjs) right before it reports that
165
+ // its wasm thread died. Shared memory, so this thread reads it synchronously even
166
+ // while the worker's 'error' event is still queued behind the code that is
167
+ // exiting right now.
168
+ const __wasiThreadCrashFlag = new Int32Array(new SharedArrayBuffer(4))
169
+ // Written by the first pool worker whose wasm thread dies, before it raises the
170
+ // flag: its error and `threadId` (layout in wasi-worker.mjs). Read without
171
+ // waiting for any event, see `__readWasiThreadCrashReport`.
172
+ const __wasiThreadCrashReport = new SharedArrayBuffer(4096)
173
+ let __wasiThreadCrashReportRead
174
+ // The first error a pool worker reported through its 'error' event, and that
175
+ // worker's `threadId`. See `__getWasiThreadCrashError`.
176
+ let __wasiThreadCrashWorkerError
177
+ let __wasiThreadCrashWorkerId
178
+ let __wasiThreadCrashError
179
+ // Raised while `__runWasiInitializationRollbackSteps` runs, so its polls and
180
+ // steps stop after a crash the way a public disposal's do.
181
+ let __wasiInitializationRollbackActive = false
182
+ let __wasiThreadCrashed = false
183
+
184
+ // A view of the addon's crash flag, one word of the shared wasm memory, for the
185
+ // pool workers: they raise it when their wasm thread dies, and the shutdown
186
+ // waits inside the cleanup calls on this thread then trap instead of waiting on
187
+ // the dead thread for good. Undefined for an addon built with an older napi.
188
+ let __wasiAddonCrashFlag
189
+
190
+ function __captureWasiAddonCrashFlag(instance) {
191
+ try {
192
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
193
+ if (typeof getAddress !== 'function') {
194
+ return
195
+ }
196
+ const address = getAddress() >>> 0
197
+ const buffer = __sharedMemory.buffer
198
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
199
+ return
200
+ }
201
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
202
+ } catch {}
203
+ }
204
+
205
+ /**
206
+ * Whether any wasm thread of this binding has died: a trap or an uncaught error
207
+ * in a pool worker, including one that failed to load after its thread spawn
208
+ * had already been reported as started.
209
+ *
210
+ * After that the shared wasm state cannot be trusted: a lock the dead thread
211
+ * held stays held, and a join or park that waits on it — the async runtime's
212
+ * `finish_shutdown` waiting for the dead thread's work to go idle — blocks
213
+ * this thread forever in a raw `memory.atomic.wait32`, which neither
214
+ * emnapi's crash check nor a signal can interrupt.
215
+ */
216
+ function __hasWasiThreadCrashed() {
217
+ if (__wasiThreadCrashed || Atomics.load(__wasiThreadCrashFlag, 0) !== 0) {
218
+ return true
219
+ }
220
+ const manager = __getWasiThreadManager()
221
+ return Boolean(manager && manager._fatalError)
222
+ }
223
+
224
+ let __wasiThreadCrashDisposePromise
225
+ // Raised by the crash disposal right before it terminates the workers. See
226
+ // `__wasiSetImmediate`.
227
+ let __wasiReentryClosed = false
228
+
229
+ /**
230
+ * emnapi's `features.setImmediate` for this binding's context. emnapi defers
231
+ * its calls back into wasm through it: `_emnapi_set_immediate` (libuv handle
232
+ * closes, threadsafe-function finalizers), threadsafe-function dispatch
233
+ * (`async-send`) and the finalizer queue. One queued before a crash disposal
234
+ * terminates the workers still runs after it, and a worker terminated while it
235
+ * held a lock in the wasm heap (napi's heap-sync allocator lock spins and never
236
+ * gives up) leaves that call spinning on this thread for good. The binding is
237
+ * unusable after a crash disposal, so those calls are dropped.
238
+ *
239
+ * Known residual, still able to enter wasm after a crash disposal because emnapi
240
+ * offers no hook for them: the `FinalizationRegistry` callbacks that free
241
+ * external memory when GC collects a value (`_free`, the shared-buffer meta
242
+ * release), threadsafe-function dispatch of `async-send` type 1 and
243
+ * `_emnapi_next_tick` (both `Promise.resolve().then`), and every deferred
244
+ * call under emnapi 1.x, whose `createContext` ignores `features`.
245
+ */
246
+ function __wasiSetImmediate(callback) {
247
+ return setImmediate(function () {
248
+ if (!__wasiReentryClosed) {
249
+ callback()
250
+ }
251
+ })
252
+ }
253
+
254
+ /**
255
+ * Stores the first error a pool worker reported, with the worker's id. Called
256
+ * from the loader's own 'error' listener, which runs before emnapi's.
257
+ */
258
+ function __recordWasiThreadCrashError(error, workerId) {
259
+ if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
260
+ return
261
+ }
262
+ __wasiThreadCrashWorkerError = error
263
+ __wasiThreadCrashWorkerId = workerId
264
+ __fillWasiThreadCrashError()
265
+ }
266
+
267
+ /**
268
+ * The error in the shared crash report, rebuilt once it is complete: the
269
+ * worker writes it before it raises the flag, so it is there as soon as the
270
+ * crash is seen. Plain JavaScript over shared memory; never enters wasm.
271
+ */
272
+ function __readWasiThreadCrashReport() {
273
+ if (__wasiThreadCrashReportRead !== undefined) {
274
+ return __wasiThreadCrashReportRead
275
+ }
276
+ try {
277
+ const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
278
+ if (Atomics.load(header, 0) !== 2) {
279
+ return
280
+ }
281
+ const length = Atomics.load(header, 1)
282
+ const threadId = Atomics.load(header, 2)
283
+ let error
284
+ if (length > 0) {
285
+ // Copied out of shared memory: TextDecoder does not take a shared view.
286
+ const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
287
+ const report = JSON.parse(new TextDecoder().decode(bytes))
288
+ error = new Error(String(report.message))
289
+ if (typeof report.name === 'string') {
290
+ error.name = report.name
291
+ }
292
+ if (typeof report.stack === 'string') {
293
+ error.stack = report.stack
294
+ }
295
+ }
296
+ __wasiThreadCrashReportRead = { error, threadId }
297
+ } catch {
298
+ __wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
299
+ }
300
+ return __wasiThreadCrashReportRead
301
+ }
302
+
303
+ /**
304
+ * The one error every crash path of this binding reports, created on first
305
+ * use.
306
+ *
307
+ * The shared flag is raised before this thread has processed the worker's
308
+ * 'error' event, and once the workers are terminated that event is often
309
+ * never delivered, so neither it nor emnapi's `_fatalError` can be counted
310
+ * on. The cause is filled in from the first source that has it: the error the
311
+ * 'error' listener kept, else the worker's shared crash report, else
312
+ * `_fatalError` — here, and again from the 'error' listener when it arrives
313
+ * later. Until then the error carries only its message.
314
+ */
315
+ function __getWasiThreadCrashError() {
316
+ if (__wasiThreadCrashError === undefined) {
317
+ __wasiThreadCrashError = new Error(
318
+ 'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
319
+ )
320
+ }
321
+ __fillWasiThreadCrashError()
322
+ return __wasiThreadCrashError
323
+ }
324
+
325
+ function __fillWasiThreadCrashError() {
326
+ const crashError = __wasiThreadCrashError
327
+ if (crashError === undefined) {
328
+ return
329
+ }
330
+ try {
331
+ if (crashError.cause === undefined) {
332
+ let cause = __wasiThreadCrashWorkerError
333
+ if (cause === undefined) {
334
+ const report = __readWasiThreadCrashReport()
335
+ cause = report ? report.error : undefined
336
+ }
337
+ if (cause === undefined) {
338
+ const manager = __getWasiThreadManager()
339
+ cause = manager ? manager._fatalError : undefined
340
+ }
341
+ if (cause !== undefined && cause !== null) {
342
+ crashError.cause = cause
343
+ }
344
+ }
345
+ if (crashError.workerThreadId === undefined) {
346
+ let workerId = __wasiThreadCrashWorkerId
347
+ if (workerId === undefined) {
348
+ const report = __readWasiThreadCrashReport()
349
+ workerId = report && report.threadId > 0 ? report.threadId : undefined
350
+ }
351
+ if (workerId !== undefined) {
352
+ crashError.workerThreadId = workerId
353
+ }
354
+ }
355
+ } catch {}
356
+ }
357
+
358
+ /**
359
+ * Let the event loop drain after a wasm thread died, without entering wasm.
360
+ *
361
+ * emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
362
+ * `MessagePort` (`refCounter.refHandle`) that it refs when the count of
363
+ * in-flight async work and threadsafe-function requests leaves zero and unrefs
364
+ * when it comes back. The requests the dead thread held never complete, so the
365
+ * count never returns to zero and the port holds the process open for good.
366
+ * `Context.destroy()` would not release it either — and it runs cleanup
367
+ * hooks, which is exactly what must not happen now. So unref the port directly.
368
+ * The count is left as is: it stays above zero, so a later request never refs
369
+ * the port again.
370
+ *
371
+ * The field is private in emnapi's typings, so read it defensively; a context
372
+ * without it (a non-Node host, a future emnapi) is left alone.
373
+ */
374
+ function __releaseEmnapiWaitingRequestHandle() {
375
+ try {
376
+ const refCounter = __emnapiContext && __emnapiContext.refCounter
377
+ const refHandle = refCounter && refCounter.refHandle
378
+ if (refHandle && typeof refHandle.unref === 'function') {
379
+ refHandle.unref()
380
+ }
381
+ } catch {}
382
+ }
383
+
384
+ /**
385
+ * The public disposer after a wasm thread died. The normal chain drains async
386
+ * work, runs the environment cleanup barrier and destroys the context — every
387
+ * one of those re-enters wasm, and the barrier's shutdown waits for the dead
388
+ * thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
389
+ * avoids. An app that handled the worker's error and then disposes would block
390
+ * there for good. Only stop the workers, then reject: the binding was not
391
+ * cleaned up and cannot be, so reporting success would be a lie. The context
392
+ * is not destroyed — only its waiting-request port is unrefed, so the process
393
+ * can exit on its own — and the 'exit' listener takes its short path too.
394
+ *
395
+ * Latched: every later call returns the same promise.
396
+ */
397
+ function __disposeWasiBindingAfterThreadCrash() {
398
+ if (__wasiThreadCrashDisposePromise) {
399
+ return __wasiThreadCrashDisposePromise
400
+ }
401
+ __releaseEmnapiWaitingRequestHandle()
402
+ // No call into wasm after this: see `__wasiSetImmediate`.
403
+ __wasiReentryClosed = true
404
+ let workerResult
405
+ try {
406
+ workerResult = __terminateWasiWorkers()
407
+ } catch (terminateError) {
408
+ workerResult = Promise.reject(terminateError)
409
+ }
410
+ // Built at settlement, after the workers stopped: by then the 'error' event
411
+ // has usually delivered the worker's error.
412
+ __wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
413
+ () => {
414
+ throw __getWasiThreadCrashError()
415
+ },
416
+ (terminateError) => {
417
+ throw __attachCleanupErrors(__getWasiThreadCrashError(), [
418
+ terminateError,
419
+ ])
420
+ },
421
+ )
422
+ return __wasiThreadCrashDisposePromise
423
+ }
424
+
425
+ /**
426
+ * Stops a public disposal that a thread crash overtook.
427
+ *
428
+ * The check at the top of `__disposeWasiBinding` only sees a crash that came
429
+ * first. A thread that dies once the chain is running leaves it polling for
430
+ * work the dead thread still counts — the async-work drain for
431
+ * `napi_wasm_async_work_pending`, the barrier's poll for
432
+ * `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
433
+ * the poll's referenced timers keep the process alive forever with the
434
+ * disposal promise pending. Each poll turn and each step boundary calls this,
435
+ * and the throw ends the chain before anything re-enters wasm again; the
436
+ * disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
437
+ *
438
+ * The initialization rollback runs the same polls and steps, so they stop while
439
+ * it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
440
+ * through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
441
+ * neither in flight is left alone.
442
+ */
443
+ function __abortWasiDisposalIfThreadCrashed() {
444
+ if (
445
+ (__wasiDisposePromise !== undefined ||
446
+ __wasiInitializationRollbackActive) &&
447
+ __hasWasiThreadCrashed()
448
+ ) {
449
+ throw new Error(
450
+ 'napi-rs: WASI disposal stopped because a worker thread crashed',
451
+ )
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Settles an in-flight public disposal whose chain failed after a thread
457
+ * died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
458
+ * way — through the crash disposal: it releases the waiting-request port,
459
+ * terminates the workers and rejects with the same error an entry-time crash
460
+ * gets. `__wasiDisposePromise` stays set, so this caller, every caller that
461
+ * joined it and every later one hold the same promise. Returns false when no
462
+ * thread died, leaving the ordinary failure handling alone.
463
+ */
464
+ function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
465
+ if (!__hasWasiThreadCrashed()) {
466
+ return false
467
+ }
468
+ __disposeWasiBindingAfterThreadCrash().then(resolve, reject)
469
+ return true
470
+ }
471
+
472
+ /**
473
+ * Ends an initialization rollback after a wasm thread died, without entering
474
+ * wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
475
+ * crash disposal releases the waiting-request port and terminates the workers,
476
+ * once. The initialization error itself is left to propagate: the crash error
477
+ * is returned as the rollback's cleanup error, so
478
+ * `__completeWasiInitializationRollback` attaches it — as the cause when the
479
+ * error has none — and keeps the record, since the context was not destroyed.
480
+ */
481
+ function __rollbackWasiInitializationAfterThreadCrash() {
482
+ const crashError = __getWasiThreadCrashError()
483
+ // Its rejection is `crashError` itself, which the caller reports.
484
+ void __disposeWasiBindingAfterThreadCrash().catch(() => {})
485
+ return [crashError]
486
+ }
487
+
488
+ const __wasiThreadPoolReconcileSymbol = Symbol.for('napi.rs.wasi.reconcileThreadPool')
489
+
490
+ /**
491
+ * Takes a Worker out of emnapi's reuse pool, if it is still there. emnapi
492
+ * terminates a pooled Worker that failed to load but (up to
493
+ * @emnapi/wasi-threads 2.1.0) leaves it in the pool, where the next thread
494
+ * spawn would pop it. A newer emnapi removes it itself, so this is a no-op
495
+ * then.
496
+ */
497
+ function __removeWasiPoolWorker(manager, worker) {
498
+ const index = manager.unusedWorkers.indexOf(worker)
499
+ if (index !== -1) {
500
+ manager.unusedWorkers.splice(index, 1)
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Takes a Worker the thread manager just terminated out of `__wasiWorkers`
506
+ * once it has exited, not before. `terminateWorker` only starts Node's
507
+ * asynchronous `worker.terminate()` and drops its promise, so a disposal that
508
+ * begins before the exit has to find this Worker in the set and wait for it
509
+ * like any other. A second `terminate()` settles when the Worker has exited,
510
+ * the way `__terminateWasiWorkers` waits.
511
+ */
512
+ function __untrackWasiWorkerOnExit(worker) {
513
+ const terminated = worker.terminate()
514
+ if (__isThenable(terminated)) {
515
+ Promise.resolve(terminated).then(
516
+ () => {
517
+ __wasiWorkers.delete(worker)
518
+ },
519
+ // Left tracked: disposal terminates it again and reports the error.
520
+ () => {},
521
+ )
522
+ } else {
523
+ __wasiWorkers.delete(worker)
524
+ }
525
+ }
526
+
527
+ /**
528
+ * Matches emnapi's idle reuse pool to the addon's configured MultiThread worker
529
+ * count, which the addon exports as `napi_wasm_runtime_pool_workers`
530
+ * (napi-async-runtime; 0 under CurrentThread). `reuseWorker: true` starts the
531
+ * pool empty, so without this every pool thread the first async call spawns
532
+ * boots a Worker and loads the wasm into it first. Here each missing Worker is
533
+ * created and starts loading now; a spawn later pops one that is already
534
+ * booting. Idle Workers above the count are terminated, last in first out,
535
+ * the way a spawn takes them. A Worker a spawn already took is not in the pool
536
+ * and is left alone.
537
+ *
538
+ * Runs once after a successful load and, when the loader wraps it, after every
539
+ * successful `configureAsyncRuntime`. Also reachable as
540
+ * binding[Symbol.for('napi.rs.wasi.reconcileThreadPool')]().
541
+ * It never throws and never waits on a Worker: a Worker whose load fails is
542
+ * dropped from the pool when its load rejects. Nothing at all happens after a
543
+ * thread crash, once disposal started, or for an addon without the export.
544
+ */
545
+ function __reconcileWasiThreadPool() {
546
+ try {
547
+ if (__wasiDisposed || __wasiDisposePromise || __hasWasiThreadCrashed()) {
548
+ return
549
+ }
550
+ const read = __napiInstance?.exports?.napi_wasm_runtime_pool_workers
551
+ if (typeof read !== 'function') {
552
+ return
553
+ }
554
+ const count = read() >>> 0
555
+ const manager = __getWasiThreadManager()
556
+ if (
557
+ !manager ||
558
+ !Array.isArray(manager.unusedWorkers) ||
559
+ typeof manager.allocateUnusedWorker !== 'function' ||
560
+ typeof manager.loadWasmModuleToWorker !== 'function'
561
+ ) {
562
+ return
563
+ }
564
+ // Both loops are bounded by the difference they start from, so a manager
565
+ // that does not update `unusedWorkers` the way emnapi does cannot spin.
566
+ for (let excess = manager.unusedWorkers.length - count; excess > 0; excess--) {
567
+ const worker = manager.unusedWorkers[manager.unusedWorkers.length - 1]
568
+ manager.terminateWorker(worker)
569
+ __removeWasiPoolWorker(manager, worker)
570
+ __untrackWasiWorkerOnExit(worker)
571
+ // Compatibility with @emnapi/wasi-threads 2.1.0 and older:
572
+ // `terminateWorker` installs a reporter that logs every emnapi message
573
+ // still queued on the port, so a Worker that finished loading just
574
+ // before it was terminated prints 'received "loaded" command from
575
+ // terminated worker'. Nothing listens for that Worker any more, and a
576
+ // newer emnapi ignores the late 'loaded' itself, so this is harmless
577
+ // there. `__terminateWasiWorkers` does the same.
578
+ worker.onmessage = undefined
579
+ }
580
+ for (let missing = count - manager.unusedWorkers.length; missing > 0; missing--) {
581
+ let worker
582
+ try {
583
+ // Through `onCreateWorker`: tracked in `__wasiWorkers`, unref'd, and
584
+ // handed the crash flags like any pool Worker.
585
+ worker = manager.allocateUnusedWorker()
586
+ manager
587
+ .loadWasmModuleToWorker(worker)
588
+ .then(undefined, () => __removeWasiPoolWorker(manager, worker))
589
+ } catch {
590
+ if (worker !== undefined) {
591
+ __removeWasiPoolWorker(manager, worker)
592
+ try {
593
+ manager.terminateWorker(worker)
594
+ __untrackWasiWorkerOnExit(worker)
595
+ } catch {}
596
+ }
597
+ return
598
+ }
599
+ }
600
+ } catch {}
601
+ }
602
+
603
+ function __publishWasiThreadPoolReconcile(exports) {
604
+ Object.defineProperty(exports, __wasiThreadPoolReconcileSymbol, {
605
+ configurable: false,
606
+ enumerable: false,
607
+ value: __reconcileWasiThreadPool,
608
+ writable: false,
609
+ })
610
+ }
611
+
108
612
  const __cwd = process.cwd()
109
613
  const __rootDir = __nodePath.parse(__cwd).root
110
614
  const __hostRoot =
@@ -149,14 +653,59 @@ let __emnapiContext
149
653
 
150
654
  const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
151
655
  const __wasiWorkers = new Set()
656
+ // The thread manager has to be reachable *before* anything that can throw
657
+ // during load or registration. Initialization can fail after the pool has
658
+ // already spawned workers, and the rollback still has to mark their
659
+ // terminations as expected — but `__napiModule` is assigned only when
660
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
661
+ // plugin factory runs while the emnapi module is being created, before the
662
+ // wasm is loaded and before any registration function runs, and its context
663
+ // carries the very same manager instance.
664
+ let __wasiThreadManager
665
+
666
+ function __captureWasiThreadManager(context) {
667
+ if (context && context.PThread) {
668
+ __wasiThreadManager = context.PThread
669
+ }
670
+ return {}
671
+ }
672
+
673
+ function __getWasiThreadManager() {
674
+ const manager =
675
+ __wasiThreadManager !== undefined
676
+ ? __wasiThreadManager
677
+ : __napiModule
678
+ ? __napiModule.PThread
679
+ : undefined
680
+ if (manager && typeof manager.terminateWorker === 'function') {
681
+ return manager
682
+ }
683
+ return undefined
684
+ }
152
685
  let __napiInstance
153
686
  let __emnapiContextDestroyed = false
154
687
  let __emnapiContextDestroyPromise
155
688
  let __emnapiWasmEnvCleanupPrepared = false
689
+ let __emnapiWasmEnvCleanupPreparing = false
690
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
691
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
692
+ // tell those two apart on its own: it is raised both for a purely synchronous
693
+ // frame — which must not be re-entered, and which nothing outside it can
694
+ // finish — and across this window, which spans real event-loop turns, so a
695
+ // caller that cannot yield can land in the middle of one. That caller can close
696
+ // this window, because `…_finish` is idempotent and joins, which is exactly
697
+ // what the single call does. See `__prepareWasmEnvCleanup`.
698
+ let __finishParkedWasmEnvCleanup
699
+ // Raised while a caller that can still yield is driving the barrier, so the
700
+ // queue it leaves behind is expected rather than lost. See
701
+ // `__reportUnreachedWasmEnvSettlements`.
702
+ let __emnapiWasmEnvCleanupYielding = false
703
+ let __emnapiWasmEnvSettlementLossReported = false
156
704
  let __emnapiWasmEnvCleanupRan = false
157
705
  let __emnapiWasmEnvCleanupDrained = false
158
706
  let __emnapiWasmEnvCleanupDrainPromise
159
707
  let __wasiDisposed = false
708
+ let __wasiAsyncWorkDrainPromise
160
709
  let __wasiDisposePromise
161
710
  let __completeWasiDisposal = function () {}
162
711
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
@@ -226,18 +775,127 @@ function __attachCleanupErrors(error, cleanupErrors) {
226
775
  return aggregate
227
776
  }
228
777
 
778
+ function __wrapEmnapiContextDestroyForSettlement(
779
+ context,
780
+ prepareEnvCleanup,
781
+ isPreparingEnvCleanup,
782
+ ) {
783
+ let destroy
784
+ try {
785
+ destroy = context.destroy
786
+ } catch {
787
+ return context
788
+ }
789
+ if (typeof destroy !== 'function') {
790
+ return context
791
+ }
792
+ try {
793
+ Object.defineProperty(context, 'destroy', {
794
+ configurable: true,
795
+ enumerable: false,
796
+ writable: true,
797
+ value: function () {
798
+ // Reentered from a promise hook that fired inside the barrier: the
799
+ // frame running it destroys as soon as it returns.
800
+ if (isPreparingEnvCleanup?.()) {
801
+ return
802
+ }
803
+ prepareEnvCleanup?.()
804
+ return Reflect.apply(destroy, this, arguments)
805
+ },
806
+ })
807
+ } catch {}
808
+ return context
809
+ }
810
+
811
+ function __isPreparingWasmEnvCleanup() {
812
+ return __emnapiWasmEnvCleanupPreparing
813
+ }
814
+
229
815
  function __prepareWasmEnvCleanup() {
230
816
  if (__emnapiWasmEnvCleanupPrepared) {
231
817
  return
232
818
  }
819
+ // A handshake parked between its two halves is one this frame can close, and
820
+ // must: every caller of this function is about to destroy the context, and
821
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
822
+ // the last thing the process runs, and `Context.destroy()` takes the
823
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
824
+ // this degrades to exactly the single call below. Leaving it open instead
825
+ // destroys the context with the barrier still raised, the runtime never
826
+ // joined and the workers never drained.
827
+ const finishParked = __finishParkedWasmEnvCleanup
828
+ if (finishParked !== undefined) {
829
+ finishParked()
830
+ __reportUnreachedWasmEnvSettlements()
831
+ return
832
+ }
833
+ if (__emnapiWasmEnvCleanupPreparing) {
834
+ return
835
+ }
233
836
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
234
837
  if (typeof prepare === 'function') {
235
- prepare()
838
+ // The addon settles the promises it cancels synchronously, under a
839
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
840
+ // here must not reach this export again.
841
+ __emnapiWasmEnvCleanupPreparing = true
842
+ try {
843
+ prepare()
844
+ } finally {
845
+ __emnapiWasmEnvCleanupPreparing = false
846
+ }
236
847
  __emnapiWasmEnvCleanupRan = true
848
+ __reportUnreachedWasmEnvSettlements()
237
849
  }
238
850
  __emnapiWasmEnvCleanupPrepared = true
239
851
  }
240
852
 
853
+ /**
854
+ * Say so when the barrier leaves settlements queued and nothing is left that
855
+ * could deliver them.
856
+ *
857
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
858
+ * dispatch its queue. Every other caller of the barrier destroys in the same
859
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
860
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
861
+ * that queue with a null env and discards it. The promises those settlements
862
+ * were for then hang forever, silently.
863
+ *
864
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
865
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
866
+ * teardown down with it. Destroying anyway is still the right trade — the queue
867
+ * is already unreachable by then.
868
+ */
869
+ function __reportUnreachedWasmEnvSettlements() {
870
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
871
+ return
872
+ }
873
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
874
+ if (typeof pending !== 'function') {
875
+ return
876
+ }
877
+ let queued
878
+ try {
879
+ queued = pending()
880
+ } catch {
881
+ return
882
+ }
883
+ if (!queued) {
884
+ return
885
+ }
886
+ __emnapiWasmEnvSettlementLossReported = true
887
+ try {
888
+ const consoleHost = globalThis.console
889
+ if (consoleHost && typeof consoleHost.error === 'function') {
890
+ consoleHost.error(
891
+ "napi-rs: the wasm environment is being destroyed with " +
892
+ queued +
893
+ " queued promise settlement(s). Context.destroy() discards them, so those promises never settle. Dispose with binding[Symbol.for('napi.rs.wasi.dispose')]() instead: only it yields the event-loop turns the settlements need.",
894
+ )
895
+ }
896
+ } catch {}
897
+ }
898
+
241
899
  // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
242
900
  // on, so the drain turns below interleave with that dispatch instead of racing
243
901
  // ahead of it on a faster queue.
@@ -269,6 +927,319 @@ const __scheduleMacrotask = (function () {
269
927
  }
270
928
  })()
271
929
 
930
+ // A real, *referenced* timer, for waits that must let the whole host make
931
+ // progress between looks — the async-work drain polls the addon rather than
932
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
933
+ // would spin the loop instead of yielding it. Falls back to the macrotask
934
+ // scheduler on a host without timers.
935
+ function __scheduleTimer(callback, delay) {
936
+ const setTimer = globalThis.setTimeout
937
+ if (typeof setTimer !== 'function') {
938
+ __scheduleMacrotask(callback)
939
+ return
940
+ }
941
+ try {
942
+ setTimer(callback, delay)
943
+ } catch {
944
+ __scheduleMacrotask(callback)
945
+ }
946
+ }
947
+
948
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
949
+ // reason the async-work drain uses one: this polls the addon instead of
950
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
951
+ // the loop instead of yielding it.
952
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
953
+ // Arrivals it takes before the poll paces on the host's timers alone. One
954
+ // proves nothing: a timer armed before the host's timers stopped still fires.
955
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
956
+ // How long a parked turn's own timer must already have been due before a
957
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
958
+ // against the event loop's clock, which is read once per iteration, while
959
+ // these are `Date.now()` readings taken part-way through one, so the two
960
+ // drift apart by however long the loop has been inside the current iteration.
961
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
962
+ // How long a backup itself waits. What is left of it after the slack and one
963
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
964
+ // parked turn from the last backup armed while the host's timers still
965
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
966
+ // `__armWasmRuntimePollStallBackup`.
967
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
968
+
969
+ /**
970
+ * Pacing state for one runtime-work poll.
971
+ *
972
+ * Per poll, never per module: whether the host's timers arrive is not a
973
+ * property of the module. A host can lose its timers between two disposals,
974
+ * and in the deferred shape every instance shares this module — one healthy
975
+ * instance must not disarm the fallback for the next one.
976
+ */
977
+ function __createWasmRuntimePollPace() {
978
+ return {
979
+ // Timers armed by *this* poll that have actually arrived.
980
+ arrivals: 0,
981
+ // The turn waiting on a timer alone *right now* — undefined whenever no
982
+ // turn is parked — and when that turn's own timer came due.
983
+ settleTurn: undefined,
984
+ turnTimerDueAt: 0,
985
+ }
986
+ }
987
+
988
+ /**
989
+ * The backup that ends a turn whose timer is never going to arrive.
990
+ *
991
+ * Once the poll paces on the timer alone it has nothing left to fall back on
992
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
993
+ * the turn that parks, and a parked poll schedules nothing that could notice.
994
+ * So every turn arms one of these before it yields, and each one compares due
995
+ * times instead of measuring how long the parked turn has been waiting.
996
+ *
997
+ * Invariant: a parked turn is ended by the newest backup that was armed while
998
+ * the host's timers still worked, and a backup ends a turn only when that
999
+ * turn's own timer was already due a whole window before the backup itself.
1000
+ * Neither half turns on how far apart the arms happen to fall — what bounds
1001
+ * the rescue is how far back that newest live backup is:
1002
+ *
1003
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
1004
+ * turn due a whole window earlier is still parked proves that turn's timer
1005
+ * was dropped rather than merely late. That same comparison is what leaves a
1006
+ * healthy host alone: there the turn's timer has already run and cleared
1007
+ * `settleTurn` before any backup due after it can look.
1008
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
1009
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
1010
+ * primitives and the macrotask wins, so such a turn can end with its own
1011
+ * timer — and the backup armed one line before it — already dead. The
1012
+ * arrival that then flips the poll onto the timer alone can itself be a
1013
+ * timer armed before the host's timers died. So the turn that parks can sit
1014
+ * two turns past the last live arm, and the newest live backup is due
1015
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
1016
+ * Arming on every turn is what holds it to two, rather than however far back
1017
+ * a throttle last let one through.
1018
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
1019
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
1020
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
1021
+ * Past that the turn stays parked and the disposal promise never settles.
1022
+ * The bound is deliberate: reaching it takes a host that drops timers
1023
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
1024
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
1025
+ * the second.
1026
+ *
1027
+ * The poll then goes back to arming both primitives until two fresh arrivals
1028
+ * prove the timers again. A host that stops running the timers it has
1029
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
1030
+ * pending rather than wedging the thread — the same outcome as a blocking
1031
+ * closure that never returns. Unreferenced wherever the host allows it: the
1032
+ * poll's own turn timers are what keep the loop alive, never these.
1033
+ */
1034
+ function __armWasmRuntimePollStallBackup(pace) {
1035
+ const setTimer = globalThis.setTimeout
1036
+ if (typeof setTimer !== 'function') {
1037
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
1038
+ // already, and that one cannot park.
1039
+ return
1040
+ }
1041
+ // Read before arming, so this never claims to be due earlier than the timer
1042
+ // actually is: a backup ends a turn only when it is provably due after it.
1043
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
1044
+ let handle
1045
+ try {
1046
+ handle = setTimer(() => {
1047
+ const settleTurn = pace.settleTurn
1048
+ if (
1049
+ !settleTurn ||
1050
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
1051
+ ) {
1052
+ // No turn is parked, or the parked one's timer came due too close to
1053
+ // this backup to call it dropped — it may still arrive, and the turn
1054
+ // that armed it armed a backup due a whole window after *that*.
1055
+ return
1056
+ }
1057
+ pace.arrivals = 0
1058
+ pace.settleTurn = undefined
1059
+ settleTurn()
1060
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
1061
+ } catch {
1062
+ return
1063
+ }
1064
+ if (handle && typeof handle.unref === 'function') {
1065
+ try {
1066
+ handle.unref()
1067
+ } catch {}
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * One turn of the runtime-work poll.
1073
+ *
1074
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
1075
+ * missing or throws, but not when it is present, returns a handle and never
1076
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
1077
+ * host whose timers belong to an IO context that is already gone. That host
1078
+ * would park this poll forever, and the poll is unbounded, so nothing would
1079
+ * ever call `…_finish`.
1080
+ *
1081
+ * Arm both primitives until timers armed by this poll have arrived twice, and
1082
+ * let whichever lands first end the turn; the loser resolves nothing. A host
1083
+ * with working timers therefore pays the double arming for the first turn or
1084
+ * two — the macrotask wins the race, but the timers behind it still arrive and
1085
+ * are counted — and paces on the timer alone from then on, instead of spinning
1086
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
1087
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
1088
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
1089
+ * which ends the parked turn and puts this poll back on both.
1090
+ */
1091
+ function __yieldWasmRuntimePollTurn(pace) {
1092
+ // Armed before the turn yields, and by every turn: what rescues a parked
1093
+ // turn has to have been armed while the host's timers still worked, and the
1094
+ // turn that parks is the one whose own timer is already dead.
1095
+ __armWasmRuntimePollStallBackup(pace)
1096
+ return new Promise((resolve) => {
1097
+ let settled = false
1098
+ const settle = () => {
1099
+ if (settled) {
1100
+ return
1101
+ }
1102
+ settled = true
1103
+ if (pace.settleTurn === settle) {
1104
+ // Nothing is parked any more: a backup running later must not read a
1105
+ // due time this turn has already answered.
1106
+ pace.settleTurn = undefined
1107
+ }
1108
+ resolve()
1109
+ }
1110
+ __scheduleTimer(() => {
1111
+ pace.arrivals++
1112
+ settle()
1113
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
1114
+ // Read next to the arming it describes; see
1115
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
1116
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
1117
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
1118
+ __scheduleMacrotask(settle)
1119
+ return
1120
+ }
1121
+ // Paced by the timer alone from here; the backup is what ends this turn if
1122
+ // the timer never arrives.
1123
+ pace.settleTurn = settle
1124
+ pace.turnTimerDueAt = turnTimerDueAt
1125
+ })
1126
+ }
1127
+
1128
+ /**
1129
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
1130
+ * event-loop turns in the middle.
1131
+ *
1132
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
1133
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
1134
+ * waits on is this one, the only thread that can give a running blocking
1135
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
1136
+ * for work that can never finish. The addon's two-phase form splits that:
1137
+ * `…_begin` stops the runtime without joining and reports whether anything is
1138
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
1139
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
1140
+ * entire point.
1141
+ *
1142
+ * The poll has no deadline, for the same reason the async-work drain below has
1143
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
1144
+ * work it would join is the work that is waiting for a turn from this thread —
1145
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
1146
+ * thread can no longer be reached. A blocking closure that never returns keeps
1147
+ * the disposal promise pending instead, exactly as a task whose `execute` never
1148
+ * returns already keeps an *undisposed* process alive. The host contract is in
1149
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
1150
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
1151
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
1152
+ *
1153
+ * Feature-detected like every other export in this teardown, so an addon built
1154
+ * against a napi crate that predates the split keeps the single blocking call.
1155
+ * Returns nothing whenever the handshake finished without yielding, which keeps
1156
+ * an idle disposal synchronous.
1157
+ */
1158
+ function __prepareWasmEnvCleanupWithTurns() {
1159
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
1160
+ return
1161
+ }
1162
+ const exports = __napiInstance?.exports
1163
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
1164
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
1165
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
1166
+ // No split to use. The settlement drain still follows this, so the queue
1167
+ // the single call leaves behind is expected rather than lost.
1168
+ __emnapiWasmEnvCleanupYielding = true
1169
+ try {
1170
+ __prepareWasmEnvCleanup()
1171
+ } finally {
1172
+ __emnapiWasmEnvCleanupYielding = false
1173
+ }
1174
+ return
1175
+ }
1176
+ const workPending = exports?.napi_wasm_runtime_work_pending
1177
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
1178
+ // from one of the JavaScript handlers they run is the same no-op it is inside
1179
+ // the single call: the barrier is up and the runtime is mid-teardown, and
1180
+ // destroying between the halves would strand exactly what this delivers.
1181
+ __emnapiWasmEnvCleanupPreparing = true
1182
+ let live
1183
+ try {
1184
+ live = begin()
1185
+ } catch (error) {
1186
+ __emnapiWasmEnvCleanupPreparing = false
1187
+ throw error
1188
+ }
1189
+ __emnapiWasmEnvCleanupRan = true
1190
+ const finishCleanup = () => {
1191
+ if (__emnapiWasmEnvCleanupPrepared) {
1192
+ // Already closed by a caller that could not yield — the 'exit' teardown
1193
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
1194
+ // is idempotent, but the flags it lowers are not: running it again here
1195
+ // would clear a `preparing` some later barrier had raised.
1196
+ return
1197
+ }
1198
+ __finishParkedWasmEnvCleanup = undefined
1199
+ try {
1200
+ finish()
1201
+ } finally {
1202
+ __emnapiWasmEnvCleanupPreparing = false
1203
+ }
1204
+ __emnapiWasmEnvCleanupPrepared = true
1205
+ }
1206
+ if (!live || typeof workPending !== 'function') {
1207
+ finishCleanup()
1208
+ return
1209
+ }
1210
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
1211
+ // a caller that cannot yield is entitled to end this handshake itself.
1212
+ __finishParkedWasmEnvCleanup = finishCleanup
1213
+ const finishCleanupUnlessCrashed = () => {
1214
+ try {
1215
+ __abortWasiDisposalIfThreadCrashed()
1216
+ } catch (error) {
1217
+ __finishParkedWasmEnvCleanup = undefined
1218
+ throw error
1219
+ }
1220
+ finishCleanup()
1221
+ }
1222
+ return (async () => {
1223
+ // Unbounded, exactly like the async-work drain below. The wait ends when
1224
+ // the addon reports its runtime work finished; the turns spent here are
1225
+ // what let that happen at all.
1226
+ const pace = __createWasmRuntimePollPace()
1227
+ for (;;) {
1228
+ await __yieldWasmRuntimePollTurn(pace)
1229
+ __abortWasiDisposalIfThreadCrashed()
1230
+ try {
1231
+ if (!workPending()) {
1232
+ return
1233
+ }
1234
+ } catch {
1235
+ // A trap is the only way this fails, and a trapped instance has no
1236
+ // reachable work left. Stop polling and finish.
1237
+ return
1238
+ }
1239
+ }
1240
+ })().then(finishCleanupUnlessCrashed, finishCleanupUnlessCrashed)
1241
+ }
1242
+
272
1243
  // Turns to wait for while the addon still reports queued settlements. Reaching
273
1244
  // zero is the only success. A counter still nonzero at this bound rejects the
274
1245
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -405,6 +1376,19 @@ function __destroyEmnapiContext() {
405
1376
  }
406
1377
 
407
1378
  __prepareWasmEnvCleanup()
1379
+ if (__isPreparingWasmEnvCleanup()) {
1380
+ // Reached from inside the synchronous barrier — a promise hook one of the
1381
+ // settlements above ran, which is the reentrancy the destroy wrapper
1382
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
1383
+ // no-op and answer `undefined`, and recording that as a completed destroy
1384
+ // is what makes the frame that *did* start the barrier skip the real one
1385
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
1386
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
1387
+ // moment it returns. The deferred loader carries the same backstop. A
1388
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
1389
+ // rather than skipping it.
1390
+ return
1391
+ }
408
1392
  const result = __emnapiContext.destroy()
409
1393
  if (!__isThenable(result)) {
410
1394
  __emnapiContextDestroyed = true
@@ -425,13 +1409,210 @@ function __destroyEmnapiContext() {
425
1409
  return destroyPromise
426
1410
  }
427
1411
 
1412
+ /**
1413
+ * Holds the event loop open until `work` settles.
1414
+ *
1415
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
1416
+ * binding cannot keep a process alive, and referencing them again for the
1417
+ * termination does not hold either — emnapi unreferences a worker the moment it
1418
+ * reports `async-thread-ready`, which for a worker that was still starting
1419
+ * lands *after* the termination began. Without a handle of its own, an
1420
+ * `await dispose()` with nothing else pending exits the process with its
1421
+ * promise unsettled, and everything after the `await` is skipped.
1422
+ *
1423
+ * The timer is cleared as soon as the work settles, so this never outlives the
1424
+ * disposal that asked for it.
1425
+ */
1426
+ function __keepEventLoopAliveUntil(work) {
1427
+ const setTimer = globalThis.setInterval
1428
+ const clearTimer = globalThis.clearInterval
1429
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
1430
+ return work
1431
+ }
1432
+ let timer
1433
+ try {
1434
+ timer = setTimer(function () {}, 50)
1435
+ } catch {
1436
+ return work
1437
+ }
1438
+ const release = function () {
1439
+ try {
1440
+ clearTimer(timer)
1441
+ } catch {}
1442
+ }
1443
+ return work.then(
1444
+ (value) => {
1445
+ release()
1446
+ return value
1447
+ },
1448
+ (error) => {
1449
+ release()
1450
+ throw error
1451
+ },
1452
+ )
1453
+ }
1454
+
1455
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
1456
+ // ends when the addon reports zero, so this only decides how promptly disposal
1457
+ // notices — not how long it waits.
1458
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
1459
+
1460
+ /**
1461
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
1462
+ * would strand it.
1463
+ *
1464
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
1465
+ * it is observable from JavaScript: the threadless archive resolves
1466
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
1467
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
1468
+ * imports nor exports those symbols and the only brackets a loader could watch
1469
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
1470
+ * functions. The addon is the one place both flavors go through, so it answers
1471
+ * for both, through the same kind of handshake the settlement drain uses:
1472
+ *
1473
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
1474
+ * started. Those completion callbacks run with `napi_cancelled`, which
1475
+ * napi-rs turns into a promise rejected with an `AbortError`.
1476
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
1477
+ * callback. Work already executing refuses cancellation and stays counted
1478
+ * until it finishes normally — which it can, because this runs before the
1479
+ * barrier, before `Context.destroy()` and before anything is terminated.
1480
+ *
1481
+ * Both exports are optional: an addon built against a napi crate that predates
1482
+ * them drains nothing and keeps the previous behavior, exactly as the
1483
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
1484
+ *
1485
+ * Returns nothing when there is nothing outstanding, which keeps disposal
1486
+ * synchronous in the common case. The promise it returns otherwise never
1487
+ * rejects.
1488
+ *
1489
+ * The wait has no deadline, and that is the point: giving up would destroy the
1490
+ * environment with a completion callback still owed, which is the stranding
1491
+ * this exists to prevent. A task whose `execute` never returns already keeps an
1492
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
1493
+ * rather than inventing a bound it cannot honor.
1494
+ *
1495
+ * Safe to call from inside a completion callback, which is reachable: settling
1496
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
1497
+ * being handed back, a threadsafe-function callback — and that JavaScript can
1498
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
1499
+ *
1500
+ * - The addon keeps a work registered until its completion callback
1501
+ * *finishes*, so the count read here is at least one and this takes the
1502
+ * polling path instead of declaring the environment drained and tearing it
1503
+ * down from inside the frame that is still settling a promise.
1504
+ * - The poll is a timer, so it cannot run until the callback has returned to
1505
+ * the host — by which time that work has left the registry. The count the
1506
+ * next poll reads is the one taken after the callback finished.
1507
+ *
1508
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
1509
+ * nested call joins this disposal rather than starting a second one.
1510
+ */
1511
+ function __drainWasiAsyncWork() {
1512
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
1513
+ return __wasiAsyncWorkDrainPromise
1514
+ }
1515
+ const exports = __napiInstance?.exports
1516
+ const pending = exports?.napi_wasm_async_work_pending
1517
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
1518
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
1519
+ return
1520
+ }
1521
+
1522
+ const readPending = () => {
1523
+ try {
1524
+ return pending()
1525
+ } catch (error) {
1526
+ // A trap is the only way this call fails: it reads a counter and cannot
1527
+ // allocate or call back into JavaScript. A trapped instance can no longer
1528
+ // run anything, so its outstanding work is unreachable by definition —
1529
+ // there is nothing left to wait for, and refusing to dispose would only
1530
+ // keep a dead instance and its stuck counter alive. Best-effort here is
1531
+ // the honest answer, and it is what disposal did before this drain
1532
+ // existed.
1533
+ //
1534
+ // Only a trap. Anything else means the export is not what this loader
1535
+ // thinks it is, which is a defect worth surfacing rather than disposing
1536
+ // over.
1537
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
1538
+ return 0
1539
+ }
1540
+ throw error
1541
+ }
1542
+ }
1543
+
1544
+ if (!readPending()) {
1545
+ return
1546
+ }
1547
+ try {
1548
+ cancelPending()
1549
+ } catch {
1550
+ // Cancellation is an optimization: it bounds the wait by the work already
1551
+ // executing. Failing it only means waiting for the whole queue instead.
1552
+ }
1553
+ if (!readPending()) {
1554
+ return
1555
+ }
1556
+
1557
+ const drainPromise = __keepEventLoopAliveUntil(
1558
+ (async () => {
1559
+ while (readPending()) {
1560
+ await new Promise((resolve) => {
1561
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1562
+ })
1563
+ __abortWasiDisposalIfThreadCrashed()
1564
+ }
1565
+ })(),
1566
+ ).then(
1567
+ () => {
1568
+ __wasiAsyncWorkDrainPromise = undefined
1569
+ },
1570
+ (error) => {
1571
+ // A wait that could not run is not a wait that finished. The only way
1572
+ // here is a host whose timers and macrotask primitives all refuse, and
1573
+ // the work is still outstanding — reporting success would destroy the
1574
+ // environment over it, which is the stranding this exists to prevent.
1575
+ // Reject instead: disposal stays retryable, and the context is not
1576
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1577
+ __wasiAsyncWorkDrainPromise = undefined
1578
+ throw error
1579
+ },
1580
+ )
1581
+ __wasiAsyncWorkDrainPromise = drainPromise
1582
+ return drainPromise
1583
+ }
1584
+
1585
+ /**
1586
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1587
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1588
+ * the manager's `exit` listener instead, which reports
1589
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1590
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1591
+ * promise, so disposal never settles and the process dies with an uncaught
1592
+ * exception. Mark the termination through the manager first.
1593
+ *
1594
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1595
+ * the initialization rollback runs on the one path where instantiation never
1596
+ * returned, so `__napiModule` is still undefined there while the workers it
1597
+ * spawned are already registered and loaded.
1598
+ *
1599
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1600
+ */
428
1601
  function __terminateWasiWorkers() {
429
1602
  const cleanupErrors = []
430
1603
  const pending = []
1604
+ const threadManager = __getWasiThreadManager()
431
1605
 
432
1606
  for (const worker of __wasiWorkers) {
433
1607
  let result
434
1608
  try {
1609
+ if (threadManager) {
1610
+ threadManager.terminateWorker(worker)
1611
+ // `terminateWorker` leaves behind a reporter that logs every message
1612
+ // still queued on the port, which Node flushes on exit. Nothing is
1613
+ // listening for those any more.
1614
+ worker.onmessage = undefined
1615
+ }
435
1616
  result = worker.terminate()
436
1617
  } catch (error) {
437
1618
  cleanupErrors.push(error)
@@ -461,7 +1642,9 @@ function __terminateWasiWorkers() {
461
1642
  )
462
1643
  }
463
1644
  }
464
- return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
1645
+ return pending.length > 0
1646
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1647
+ : finish()
465
1648
  }
466
1649
 
467
1650
  function __finishWasiDisposal() {
@@ -473,6 +1656,7 @@ function __finishWasiDisposal() {
473
1656
  }
474
1657
 
475
1658
  function __continueWasiDisposal() {
1659
+ __abortWasiDisposalIfThreadCrashed()
476
1660
  const destroyResult = __destroyEmnapiContext()
477
1661
  if (__isThenable(destroyResult)) {
478
1662
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -480,11 +1664,8 @@ function __continueWasiDisposal() {
480
1664
  return __finishWasiDisposal()
481
1665
  }
482
1666
 
483
- function __startWasiDisposal() {
484
- // Run the pre-teardown barrier, then let the settlements it queued actually
485
- // reach JavaScript, and only then destroy the environment. Doing these two
486
- // back to back is what strands them.
487
- __prepareWasmEnvCleanup()
1667
+ function __drainWasmEnvForWasiDisposal() {
1668
+ __abortWasiDisposalIfThreadCrashed()
488
1669
  const drainResult = __drainWasmEnvCleanup()
489
1670
  if (__isThenable(drainResult)) {
490
1671
  return Promise.resolve(drainResult).then(__continueWasiDisposal)
@@ -492,6 +1673,34 @@ function __startWasiDisposal() {
492
1673
  return __continueWasiDisposal()
493
1674
  }
494
1675
 
1676
+ function __cleanUpWasmEnvForWasiDisposal() {
1677
+ __abortWasiDisposalIfThreadCrashed()
1678
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1679
+ // for, when the addon has one — then let the settlements it queued actually
1680
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1681
+ // these back to back is what strands them.
1682
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1683
+ if (__isThenable(prepareResult)) {
1684
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1685
+ }
1686
+ return __drainWasmEnvForWasiDisposal()
1687
+ }
1688
+
1689
+ function __startWasiDisposal() {
1690
+ // Outstanding `napi_async_work` goes first, while the environment is still
1691
+ // completely live: the completion callbacks run addon code, and everything
1692
+ // after this point takes that away from them — the barrier shuts the async
1693
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1694
+ // the pool threads removes what would have reported the work finished.
1695
+ const asyncWorkResult = __drainWasiAsyncWork()
1696
+ if (__isThenable(asyncWorkResult)) {
1697
+ return Promise.resolve(asyncWorkResult).then(
1698
+ __cleanUpWasmEnvForWasiDisposal,
1699
+ )
1700
+ }
1701
+ return __cleanUpWasmEnvForWasiDisposal()
1702
+ }
1703
+
495
1704
  /**
496
1705
  * Disposes this generated WASI binding.
497
1706
  *
@@ -502,6 +1711,9 @@ function __disposeWasiBinding() {
502
1711
  if (__wasiDisposePromise) {
503
1712
  return __wasiDisposePromise
504
1713
  }
1714
+ if (!__wasiDisposed && __hasWasiThreadCrashed()) {
1715
+ return __disposeWasiBindingAfterThreadCrash()
1716
+ }
505
1717
  if (__wasiDisposed) {
506
1718
  return Promise.resolve()
507
1719
  }
@@ -518,6 +1730,9 @@ function __disposeWasiBinding() {
518
1730
  try {
519
1731
  result = __startWasiDisposal()
520
1732
  } catch (error) {
1733
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1734
+ return disposePromise
1735
+ }
521
1736
  __wasiDisposePromise = undefined
522
1737
  rejectDispose(error)
523
1738
  return disposePromise
@@ -529,6 +1744,9 @@ function __disposeWasiBinding() {
529
1744
  resolveDispose(value)
530
1745
  },
531
1746
  (error) => {
1747
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1748
+ return
1749
+ }
532
1750
  __wasiDisposePromise = undefined
533
1751
  rejectDispose(error)
534
1752
  },
@@ -564,6 +1782,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
564
1782
  }
565
1783
 
566
1784
  function __destroyContextForWasiRollback(cleanupErrors) {
1785
+ __abortWasiDisposalIfThreadCrashed()
567
1786
  let destroyResult
568
1787
  try {
569
1788
  destroyResult = __destroyEmnapiContext()
@@ -632,30 +1851,131 @@ function __retainFailedWasiRollback(cleanupErrors) {
632
1851
  * goes away. That is the deliberate choice: a hung promise is a silent liveness
633
1852
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
634
1853
  */
635
- function __rollbackWasiInitialization() {
636
- const cleanupErrors = []
637
- let drainResult
638
- let settlementsUnreached = false
1854
+ function __runWasiInitializationRollbackSteps() {
1855
+ // The environment teardown this rollback performs, kept nested so it cannot
1856
+ // be reached without the async-work drain below running first.
1857
+ function __rollbackWasmEnvForWasiInitialization() {
1858
+ __abortWasiDisposalIfThreadCrashed()
1859
+ const cleanupErrors = []
1860
+ let prepareResult
1861
+ try {
1862
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1863
+ } catch (cleanupError) {
1864
+ cleanupErrors.push(cleanupError)
1865
+ return __retainFailedWasiRollback(cleanupErrors)
1866
+ }
1867
+ if (__isThenable(prepareResult)) {
1868
+ return Promise.resolve(prepareResult).then(
1869
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1870
+ (cleanupError) => {
1871
+ cleanupErrors.push(cleanupError)
1872
+ return __retainFailedWasiRollback(cleanupErrors)
1873
+ },
1874
+ )
1875
+ }
1876
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1877
+ }
1878
+
1879
+ // The settlement drain of the rollback above, reached either straight away or
1880
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1881
+ // did not finish never gets here: it retains instead, exactly as a drain that
1882
+ // did not finish does.
1883
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1884
+ __abortWasiDisposalIfThreadCrashed()
1885
+ let drainResult
1886
+ try {
1887
+ drainResult = __drainWasmEnvCleanup()
1888
+ } catch (cleanupError) {
1889
+ cleanupErrors.push(cleanupError)
1890
+ return __retainFailedWasiRollback(cleanupErrors)
1891
+ }
1892
+ if (__isThenable(drainResult)) {
1893
+ return Promise.resolve(drainResult).then(
1894
+ () => __destroyContextForWasiRollback(cleanupErrors),
1895
+ (cleanupError) => {
1896
+ cleanupErrors.push(cleanupError)
1897
+ return __retainFailedWasiRollback(cleanupErrors)
1898
+ },
1899
+ )
1900
+ }
1901
+ return __destroyContextForWasiRollback(cleanupErrors)
1902
+ }
1903
+
1904
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1905
+ // work before the load goes on to fail, and this rollback tears down exactly
1906
+ // what those completions need. Settle them while everything is still live,
1907
+ // before the barrier and the teardown above take that away.
1908
+ //
1909
+ // A drain that could not finish leaves async work possibly outstanding, and
1910
+ // destroying the context over it would strand exactly what this rollback is
1911
+ // there to settle. Stop short and retain instead — the same trade
1912
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1913
+ // the context stays reclaimable by a retry or by this flavor's own
1914
+ // last-resort teardown.
1915
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1916
+ __retainFailedWasiRollback([cleanupError])
1917
+ let asyncWorkResult
639
1918
  try {
640
- __prepareWasmEnvCleanup()
641
- drainResult = __drainWasmEnvCleanup()
1919
+ asyncWorkResult = __drainWasiAsyncWork()
642
1920
  } catch (cleanupError) {
643
- cleanupErrors.push(cleanupError)
644
- settlementsUnreached = true
1921
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
645
1922
  }
646
- if (__isThenable(drainResult)) {
647
- return Promise.resolve(drainResult).then(
648
- () => __destroyContextForWasiRollback(cleanupErrors),
649
- (cleanupError) => {
650
- cleanupErrors.push(cleanupError)
651
- return __retainFailedWasiRollback(cleanupErrors)
652
- },
1923
+ if (__isThenable(asyncWorkResult)) {
1924
+ return Promise.resolve(asyncWorkResult).then(
1925
+ __rollbackWasmEnvForWasiInitialization,
1926
+ __retainAfterAsyncWorkDrainFailure,
653
1927
  )
654
1928
  }
655
- if (settlementsUnreached) {
656
- return __retainFailedWasiRollback(cleanupErrors)
1929
+ return __rollbackWasmEnvForWasiInitialization()
1930
+ }
1931
+
1932
+ /**
1933
+ * The rollback above, stopped when a wasm thread has died.
1934
+ *
1935
+ * Its polls wait for work the dead thread still counts, so they never end, and
1936
+ * the barrier's `…_finish` and `Context.destroy()` would re-enter wasm
1937
+ * and wait on that thread for good. While the rollback runs, the poll turns
1938
+ * and step boundaries stop it (`__abortWasiDisposalIfThreadCrashed`), and a
1939
+ * crash seen before, during or after it ends it through
1940
+ * `__rollbackWasiInitializationAfterThreadCrash`. Without a crash the
1941
+ * result — synchronous or not — is passed through unchanged.
1942
+ */
1943
+ function __rollbackWasiInitialization() {
1944
+ if (__hasWasiThreadCrashed()) {
1945
+ return __rollbackWasiInitializationAfterThreadCrash()
657
1946
  }
658
- return __destroyContextForWasiRollback(cleanupErrors)
1947
+ __wasiInitializationRollbackActive = true
1948
+ let result
1949
+ try {
1950
+ result = __runWasiInitializationRollbackSteps()
1951
+ } catch (error) {
1952
+ __wasiInitializationRollbackActive = false
1953
+ if (__hasWasiThreadCrashed()) {
1954
+ return __rollbackWasiInitializationAfterThreadCrash()
1955
+ }
1956
+ throw error
1957
+ }
1958
+ if (!__isThenable(result)) {
1959
+ __wasiInitializationRollbackActive = false
1960
+ return __hasWasiThreadCrashed()
1961
+ ? __rollbackWasiInitializationAfterThreadCrash()
1962
+ : result
1963
+ }
1964
+ return Promise.resolve(result).then(
1965
+ (cleanupErrors) => {
1966
+ __wasiInitializationRollbackActive = false
1967
+ return __hasWasiThreadCrashed()
1968
+ ? __rollbackWasiInitializationAfterThreadCrash()
1969
+ : cleanupErrors
1970
+ },
1971
+ (error) => {
1972
+ __wasiInitializationRollbackActive = false
1973
+ if (__hasWasiThreadCrashed()) {
1974
+ return __rollbackWasiInitializationAfterThreadCrash()
1975
+ }
1976
+ throw error
1977
+ },
1978
+ )
659
1979
  }
660
1980
 
661
1981
  const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
@@ -761,11 +2081,24 @@ function __removeWasiExitListener() {
761
2081
 
762
2082
  function __disposeWasiBindingAtExit() {
763
2083
  __wasiExitListenerRegistered = false
2084
+ if (__hasWasiThreadCrashed()) {
2085
+ // Never re-enter wasm after a thread died: the environment cleanup joins
2086
+ // the dead thread's work and would hang the exit forever — SIGTERM
2087
+ // included, since its JavaScript listener never gets a turn. Stop the
2088
+ // workers and leave.
2089
+ try {
2090
+ void Promise.resolve(__terminateWasiWorkers()).catch(() => {})
2091
+ } catch {}
2092
+ return
2093
+ }
764
2094
  // An 'exit' handler cannot yield, so it cannot wait for queued promise
765
2095
  // settlements the way __startWasiDisposal does — the process is leaving and
766
2096
  // those promises have no observer left anyway. Run the synchronous teardown
767
2097
  // directly. Every step is idempotent, which also makes this the synchronous
768
- // finish for a disposal that is still waiting for its drain.
2098
+ // finish for a disposal that is still waiting for its drain — and, through
2099
+ // __prepareWasmEnvCleanup, for one still parked between the two halves of
2100
+ // the environment cleanup barrier: there are no turns left to poll with, so
2101
+ // this closes that handshake with `…_finish`, which joins.
769
2102
  try {
770
2103
  __destroyEmnapiContext()
771
2104
  } catch {}
@@ -831,7 +2164,11 @@ function __captureEmnapiAutoDestroyListener() {
831
2164
  try {
832
2165
  const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
833
2166
  try {
834
- __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
2167
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
2168
+ __emnapiCreateContext({ autoDestroy: false, features: { setImmediate: __wasiSetImmediate } }),
2169
+ __prepareWasmEnvCleanup,
2170
+ __isPreparingWasmEnvCleanup,
2171
+ )
835
2172
  // emnapi 2.x still registers an unconditional once-listener for
836
2173
  // beforeExit that auto-destroys the context, and suppressDestroy() only
837
2174
  // neutralizes its callback without removing it. This loader owns cleanup
@@ -859,11 +2196,20 @@ try {
859
2196
  }
860
2197
  })(),
861
2198
  reuseWorker: true,
862
- plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
2199
+ plugins: [
2200
+ __captureWasiThreadManager,
2201
+ __emnapiAsyncWorkPlugin,
2202
+ __emnapiTSFNPlugin,
2203
+ ],
863
2204
  wasi: __wasi,
864
2205
  onCreateWorker() {
865
2206
  const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
866
2207
  __wasiWorkers.add(worker)
2208
+ // Registered before emnapi's own listeners, which rethrow the error.
2209
+ worker.on('error', (error) => {
2210
+ __wasiThreadCrashed = true
2211
+ __recordWasiThreadCrashError(error, worker.threadId)
2212
+ })
867
2213
  worker.onmessage = ({ data }) => {
868
2214
  __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
869
2215
  }
@@ -889,6 +2235,10 @@ try {
889
2235
  }
890
2236
 
891
2237
  worker.unref()
2238
+ // These stubs stay in place for the worker's whole life, disposal
2239
+ // included: `__keepEventLoopAliveUntil` is what holds the process open
2240
+ // while a termination is pending, precisely because a worker's own
2241
+ // references cannot be relied on for it.
892
2242
  }
893
2243
  return worker
894
2244
  },
@@ -903,6 +2253,7 @@ try {
903
2253
  },
904
2254
  beforeInit({ instance }) {
905
2255
  __napiInstance = instance
2256
+ __captureWasiAddonCrashFlag(instance)
906
2257
  for (const name of Object.keys(instance.exports)) {
907
2258
  if (name.startsWith('__napi_register__')) {
908
2259
  instance.exports[name]()
@@ -911,6 +2262,23 @@ try {
911
2262
  },
912
2263
  }))
913
2264
  __publishWasiDispose(__napiModule.exports)
2265
+ __publishWasiThreadPoolReconcile(__napiModule.exports)
2266
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
2267
+ // export does not travel with it, so carry the marker on the binding itself
2268
+ // too. Three things pin the stamp to exactly this spot:
2269
+ // - inside this `try`, because the guard throws on a
2270
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
2271
+ // catch below tears the environment — context, workers, exit listener —
2272
+ // back down;
2273
+ // - after the async runtime host install, which hands this same object to
2274
+ // addon-provided registration functions that may put anything on it;
2275
+ // - assigning onto the loader's own `module.exports`, which is still the
2276
+ // original object here, so an addon accessor with a refusing setter is
2277
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
2278
+ // export detection — reads the static `module.exports.<name> =` either
2279
+ // way, and the later `module.exports = __napiModule.exports` does not
2280
+ // undo that.
2281
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
914
2282
  __registerWasiExitListener()
915
2283
  } catch (error) {
916
2284
  const rollback = {
@@ -923,5 +2291,10 @@ try {
923
2291
  __runWasiInitializationRollback(rollback)
924
2292
  throw rollback.error
925
2293
  }
2294
+ // Preload the pool for the count the addon configured during registration.
2295
+ // See `__reconcileWasiThreadPool`.
2296
+ try {
2297
+ __reconcileWasiThreadPool()
2298
+ } catch {}
926
2299
  module.exports = __napiModule.exports
927
2300
  module.exports.compressBuffers = __napiModule.exports.compressBuffers