@oxc-minify/binding-wasm32-wasi 0.150.0 → 0.152.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.
package/minify.wasi.cjs CHANGED
@@ -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')
@@ -149,14 +199,59 @@ let __emnapiContext
149
199
 
150
200
  const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
151
201
  const __wasiWorkers = new Set()
202
+ // The thread manager has to be reachable *before* anything that can throw
203
+ // during load or registration. Initialization can fail after the pool has
204
+ // already spawned workers, and the rollback still has to mark their
205
+ // terminations as expected — but `__napiModule` is assigned only when
206
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
207
+ // plugin factory runs while the emnapi module is being created, before the
208
+ // wasm is loaded and before any registration function runs, and its context
209
+ // carries the very same manager instance.
210
+ let __wasiThreadManager
211
+
212
+ function __captureWasiThreadManager(context) {
213
+ if (context && context.PThread) {
214
+ __wasiThreadManager = context.PThread
215
+ }
216
+ return {}
217
+ }
218
+
219
+ function __getWasiThreadManager() {
220
+ const manager =
221
+ __wasiThreadManager !== undefined
222
+ ? __wasiThreadManager
223
+ : __napiModule
224
+ ? __napiModule.PThread
225
+ : undefined
226
+ if (manager && typeof manager.terminateWorker === 'function') {
227
+ return manager
228
+ }
229
+ return undefined
230
+ }
152
231
  let __napiInstance
153
232
  let __emnapiContextDestroyed = false
154
233
  let __emnapiContextDestroyPromise
155
234
  let __emnapiWasmEnvCleanupPrepared = false
235
+ let __emnapiWasmEnvCleanupPreparing = false
236
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
237
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
238
+ // tell those two apart on its own: it is raised both for a purely synchronous
239
+ // frame — which must not be re-entered, and which nothing outside it can
240
+ // finish — and across this window, which spans real event-loop turns, so a
241
+ // caller that cannot yield can land in the middle of one. That caller can close
242
+ // this window, because `…_finish` is idempotent and joins, which is exactly
243
+ // what the single call does. See `__prepareWasmEnvCleanup`.
244
+ let __finishParkedWasmEnvCleanup
245
+ // Raised while a caller that can still yield is driving the barrier, so the
246
+ // queue it leaves behind is expected rather than lost. See
247
+ // `__reportUnreachedWasmEnvSettlements`.
248
+ let __emnapiWasmEnvCleanupYielding = false
249
+ let __emnapiWasmEnvSettlementLossReported = false
156
250
  let __emnapiWasmEnvCleanupRan = false
157
251
  let __emnapiWasmEnvCleanupDrained = false
158
252
  let __emnapiWasmEnvCleanupDrainPromise
159
253
  let __wasiDisposed = false
254
+ let __wasiAsyncWorkDrainPromise
160
255
  let __wasiDisposePromise
161
256
  let __completeWasiDisposal = function () {}
162
257
  // Overridden by loader flavors that have a last-resort reclaim for a rollback
@@ -226,18 +321,127 @@ function __attachCleanupErrors(error, cleanupErrors) {
226
321
  return aggregate
227
322
  }
228
323
 
324
+ function __wrapEmnapiContextDestroyForSettlement(
325
+ context,
326
+ prepareEnvCleanup,
327
+ isPreparingEnvCleanup,
328
+ ) {
329
+ let destroy
330
+ try {
331
+ destroy = context.destroy
332
+ } catch {
333
+ return context
334
+ }
335
+ if (typeof destroy !== 'function') {
336
+ return context
337
+ }
338
+ try {
339
+ Object.defineProperty(context, 'destroy', {
340
+ configurable: true,
341
+ enumerable: false,
342
+ writable: true,
343
+ value: function () {
344
+ // Reentered from a promise hook that fired inside the barrier: the
345
+ // frame running it destroys as soon as it returns.
346
+ if (isPreparingEnvCleanup?.()) {
347
+ return
348
+ }
349
+ prepareEnvCleanup?.()
350
+ return Reflect.apply(destroy, this, arguments)
351
+ },
352
+ })
353
+ } catch {}
354
+ return context
355
+ }
356
+
357
+ function __isPreparingWasmEnvCleanup() {
358
+ return __emnapiWasmEnvCleanupPreparing
359
+ }
360
+
229
361
  function __prepareWasmEnvCleanup() {
230
362
  if (__emnapiWasmEnvCleanupPrepared) {
231
363
  return
232
364
  }
365
+ // A handshake parked between its two halves is one this frame can close, and
366
+ // must: every caller of this function is about to destroy the context, and
367
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
368
+ // the last thing the process runs, and `Context.destroy()` takes the
369
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
370
+ // this degrades to exactly the single call below. Leaving it open instead
371
+ // destroys the context with the barrier still raised, the runtime never
372
+ // joined and the workers never drained.
373
+ const finishParked = __finishParkedWasmEnvCleanup
374
+ if (finishParked !== undefined) {
375
+ finishParked()
376
+ __reportUnreachedWasmEnvSettlements()
377
+ return
378
+ }
379
+ if (__emnapiWasmEnvCleanupPreparing) {
380
+ return
381
+ }
233
382
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
234
383
  if (typeof prepare === 'function') {
235
- prepare()
384
+ // The addon settles the promises it cancels synchronously, under a
385
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
386
+ // here must not reach this export again.
387
+ __emnapiWasmEnvCleanupPreparing = true
388
+ try {
389
+ prepare()
390
+ } finally {
391
+ __emnapiWasmEnvCleanupPreparing = false
392
+ }
236
393
  __emnapiWasmEnvCleanupRan = true
394
+ __reportUnreachedWasmEnvSettlements()
237
395
  }
238
396
  __emnapiWasmEnvCleanupPrepared = true
239
397
  }
240
398
 
399
+ /**
400
+ * Say so when the barrier leaves settlements queued and nothing is left that
401
+ * could deliver them.
402
+ *
403
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
404
+ * dispatch its queue. Every other caller of the barrier destroys in the same
405
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
406
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
407
+ * that queue with a null env and discards it. The promises those settlements
408
+ * were for then hang forever, silently.
409
+ *
410
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
411
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
412
+ * teardown down with it. Destroying anyway is still the right trade — the queue
413
+ * is already unreachable by then.
414
+ */
415
+ function __reportUnreachedWasmEnvSettlements() {
416
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
417
+ return
418
+ }
419
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
420
+ if (typeof pending !== 'function') {
421
+ return
422
+ }
423
+ let queued
424
+ try {
425
+ queued = pending()
426
+ } catch {
427
+ return
428
+ }
429
+ if (!queued) {
430
+ return
431
+ }
432
+ __emnapiWasmEnvSettlementLossReported = true
433
+ try {
434
+ const consoleHost = globalThis.console
435
+ if (consoleHost && typeof consoleHost.error === 'function') {
436
+ consoleHost.error(
437
+ "napi-rs: the wasm environment is being destroyed with " +
438
+ queued +
439
+ " 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.",
440
+ )
441
+ }
442
+ } catch {}
443
+ }
444
+
241
445
  // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
242
446
  // on, so the drain turns below interleave with that dispatch instead of racing
243
447
  // ahead of it on a faster queue.
@@ -269,6 +473,309 @@ const __scheduleMacrotask = (function () {
269
473
  }
270
474
  })()
271
475
 
476
+ // A real, *referenced* timer, for waits that must let the whole host make
477
+ // progress between looks — the async-work drain polls the addon rather than
478
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
479
+ // would spin the loop instead of yielding it. Falls back to the macrotask
480
+ // scheduler on a host without timers.
481
+ function __scheduleTimer(callback, delay) {
482
+ const setTimer = globalThis.setTimeout
483
+ if (typeof setTimer !== 'function') {
484
+ __scheduleMacrotask(callback)
485
+ return
486
+ }
487
+ try {
488
+ setTimer(callback, delay)
489
+ } catch {
490
+ __scheduleMacrotask(callback)
491
+ }
492
+ }
493
+
494
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
495
+ // reason the async-work drain uses one: this polls the addon instead of
496
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
497
+ // the loop instead of yielding it.
498
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
499
+ // Arrivals it takes before the poll paces on the host's timers alone. One
500
+ // proves nothing: a timer armed before the host's timers stopped still fires.
501
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
502
+ // How long a parked turn's own timer must already have been due before a
503
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
504
+ // against the event loop's clock, which is read once per iteration, while
505
+ // these are `Date.now()` readings taken part-way through one, so the two
506
+ // drift apart by however long the loop has been inside the current iteration.
507
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
508
+ // How long a backup itself waits. What is left of it after the slack and one
509
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
510
+ // parked turn from the last backup armed while the host's timers still
511
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
512
+ // `__armWasmRuntimePollStallBackup`.
513
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
514
+
515
+ /**
516
+ * Pacing state for one runtime-work poll.
517
+ *
518
+ * Per poll, never per module: whether the host's timers arrive is not a
519
+ * property of the module. A host can lose its timers between two disposals,
520
+ * and in the deferred shape every instance shares this module — one healthy
521
+ * instance must not disarm the fallback for the next one.
522
+ */
523
+ function __createWasmRuntimePollPace() {
524
+ return {
525
+ // Timers armed by *this* poll that have actually arrived.
526
+ arrivals: 0,
527
+ // The turn waiting on a timer alone *right now* — undefined whenever no
528
+ // turn is parked — and when that turn's own timer came due.
529
+ settleTurn: undefined,
530
+ turnTimerDueAt: 0,
531
+ }
532
+ }
533
+
534
+ /**
535
+ * The backup that ends a turn whose timer is never going to arrive.
536
+ *
537
+ * Once the poll paces on the timer alone it has nothing left to fall back on
538
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
539
+ * the turn that parks, and a parked poll schedules nothing that could notice.
540
+ * So every turn arms one of these before it yields, and each one compares due
541
+ * times instead of measuring how long the parked turn has been waiting.
542
+ *
543
+ * Invariant: a parked turn is ended by the newest backup that was armed while
544
+ * the host's timers still worked, and a backup ends a turn only when that
545
+ * turn's own timer was already due a whole window before the backup itself.
546
+ * Neither half turns on how far apart the arms happen to fall — what bounds
547
+ * the rescue is how far back that newest live backup is:
548
+ *
549
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
550
+ * turn due a whole window earlier is still parked proves that turn's timer
551
+ * was dropped rather than merely late. That same comparison is what leaves a
552
+ * healthy host alone: there the turn's timer has already run and cleared
553
+ * `settleTurn` before any backup due after it can look.
554
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
555
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
556
+ * primitives and the macrotask wins, so such a turn can end with its own
557
+ * timer — and the backup armed one line before it — already dead. The
558
+ * arrival that then flips the poll onto the timer alone can itself be a
559
+ * timer armed before the host's timers died. So the turn that parks can sit
560
+ * two turns past the last live arm, and the newest live backup is due
561
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
562
+ * Arming on every turn is what holds it to two, rather than however far back
563
+ * a throttle last let one through.
564
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
565
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
566
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
567
+ * Past that the turn stays parked and the disposal promise never settles.
568
+ * The bound is deliberate: reaching it takes a host that drops timers
569
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
570
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
571
+ * the second.
572
+ *
573
+ * The poll then goes back to arming both primitives until two fresh arrivals
574
+ * prove the timers again. A host that stops running the timers it has
575
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
576
+ * pending rather than wedging the thread — the same outcome as a blocking
577
+ * closure that never returns. Unreferenced wherever the host allows it: the
578
+ * poll's own turn timers are what keep the loop alive, never these.
579
+ */
580
+ function __armWasmRuntimePollStallBackup(pace) {
581
+ const setTimer = globalThis.setTimeout
582
+ if (typeof setTimer !== 'function') {
583
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
584
+ // already, and that one cannot park.
585
+ return
586
+ }
587
+ // Read before arming, so this never claims to be due earlier than the timer
588
+ // actually is: a backup ends a turn only when it is provably due after it.
589
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
590
+ let handle
591
+ try {
592
+ handle = setTimer(() => {
593
+ const settleTurn = pace.settleTurn
594
+ if (
595
+ !settleTurn ||
596
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
597
+ ) {
598
+ // No turn is parked, or the parked one's timer came due too close to
599
+ // this backup to call it dropped — it may still arrive, and the turn
600
+ // that armed it armed a backup due a whole window after *that*.
601
+ return
602
+ }
603
+ pace.arrivals = 0
604
+ pace.settleTurn = undefined
605
+ settleTurn()
606
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
607
+ } catch {
608
+ return
609
+ }
610
+ if (handle && typeof handle.unref === 'function') {
611
+ try {
612
+ handle.unref()
613
+ } catch {}
614
+ }
615
+ }
616
+
617
+ /**
618
+ * One turn of the runtime-work poll.
619
+ *
620
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
621
+ * missing or throws, but not when it is present, returns a handle and never
622
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
623
+ * host whose timers belong to an IO context that is already gone. That host
624
+ * would park this poll forever, and the poll is unbounded, so nothing would
625
+ * ever call `…_finish`.
626
+ *
627
+ * Arm both primitives until timers armed by this poll have arrived twice, and
628
+ * let whichever lands first end the turn; the loser resolves nothing. A host
629
+ * with working timers therefore pays the double arming for the first turn or
630
+ * two — the macrotask wins the race, but the timers behind it still arrive and
631
+ * are counted — and paces on the timer alone from then on, instead of spinning
632
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
633
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
634
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
635
+ * which ends the parked turn and puts this poll back on both.
636
+ */
637
+ function __yieldWasmRuntimePollTurn(pace) {
638
+ // Armed before the turn yields, and by every turn: what rescues a parked
639
+ // turn has to have been armed while the host's timers still worked, and the
640
+ // turn that parks is the one whose own timer is already dead.
641
+ __armWasmRuntimePollStallBackup(pace)
642
+ return new Promise((resolve) => {
643
+ let settled = false
644
+ const settle = () => {
645
+ if (settled) {
646
+ return
647
+ }
648
+ settled = true
649
+ if (pace.settleTurn === settle) {
650
+ // Nothing is parked any more: a backup running later must not read a
651
+ // due time this turn has already answered.
652
+ pace.settleTurn = undefined
653
+ }
654
+ resolve()
655
+ }
656
+ __scheduleTimer(() => {
657
+ pace.arrivals++
658
+ settle()
659
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
660
+ // Read next to the arming it describes; see
661
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
662
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
663
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
664
+ __scheduleMacrotask(settle)
665
+ return
666
+ }
667
+ // Paced by the timer alone from here; the backup is what ends this turn if
668
+ // the timer never arrives.
669
+ pace.settleTurn = settle
670
+ pace.turnTimerDueAt = turnTimerDueAt
671
+ })
672
+ }
673
+
674
+ /**
675
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
676
+ * event-loop turns in the middle.
677
+ *
678
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
679
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
680
+ * waits on is this one, the only thread that can give a running blocking
681
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
682
+ * for work that can never finish. The addon's two-phase form splits that:
683
+ * `…_begin` stops the runtime without joining and reports whether anything is
684
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
685
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
686
+ * entire point.
687
+ *
688
+ * The poll has no deadline, for the same reason the async-work drain below has
689
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
690
+ * work it would join is the work that is waiting for a turn from this thread —
691
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
692
+ * thread can no longer be reached. A blocking closure that never returns keeps
693
+ * the disposal promise pending instead, exactly as a task whose `execute` never
694
+ * returns already keeps an *undisposed* process alive. The host contract is in
695
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
696
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
697
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
698
+ *
699
+ * Feature-detected like every other export in this teardown, so an addon built
700
+ * against a napi crate that predates the split keeps the single blocking call.
701
+ * Returns nothing whenever the handshake finished without yielding, which keeps
702
+ * an idle disposal synchronous.
703
+ */
704
+ function __prepareWasmEnvCleanupWithTurns() {
705
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
706
+ return
707
+ }
708
+ const exports = __napiInstance?.exports
709
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
710
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
711
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
712
+ // No split to use. The settlement drain still follows this, so the queue
713
+ // the single call leaves behind is expected rather than lost.
714
+ __emnapiWasmEnvCleanupYielding = true
715
+ try {
716
+ __prepareWasmEnvCleanup()
717
+ } finally {
718
+ __emnapiWasmEnvCleanupYielding = false
719
+ }
720
+ return
721
+ }
722
+ const workPending = exports?.napi_wasm_runtime_work_pending
723
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
724
+ // from one of the JavaScript handlers they run is the same no-op it is inside
725
+ // the single call: the barrier is up and the runtime is mid-teardown, and
726
+ // destroying between the halves would strand exactly what this delivers.
727
+ __emnapiWasmEnvCleanupPreparing = true
728
+ let live
729
+ try {
730
+ live = begin()
731
+ } catch (error) {
732
+ __emnapiWasmEnvCleanupPreparing = false
733
+ throw error
734
+ }
735
+ __emnapiWasmEnvCleanupRan = true
736
+ const finishCleanup = () => {
737
+ if (__emnapiWasmEnvCleanupPrepared) {
738
+ // Already closed by a caller that could not yield — the 'exit' teardown
739
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
740
+ // is idempotent, but the flags it lowers are not: running it again here
741
+ // would clear a `preparing` some later barrier had raised.
742
+ return
743
+ }
744
+ __finishParkedWasmEnvCleanup = undefined
745
+ try {
746
+ finish()
747
+ } finally {
748
+ __emnapiWasmEnvCleanupPreparing = false
749
+ }
750
+ __emnapiWasmEnvCleanupPrepared = true
751
+ }
752
+ if (!live || typeof workPending !== 'function') {
753
+ finishCleanup()
754
+ return
755
+ }
756
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
757
+ // a caller that cannot yield is entitled to end this handshake itself.
758
+ __finishParkedWasmEnvCleanup = finishCleanup
759
+ return (async () => {
760
+ // Unbounded, exactly like the async-work drain below. The wait ends when
761
+ // the addon reports its runtime work finished; the turns spent here are
762
+ // what let that happen at all.
763
+ const pace = __createWasmRuntimePollPace()
764
+ for (;;) {
765
+ await __yieldWasmRuntimePollTurn(pace)
766
+ try {
767
+ if (!workPending()) {
768
+ return
769
+ }
770
+ } catch {
771
+ // A trap is the only way this fails, and a trapped instance has no
772
+ // reachable work left. Stop polling and finish.
773
+ return
774
+ }
775
+ }
776
+ })().then(finishCleanup, finishCleanup)
777
+ }
778
+
272
779
  // Turns to wait for while the addon still reports queued settlements. Reaching
273
780
  // zero is the only success. A counter still nonzero at this bound rejects the
274
781
  // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
@@ -405,6 +912,19 @@ function __destroyEmnapiContext() {
405
912
  }
406
913
 
407
914
  __prepareWasmEnvCleanup()
915
+ if (__isPreparingWasmEnvCleanup()) {
916
+ // Reached from inside the synchronous barrier — a promise hook one of the
917
+ // settlements above ran, which is the reentrancy the destroy wrapper
918
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
919
+ // no-op and answer `undefined`, and recording that as a completed destroy
920
+ // is what makes the frame that *did* start the barrier skip the real one
921
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
922
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
923
+ // moment it returns. The deferred loader carries the same backstop. A
924
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
925
+ // rather than skipping it.
926
+ return
927
+ }
408
928
  const result = __emnapiContext.destroy()
409
929
  if (!__isThenable(result)) {
410
930
  __emnapiContextDestroyed = true
@@ -425,13 +945,209 @@ function __destroyEmnapiContext() {
425
945
  return destroyPromise
426
946
  }
427
947
 
948
+ /**
949
+ * Holds the event loop open until `work` settles.
950
+ *
951
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
952
+ * binding cannot keep a process alive, and referencing them again for the
953
+ * termination does not hold either — emnapi unreferences a worker the moment it
954
+ * reports `async-thread-ready`, which for a worker that was still starting
955
+ * lands *after* the termination began. Without a handle of its own, an
956
+ * `await dispose()` with nothing else pending exits the process with its
957
+ * promise unsettled, and everything after the `await` is skipped.
958
+ *
959
+ * The timer is cleared as soon as the work settles, so this never outlives the
960
+ * disposal that asked for it.
961
+ */
962
+ function __keepEventLoopAliveUntil(work) {
963
+ const setTimer = globalThis.setInterval
964
+ const clearTimer = globalThis.clearInterval
965
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
966
+ return work
967
+ }
968
+ let timer
969
+ try {
970
+ timer = setTimer(function () {}, 50)
971
+ } catch {
972
+ return work
973
+ }
974
+ const release = function () {
975
+ try {
976
+ clearTimer(timer)
977
+ } catch {}
978
+ }
979
+ return work.then(
980
+ (value) => {
981
+ release()
982
+ return value
983
+ },
984
+ (error) => {
985
+ release()
986
+ throw error
987
+ },
988
+ )
989
+ }
990
+
991
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
992
+ // ends when the addon reports zero, so this only decides how promptly disposal
993
+ // notices — not how long it waits.
994
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
995
+
996
+ /**
997
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
998
+ * would strand it.
999
+ *
1000
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
1001
+ * it is observable from JavaScript: the threadless archive resolves
1002
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
1003
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
1004
+ * imports nor exports those symbols and the only brackets a loader could watch
1005
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
1006
+ * functions. The addon is the one place both flavors go through, so it answers
1007
+ * for both, through the same kind of handshake the settlement drain uses:
1008
+ *
1009
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
1010
+ * started. Those completion callbacks run with `napi_cancelled`, which
1011
+ * napi-rs turns into a promise rejected with an `AbortError`.
1012
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
1013
+ * callback. Work already executing refuses cancellation and stays counted
1014
+ * until it finishes normally — which it can, because this runs before the
1015
+ * barrier, before `Context.destroy()` and before anything is terminated.
1016
+ *
1017
+ * Both exports are optional: an addon built against a napi crate that predates
1018
+ * them drains nothing and keeps the previous behavior, exactly as the
1019
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
1020
+ *
1021
+ * Returns nothing when there is nothing outstanding, which keeps disposal
1022
+ * synchronous in the common case. The promise it returns otherwise never
1023
+ * rejects.
1024
+ *
1025
+ * The wait has no deadline, and that is the point: giving up would destroy the
1026
+ * environment with a completion callback still owed, which is the stranding
1027
+ * this exists to prevent. A task whose `execute` never returns already keeps an
1028
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
1029
+ * rather than inventing a bound it cannot honor.
1030
+ *
1031
+ * Safe to call from inside a completion callback, which is reachable: settling
1032
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
1033
+ * being handed back, a threadsafe-function callback — and that JavaScript can
1034
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
1035
+ *
1036
+ * - The addon keeps a work registered until its completion callback
1037
+ * *finishes*, so the count read here is at least one and this takes the
1038
+ * polling path instead of declaring the environment drained and tearing it
1039
+ * down from inside the frame that is still settling a promise.
1040
+ * - The poll is a timer, so it cannot run until the callback has returned to
1041
+ * the host — by which time that work has left the registry. The count the
1042
+ * next poll reads is the one taken after the callback finished.
1043
+ *
1044
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
1045
+ * nested call joins this disposal rather than starting a second one.
1046
+ */
1047
+ function __drainWasiAsyncWork() {
1048
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
1049
+ return __wasiAsyncWorkDrainPromise
1050
+ }
1051
+ const exports = __napiInstance?.exports
1052
+ const pending = exports?.napi_wasm_async_work_pending
1053
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
1054
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
1055
+ return
1056
+ }
1057
+
1058
+ const readPending = () => {
1059
+ try {
1060
+ return pending()
1061
+ } catch (error) {
1062
+ // A trap is the only way this call fails: it reads a counter and cannot
1063
+ // allocate or call back into JavaScript. A trapped instance can no longer
1064
+ // run anything, so its outstanding work is unreachable by definition —
1065
+ // there is nothing left to wait for, and refusing to dispose would only
1066
+ // keep a dead instance and its stuck counter alive. Best-effort here is
1067
+ // the honest answer, and it is what disposal did before this drain
1068
+ // existed.
1069
+ //
1070
+ // Only a trap. Anything else means the export is not what this loader
1071
+ // thinks it is, which is a defect worth surfacing rather than disposing
1072
+ // over.
1073
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
1074
+ return 0
1075
+ }
1076
+ throw error
1077
+ }
1078
+ }
1079
+
1080
+ if (!readPending()) {
1081
+ return
1082
+ }
1083
+ try {
1084
+ cancelPending()
1085
+ } catch {
1086
+ // Cancellation is an optimization: it bounds the wait by the work already
1087
+ // executing. Failing it only means waiting for the whole queue instead.
1088
+ }
1089
+ if (!readPending()) {
1090
+ return
1091
+ }
1092
+
1093
+ const drainPromise = __keepEventLoopAliveUntil(
1094
+ (async () => {
1095
+ while (readPending()) {
1096
+ await new Promise((resolve) => {
1097
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1098
+ })
1099
+ }
1100
+ })(),
1101
+ ).then(
1102
+ () => {
1103
+ __wasiAsyncWorkDrainPromise = undefined
1104
+ },
1105
+ (error) => {
1106
+ // A wait that could not run is not a wait that finished. The only way
1107
+ // here is a host whose timers and macrotask primitives all refuse, and
1108
+ // the work is still outstanding — reporting success would destroy the
1109
+ // environment over it, which is the stranding this exists to prevent.
1110
+ // Reject instead: disposal stays retryable, and the context is not
1111
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1112
+ __wasiAsyncWorkDrainPromise = undefined
1113
+ throw error
1114
+ },
1115
+ )
1116
+ __wasiAsyncWorkDrainPromise = drainPromise
1117
+ return drainPromise
1118
+ }
1119
+
1120
+ /**
1121
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1122
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1123
+ * the manager's `exit` listener instead, which reports
1124
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1125
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1126
+ * promise, so disposal never settles and the process dies with an uncaught
1127
+ * exception. Mark the termination through the manager first.
1128
+ *
1129
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1130
+ * the initialization rollback runs on the one path where instantiation never
1131
+ * returned, so `__napiModule` is still undefined there while the workers it
1132
+ * spawned are already registered and loaded.
1133
+ *
1134
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1135
+ */
428
1136
  function __terminateWasiWorkers() {
429
1137
  const cleanupErrors = []
430
1138
  const pending = []
1139
+ const threadManager = __getWasiThreadManager()
431
1140
 
432
1141
  for (const worker of __wasiWorkers) {
433
1142
  let result
434
1143
  try {
1144
+ if (threadManager) {
1145
+ threadManager.terminateWorker(worker)
1146
+ // `terminateWorker` leaves behind a reporter that logs every message
1147
+ // still queued on the port, which Node flushes on exit. Nothing is
1148
+ // listening for those any more.
1149
+ worker.onmessage = undefined
1150
+ }
435
1151
  result = worker.terminate()
436
1152
  } catch (error) {
437
1153
  cleanupErrors.push(error)
@@ -461,7 +1177,9 @@ function __terminateWasiWorkers() {
461
1177
  )
462
1178
  }
463
1179
  }
464
- return pending.length > 0 ? Promise.all(pending).then(finish) : finish()
1180
+ return pending.length > 0
1181
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1182
+ : finish()
465
1183
  }
466
1184
 
467
1185
  function __finishWasiDisposal() {
@@ -480,11 +1198,7 @@ function __continueWasiDisposal() {
480
1198
  return __finishWasiDisposal()
481
1199
  }
482
1200
 
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()
1201
+ function __drainWasmEnvForWasiDisposal() {
488
1202
  const drainResult = __drainWasmEnvCleanup()
489
1203
  if (__isThenable(drainResult)) {
490
1204
  return Promise.resolve(drainResult).then(__continueWasiDisposal)
@@ -492,6 +1206,33 @@ function __startWasiDisposal() {
492
1206
  return __continueWasiDisposal()
493
1207
  }
494
1208
 
1209
+ function __cleanUpWasmEnvForWasiDisposal() {
1210
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1211
+ // for, when the addon has one — then let the settlements it queued actually
1212
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1213
+ // these back to back is what strands them.
1214
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1215
+ if (__isThenable(prepareResult)) {
1216
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1217
+ }
1218
+ return __drainWasmEnvForWasiDisposal()
1219
+ }
1220
+
1221
+ function __startWasiDisposal() {
1222
+ // Outstanding `napi_async_work` goes first, while the environment is still
1223
+ // completely live: the completion callbacks run addon code, and everything
1224
+ // after this point takes that away from them — the barrier shuts the async
1225
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1226
+ // the pool threads removes what would have reported the work finished.
1227
+ const asyncWorkResult = __drainWasiAsyncWork()
1228
+ if (__isThenable(asyncWorkResult)) {
1229
+ return Promise.resolve(asyncWorkResult).then(
1230
+ __cleanUpWasmEnvForWasiDisposal,
1231
+ )
1232
+ }
1233
+ return __cleanUpWasmEnvForWasiDisposal()
1234
+ }
1235
+
495
1236
  /**
496
1237
  * Disposes this generated WASI binding.
497
1238
  *
@@ -633,29 +1374,79 @@ function __retainFailedWasiRollback(cleanupErrors) {
633
1374
  * bug with no upper bound, while the retained bookkeeping is bounded by the page.
634
1375
  */
635
1376
  function __rollbackWasiInitialization() {
636
- const cleanupErrors = []
637
- let drainResult
638
- let settlementsUnreached = false
1377
+ // The environment teardown this rollback performs, kept nested so it cannot
1378
+ // be reached without the async-work drain below running first.
1379
+ function __rollbackWasmEnvForWasiInitialization() {
1380
+ const cleanupErrors = []
1381
+ let prepareResult
1382
+ try {
1383
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1384
+ } catch (cleanupError) {
1385
+ cleanupErrors.push(cleanupError)
1386
+ return __retainFailedWasiRollback(cleanupErrors)
1387
+ }
1388
+ if (__isThenable(prepareResult)) {
1389
+ return Promise.resolve(prepareResult).then(
1390
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1391
+ (cleanupError) => {
1392
+ cleanupErrors.push(cleanupError)
1393
+ return __retainFailedWasiRollback(cleanupErrors)
1394
+ },
1395
+ )
1396
+ }
1397
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1398
+ }
1399
+
1400
+ // The settlement drain of the rollback above, reached either straight away or
1401
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1402
+ // did not finish never gets here: it retains instead, exactly as a drain that
1403
+ // did not finish does.
1404
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1405
+ let drainResult
1406
+ try {
1407
+ drainResult = __drainWasmEnvCleanup()
1408
+ } catch (cleanupError) {
1409
+ cleanupErrors.push(cleanupError)
1410
+ return __retainFailedWasiRollback(cleanupErrors)
1411
+ }
1412
+ if (__isThenable(drainResult)) {
1413
+ return Promise.resolve(drainResult).then(
1414
+ () => __destroyContextForWasiRollback(cleanupErrors),
1415
+ (cleanupError) => {
1416
+ cleanupErrors.push(cleanupError)
1417
+ return __retainFailedWasiRollback(cleanupErrors)
1418
+ },
1419
+ )
1420
+ }
1421
+ return __destroyContextForWasiRollback(cleanupErrors)
1422
+ }
1423
+
1424
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1425
+ // work before the load goes on to fail, and this rollback tears down exactly
1426
+ // what those completions need. Settle them while everything is still live,
1427
+ // before the barrier and the teardown above take that away.
1428
+ //
1429
+ // A drain that could not finish leaves async work possibly outstanding, and
1430
+ // destroying the context over it would strand exactly what this rollback is
1431
+ // there to settle. Stop short and retain instead — the same trade
1432
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1433
+ // the context stays reclaimable by a retry or by this flavor's own
1434
+ // last-resort teardown.
1435
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1436
+ __retainFailedWasiRollback([cleanupError])
1437
+ let asyncWorkResult
639
1438
  try {
640
- __prepareWasmEnvCleanup()
641
- drainResult = __drainWasmEnvCleanup()
1439
+ asyncWorkResult = __drainWasiAsyncWork()
642
1440
  } catch (cleanupError) {
643
- cleanupErrors.push(cleanupError)
644
- settlementsUnreached = true
1441
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
645
1442
  }
646
- if (__isThenable(drainResult)) {
647
- return Promise.resolve(drainResult).then(
648
- () => __destroyContextForWasiRollback(cleanupErrors),
649
- (cleanupError) => {
650
- cleanupErrors.push(cleanupError)
651
- return __retainFailedWasiRollback(cleanupErrors)
652
- },
1443
+ if (__isThenable(asyncWorkResult)) {
1444
+ return Promise.resolve(asyncWorkResult).then(
1445
+ __rollbackWasmEnvForWasiInitialization,
1446
+ __retainAfterAsyncWorkDrainFailure,
653
1447
  )
654
1448
  }
655
- if (settlementsUnreached) {
656
- return __retainFailedWasiRollback(cleanupErrors)
657
- }
658
- return __destroyContextForWasiRollback(cleanupErrors)
1449
+ return __rollbackWasmEnvForWasiInitialization()
659
1450
  }
660
1451
 
661
1452
  const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
@@ -765,7 +1556,10 @@ function __disposeWasiBindingAtExit() {
765
1556
  // settlements the way __startWasiDisposal does — the process is leaving and
766
1557
  // those promises have no observer left anyway. Run the synchronous teardown
767
1558
  // directly. Every step is idempotent, which also makes this the synchronous
768
- // finish for a disposal that is still waiting for its drain.
1559
+ // finish for a disposal that is still waiting for its drain — and, through
1560
+ // __prepareWasmEnvCleanup, for one still parked between the two halves of
1561
+ // the environment cleanup barrier: there are no turns left to poll with, so
1562
+ // this closes that handshake with `…_finish`, which joins.
769
1563
  try {
770
1564
  __destroyEmnapiContext()
771
1565
  } catch {}
@@ -831,7 +1625,11 @@ function __captureEmnapiAutoDestroyListener() {
831
1625
  try {
832
1626
  const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
833
1627
  try {
834
- __emnapiContext = __emnapiCreateContext({ autoDestroy: false })
1628
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1629
+ __emnapiCreateContext({ autoDestroy: false }),
1630
+ __prepareWasmEnvCleanup,
1631
+ __isPreparingWasmEnvCleanup,
1632
+ )
835
1633
  // emnapi 2.x still registers an unconditional once-listener for
836
1634
  // beforeExit that auto-destroys the context, and suppressDestroy() only
837
1635
  // neutralizes its callback without removing it. This loader owns cleanup
@@ -859,7 +1657,11 @@ try {
859
1657
  }
860
1658
  })(),
861
1659
  reuseWorker: true,
862
- plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
1660
+ plugins: [
1661
+ __captureWasiThreadManager,
1662
+ __emnapiAsyncWorkPlugin,
1663
+ __emnapiTSFNPlugin,
1664
+ ],
863
1665
  wasi: __wasi,
864
1666
  onCreateWorker() {
865
1667
  const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
@@ -889,6 +1691,10 @@ try {
889
1691
  }
890
1692
 
891
1693
  worker.unref()
1694
+ // These stubs stay in place for the worker's whole life, disposal
1695
+ // included: `__keepEventLoopAliveUntil` is what holds the process open
1696
+ // while a termination is pending, precisely because a worker's own
1697
+ // references cannot be relied on for it.
892
1698
  }
893
1699
  return worker
894
1700
  },
@@ -911,6 +1717,22 @@ try {
911
1717
  },
912
1718
  }))
913
1719
  __publishWasiDispose(__napiModule.exports)
1720
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
1721
+ // export does not travel with it, so carry the marker on the binding itself
1722
+ // too. Three things pin the stamp to exactly this spot:
1723
+ // - inside this `try`, because the guard throws on a
1724
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
1725
+ // catch below tears the environment — context, workers, exit listener —
1726
+ // back down;
1727
+ // - after the async runtime host install, which hands this same object to
1728
+ // addon-provided registration functions that may put anything on it;
1729
+ // - assigning onto the loader's own `module.exports`, which is still the
1730
+ // original object here, so an addon accessor with a refusing setter is
1731
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
1732
+ // export detection — reads the static `module.exports.<name> =` either
1733
+ // way, and the later `module.exports = __napiModule.exports` does not
1734
+ // undo that.
1735
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
914
1736
  __registerWasiExitListener()
915
1737
  } catch (error) {
916
1738
  const rollback = {