@phron/image-wasm32-wasip1 0.0.0 → 0.1.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.
@@ -0,0 +1,1626 @@
1
+ // napi-rs-artifact-metadata:{"version":2,"rootEntry":"native.cjs","exports":["apiUrl","encodePath","infoUrl","optionExpires","optionFormat","optionGravity","optionHeight","optionPreset","optionQuality","optionRaw","optionResize","optionWidth","publicUrl","roundedExpiry","signUrl"],"managedRootEntries":["browser.js","native.cjs","phron-image.wasm","phron-image.debug.wasm"]}
2
+ /* eslint-disable */
3
+ /* auto-generated by NAPI-RS */
4
+
5
+ const __napiBindingTarget = 'wasm32-wasip1'
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
+
55
+ const __nodeFs = require('node:fs')
56
+ const __nodePath = require('node:path')
57
+ const { WASI: __nodeWASI } = require('node:wasi')
58
+
59
+ const {
60
+ emnapiAsyncWorkPlugin: __emnapiAsyncWorkPlugin,
61
+ emnapiTSFNPlugin: __emnapiTSFNPlugin,
62
+ instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
63
+ } = require('@napi-rs/wasm-runtime')
64
+ const { createContext: __emnapiCreateContext } = require('@emnapi/runtime')
65
+
66
+ const __cwd = process.cwd()
67
+ const __rootDir = __nodePath.parse(__cwd).root
68
+ const __hostRoot =
69
+ process.platform === 'android' ? __cwd : __rootDir
70
+
71
+ const __wasi = new __nodeWASI({
72
+ version: 'preview1',
73
+ env: process.env,
74
+ preopens: {
75
+ [__rootDir]: __hostRoot,
76
+ [__hostRoot]: __hostRoot,
77
+ },
78
+ })
79
+
80
+ const __wasmMemory = new WebAssembly.Memory({
81
+ initial: 4000,
82
+ maximum: 65536,
83
+ })
84
+
85
+ let __wasmFilePath = __nodePath.join(__dirname, 'phron-image.wasm32-wasip1.wasm')
86
+ const __wasmDebugFilePath = __nodePath.join(__dirname, 'phron-image.wasm32-wasip1.debug.wasm')
87
+
88
+ if (__nodeFs.existsSync(__wasmDebugFilePath)) {
89
+ __wasmFilePath = __wasmDebugFilePath
90
+ } else if (!__nodeFs.existsSync(__wasmFilePath)) {
91
+ const __wasiPackageEntry = require.resolve('@phron/image-wasm32-wasip1')
92
+ const __packagedWasmFilePath = __nodePath.join(
93
+ __nodePath.dirname(__wasiPackageEntry),
94
+ 'phron-image.wasm32-wasip1.wasm',
95
+ )
96
+ if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
97
+ throw new Error(
98
+ '@phron/image-wasm32-wasip1 is installed but is missing phron-image.wasm32-wasip1.wasm.',
99
+ )
100
+ }
101
+ __wasmFilePath = __packagedWasmFilePath
102
+ }
103
+
104
+ const __wasmFile = __nodeFs.readFileSync(__wasmFilePath)
105
+ let __emnapiContext
106
+
107
+ const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
108
+ const __wasiWorkers = new Set()
109
+ // The thread manager has to be reachable *before* anything that can throw
110
+ // during load or registration. Initialization can fail after the pool has
111
+ // already spawned workers, and the rollback still has to mark their
112
+ // terminations as expected — but `__napiModule` is assigned only when
113
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
114
+ // plugin factory runs while the emnapi module is being created, before the
115
+ // wasm is loaded and before any registration function runs, and its context
116
+ // carries the very same manager instance.
117
+ let __wasiThreadManager
118
+
119
+ function __captureWasiThreadManager(context) {
120
+ if (context && context.PThread) {
121
+ __wasiThreadManager = context.PThread
122
+ }
123
+ return {}
124
+ }
125
+
126
+ function __getWasiThreadManager() {
127
+ const manager =
128
+ __wasiThreadManager !== undefined
129
+ ? __wasiThreadManager
130
+ : __napiModule
131
+ ? __napiModule.PThread
132
+ : undefined
133
+ if (manager && typeof manager.terminateWorker === 'function') {
134
+ return manager
135
+ }
136
+ return undefined
137
+ }
138
+ let __napiInstance
139
+ let __emnapiContextDestroyed = false
140
+ let __emnapiContextDestroyPromise
141
+ let __emnapiWasmEnvCleanupPrepared = false
142
+ let __emnapiWasmEnvCleanupPreparing = false
143
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
144
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
145
+ // tell those two apart on its own: it is raised both for a purely synchronous
146
+ // frame — which must not be re-entered, and which nothing outside it can
147
+ // finish — and across this window, which spans real event-loop turns, so a
148
+ // caller that cannot yield can land in the middle of one. That caller can close
149
+ // this window, because `…_finish` is idempotent and joins, which is exactly
150
+ // what the single call does. See `__prepareWasmEnvCleanup`.
151
+ let __finishParkedWasmEnvCleanup
152
+ // Raised while a caller that can still yield is driving the barrier, so the
153
+ // queue it leaves behind is expected rather than lost. See
154
+ // `__reportUnreachedWasmEnvSettlements`.
155
+ let __emnapiWasmEnvCleanupYielding = false
156
+ let __emnapiWasmEnvSettlementLossReported = false
157
+ let __emnapiWasmEnvCleanupRan = false
158
+ let __emnapiWasmEnvCleanupDrained = false
159
+ let __emnapiWasmEnvCleanupDrainPromise
160
+ let __wasiDisposed = false
161
+ let __wasiAsyncWorkDrainPromise
162
+ let __wasiDisposePromise
163
+ let __completeWasiDisposal = function () {}
164
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
165
+ // that stopped short of destroying the context. See
166
+ // `__rollbackWasiInitialization`.
167
+ let __retainWasiRollbackForRetry = function () {}
168
+
169
+ function __isThenable(value) {
170
+ return (
171
+ value !== null &&
172
+ (typeof value === 'object' || typeof value === 'function') &&
173
+ typeof value.then === 'function'
174
+ )
175
+ }
176
+
177
+ function __createCleanupError(errors, message) {
178
+ if (errors.length === 1) {
179
+ return errors[0]
180
+ }
181
+ const __AggregateError = globalThis.AggregateError
182
+ if (typeof __AggregateError === 'function') {
183
+ return new __AggregateError(errors, message)
184
+ }
185
+ const error = new Error(message)
186
+ error.errors = errors
187
+ return error
188
+ }
189
+
190
+ function __attachCleanupErrors(error, cleanupErrors) {
191
+ if (cleanupErrors.length === 0) {
192
+ return error
193
+ }
194
+ const cleanupError = __createCleanupError(
195
+ cleanupErrors,
196
+ 'WASI binding cleanup failed',
197
+ )
198
+ try {
199
+ if (
200
+ error &&
201
+ (typeof error === 'object' || typeof error === 'function')
202
+ ) {
203
+ if (error.cause === undefined) {
204
+ error.cause = cleanupError
205
+ if (error.cause === cleanupError) {
206
+ return error
207
+ }
208
+ }
209
+ if (Array.isArray(error.cleanupErrors)) {
210
+ error.cleanupErrors.push(cleanupError)
211
+ return error
212
+ } else {
213
+ const attachedCleanupErrors = [cleanupError]
214
+ error.cleanupErrors = attachedCleanupErrors
215
+ if (error.cleanupErrors === attachedCleanupErrors) {
216
+ return error
217
+ }
218
+ }
219
+ }
220
+ } catch {}
221
+ const aggregate = __createCleanupError(
222
+ [error, cleanupError],
223
+ 'WASI binding initialization and cleanup failed',
224
+ )
225
+ try {
226
+ aggregate.cause = error
227
+ } catch {}
228
+ return aggregate
229
+ }
230
+
231
+ function __wrapEmnapiContextDestroyForSettlement(
232
+ context,
233
+ prepareEnvCleanup,
234
+ isPreparingEnvCleanup,
235
+ ) {
236
+ let destroy
237
+ try {
238
+ destroy = context.destroy
239
+ } catch {
240
+ return context
241
+ }
242
+ if (typeof destroy !== 'function') {
243
+ return context
244
+ }
245
+ try {
246
+ Object.defineProperty(context, 'destroy', {
247
+ configurable: true,
248
+ enumerable: false,
249
+ writable: true,
250
+ value: function () {
251
+ // Reentered from a promise hook that fired inside the barrier: the
252
+ // frame running it destroys as soon as it returns.
253
+ if (isPreparingEnvCleanup?.()) {
254
+ return
255
+ }
256
+ prepareEnvCleanup?.()
257
+ return Reflect.apply(destroy, this, arguments)
258
+ },
259
+ })
260
+ } catch {}
261
+ return context
262
+ }
263
+
264
+ function __isPreparingWasmEnvCleanup() {
265
+ return __emnapiWasmEnvCleanupPreparing
266
+ }
267
+
268
+ function __prepareWasmEnvCleanup() {
269
+ if (__emnapiWasmEnvCleanupPrepared) {
270
+ return
271
+ }
272
+ // A handshake parked between its two halves is one this frame can close, and
273
+ // must: every caller of this function is about to destroy the context, and
274
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
275
+ // the last thing the process runs, and `Context.destroy()` takes the
276
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
277
+ // this degrades to exactly the single call below. Leaving it open instead
278
+ // destroys the context with the barrier still raised, the runtime never
279
+ // joined and the workers never drained.
280
+ const finishParked = __finishParkedWasmEnvCleanup
281
+ if (finishParked !== undefined) {
282
+ finishParked()
283
+ __reportUnreachedWasmEnvSettlements()
284
+ return
285
+ }
286
+ if (__emnapiWasmEnvCleanupPreparing) {
287
+ return
288
+ }
289
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
290
+ if (typeof prepare === 'function') {
291
+ // The addon settles the promises it cancels synchronously, under a
292
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
293
+ // here must not reach this export again.
294
+ __emnapiWasmEnvCleanupPreparing = true
295
+ try {
296
+ prepare()
297
+ } finally {
298
+ __emnapiWasmEnvCleanupPreparing = false
299
+ }
300
+ __emnapiWasmEnvCleanupRan = true
301
+ __reportUnreachedWasmEnvSettlements()
302
+ }
303
+ __emnapiWasmEnvCleanupPrepared = true
304
+ }
305
+
306
+ /**
307
+ * Say so when the barrier leaves settlements queued and nothing is left that
308
+ * could deliver them.
309
+ *
310
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
311
+ * dispatch its queue. Every other caller of the barrier destroys in the same
312
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
313
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
314
+ * that queue with a null env and discards it. The promises those settlements
315
+ * were for then hang forever, silently.
316
+ *
317
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
318
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
319
+ * teardown down with it. Destroying anyway is still the right trade — the queue
320
+ * is already unreachable by then.
321
+ */
322
+ function __reportUnreachedWasmEnvSettlements() {
323
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
324
+ return
325
+ }
326
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
327
+ if (typeof pending !== 'function') {
328
+ return
329
+ }
330
+ let queued
331
+ try {
332
+ queued = pending()
333
+ } catch {
334
+ return
335
+ }
336
+ if (!queued) {
337
+ return
338
+ }
339
+ __emnapiWasmEnvSettlementLossReported = true
340
+ try {
341
+ const consoleHost = globalThis.console
342
+ if (consoleHost && typeof consoleHost.error === 'function') {
343
+ consoleHost.error(
344
+ "napi-rs: the wasm environment is being destroyed with " +
345
+ queued +
346
+ " 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.",
347
+ )
348
+ }
349
+ } catch {}
350
+ }
351
+
352
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
353
+ // on, so the drain turns below interleave with that dispatch instead of racing
354
+ // ahead of it on a faster queue.
355
+ const __scheduleMacrotask = (function () {
356
+ if (typeof setImmediate === 'function') {
357
+ return function (callback) {
358
+ setImmediate(callback)
359
+ }
360
+ }
361
+ const __MessageChannel = globalThis.MessageChannel
362
+ if (typeof __MessageChannel === 'function') {
363
+ return function (callback) {
364
+ const channel = new __MessageChannel()
365
+ channel.port1.onmessage = function () {
366
+ channel.port1.onmessage = null
367
+ try {
368
+ channel.port1.close()
369
+ } catch {}
370
+ try {
371
+ channel.port2.close()
372
+ } catch {}
373
+ callback()
374
+ }
375
+ channel.port2.postMessage(null)
376
+ }
377
+ }
378
+ return function (callback) {
379
+ setTimeout(callback, 0)
380
+ }
381
+ })()
382
+
383
+ // A real, *referenced* timer, for waits that must let the whole host make
384
+ // progress between looks — the async-work drain polls the addon rather than
385
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
386
+ // would spin the loop instead of yielding it. Falls back to the macrotask
387
+ // scheduler on a host without timers.
388
+ function __scheduleTimer(callback, delay) {
389
+ const setTimer = globalThis.setTimeout
390
+ if (typeof setTimer !== 'function') {
391
+ __scheduleMacrotask(callback)
392
+ return
393
+ }
394
+ try {
395
+ setTimer(callback, delay)
396
+ } catch {
397
+ __scheduleMacrotask(callback)
398
+ }
399
+ }
400
+
401
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
402
+ // reason the async-work drain uses one: this polls the addon instead of
403
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
404
+ // the loop instead of yielding it.
405
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
406
+ // Arrivals it takes before the poll paces on the host's timers alone. One
407
+ // proves nothing: a timer armed before the host's timers stopped still fires.
408
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
409
+ // How long a parked turn's own timer must already have been due before a
410
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
411
+ // against the event loop's clock, which is read once per iteration, while
412
+ // these are `Date.now()` readings taken part-way through one, so the two
413
+ // drift apart by however long the loop has been inside the current iteration.
414
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
415
+ // How long a backup itself waits. What is left of it after the slack and one
416
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
417
+ // parked turn from the last backup armed while the host's timers still
418
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
419
+ // `__armWasmRuntimePollStallBackup`.
420
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
421
+
422
+ /**
423
+ * Pacing state for one runtime-work poll.
424
+ *
425
+ * Per poll, never per module: whether the host's timers arrive is not a
426
+ * property of the module. A host can lose its timers between two disposals,
427
+ * and in the deferred shape every instance shares this module — one healthy
428
+ * instance must not disarm the fallback for the next one.
429
+ */
430
+ function __createWasmRuntimePollPace() {
431
+ return {
432
+ // Timers armed by *this* poll that have actually arrived.
433
+ arrivals: 0,
434
+ // The turn waiting on a timer alone *right now* — undefined whenever no
435
+ // turn is parked — and when that turn's own timer came due.
436
+ settleTurn: undefined,
437
+ turnTimerDueAt: 0,
438
+ }
439
+ }
440
+
441
+ /**
442
+ * The backup that ends a turn whose timer is never going to arrive.
443
+ *
444
+ * Once the poll paces on the timer alone it has nothing left to fall back on
445
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
446
+ * the turn that parks, and a parked poll schedules nothing that could notice.
447
+ * So every turn arms one of these before it yields, and each one compares due
448
+ * times instead of measuring how long the parked turn has been waiting.
449
+ *
450
+ * Invariant: a parked turn is ended by the newest backup that was armed while
451
+ * the host's timers still worked, and a backup ends a turn only when that
452
+ * turn's own timer was already due a whole window before the backup itself.
453
+ * Neither half turns on how far apart the arms happen to fall — what bounds
454
+ * the rescue is how far back that newest live backup is:
455
+ *
456
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
457
+ * turn due a whole window earlier is still parked proves that turn's timer
458
+ * was dropped rather than merely late. That same comparison is what leaves a
459
+ * healthy host alone: there the turn's timer has already run and cleared
460
+ * `settleTurn` before any backup due after it can look.
461
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
462
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
463
+ * primitives and the macrotask wins, so such a turn can end with its own
464
+ * timer — and the backup armed one line before it — already dead. The
465
+ * arrival that then flips the poll onto the timer alone can itself be a
466
+ * timer armed before the host's timers died. So the turn that parks can sit
467
+ * two turns past the last live arm, and the newest live backup is due
468
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
469
+ * Arming on every turn is what holds it to two, rather than however far back
470
+ * a throttle last let one through.
471
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
472
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
473
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
474
+ * Past that the turn stays parked and the disposal promise never settles.
475
+ * The bound is deliberate: reaching it takes a host that drops timers
476
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
477
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
478
+ * the second.
479
+ *
480
+ * The poll then goes back to arming both primitives until two fresh arrivals
481
+ * prove the timers again. A host that stops running the timers it has
482
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
483
+ * pending rather than wedging the thread — the same outcome as a blocking
484
+ * closure that never returns. Unreferenced wherever the host allows it: the
485
+ * poll's own turn timers are what keep the loop alive, never these.
486
+ */
487
+ function __armWasmRuntimePollStallBackup(pace) {
488
+ const setTimer = globalThis.setTimeout
489
+ if (typeof setTimer !== 'function') {
490
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
491
+ // already, and that one cannot park.
492
+ return
493
+ }
494
+ // Read before arming, so this never claims to be due earlier than the timer
495
+ // actually is: a backup ends a turn only when it is provably due after it.
496
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
497
+ let handle
498
+ try {
499
+ handle = setTimer(() => {
500
+ const settleTurn = pace.settleTurn
501
+ if (
502
+ !settleTurn ||
503
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
504
+ ) {
505
+ // No turn is parked, or the parked one's timer came due too close to
506
+ // this backup to call it dropped — it may still arrive, and the turn
507
+ // that armed it armed a backup due a whole window after *that*.
508
+ return
509
+ }
510
+ pace.arrivals = 0
511
+ pace.settleTurn = undefined
512
+ settleTurn()
513
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
514
+ } catch {
515
+ return
516
+ }
517
+ if (handle && typeof handle.unref === 'function') {
518
+ try {
519
+ handle.unref()
520
+ } catch {}
521
+ }
522
+ }
523
+
524
+ /**
525
+ * One turn of the runtime-work poll.
526
+ *
527
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
528
+ * missing or throws, but not when it is present, returns a handle and never
529
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
530
+ * host whose timers belong to an IO context that is already gone. That host
531
+ * would park this poll forever, and the poll is unbounded, so nothing would
532
+ * ever call `…_finish`.
533
+ *
534
+ * Arm both primitives until timers armed by this poll have arrived twice, and
535
+ * let whichever lands first end the turn; the loser resolves nothing. A host
536
+ * with working timers therefore pays the double arming for the first turn or
537
+ * two — the macrotask wins the race, but the timers behind it still arrive and
538
+ * are counted — and paces on the timer alone from then on, instead of spinning
539
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
540
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
541
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
542
+ * which ends the parked turn and puts this poll back on both.
543
+ */
544
+ function __yieldWasmRuntimePollTurn(pace) {
545
+ // Armed before the turn yields, and by every turn: what rescues a parked
546
+ // turn has to have been armed while the host's timers still worked, and the
547
+ // turn that parks is the one whose own timer is already dead.
548
+ __armWasmRuntimePollStallBackup(pace)
549
+ return new Promise((resolve) => {
550
+ let settled = false
551
+ const settle = () => {
552
+ if (settled) {
553
+ return
554
+ }
555
+ settled = true
556
+ if (pace.settleTurn === settle) {
557
+ // Nothing is parked any more: a backup running later must not read a
558
+ // due time this turn has already answered.
559
+ pace.settleTurn = undefined
560
+ }
561
+ resolve()
562
+ }
563
+ __scheduleTimer(() => {
564
+ pace.arrivals++
565
+ settle()
566
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
567
+ // Read next to the arming it describes; see
568
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
569
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
570
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
571
+ __scheduleMacrotask(settle)
572
+ return
573
+ }
574
+ // Paced by the timer alone from here; the backup is what ends this turn if
575
+ // the timer never arrives.
576
+ pace.settleTurn = settle
577
+ pace.turnTimerDueAt = turnTimerDueAt
578
+ })
579
+ }
580
+
581
+ /**
582
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
583
+ * event-loop turns in the middle.
584
+ *
585
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
586
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
587
+ * waits on is this one, the only thread that can give a running blocking
588
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
589
+ * for work that can never finish. The addon's two-phase form splits that:
590
+ * `…_begin` stops the runtime without joining and reports whether anything is
591
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
592
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
593
+ * entire point.
594
+ *
595
+ * The poll has no deadline, for the same reason the async-work drain below has
596
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
597
+ * work it would join is the work that is waiting for a turn from this thread —
598
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
599
+ * thread can no longer be reached. A blocking closure that never returns keeps
600
+ * the disposal promise pending instead, exactly as a task whose `execute` never
601
+ * returns already keeps an *undisposed* process alive. The host contract is in
602
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
603
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
604
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
605
+ *
606
+ * Feature-detected like every other export in this teardown, so an addon built
607
+ * against a napi crate that predates the split keeps the single blocking call.
608
+ * Returns nothing whenever the handshake finished without yielding, which keeps
609
+ * an idle disposal synchronous.
610
+ */
611
+ function __prepareWasmEnvCleanupWithTurns() {
612
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
613
+ return
614
+ }
615
+ const exports = __napiInstance?.exports
616
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
617
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
618
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
619
+ // No split to use. The settlement drain still follows this, so the queue
620
+ // the single call leaves behind is expected rather than lost.
621
+ __emnapiWasmEnvCleanupYielding = true
622
+ try {
623
+ __prepareWasmEnvCleanup()
624
+ } finally {
625
+ __emnapiWasmEnvCleanupYielding = false
626
+ }
627
+ return
628
+ }
629
+ const workPending = exports?.napi_wasm_runtime_work_pending
630
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
631
+ // from one of the JavaScript handlers they run is the same no-op it is inside
632
+ // the single call: the barrier is up and the runtime is mid-teardown, and
633
+ // destroying between the halves would strand exactly what this delivers.
634
+ __emnapiWasmEnvCleanupPreparing = true
635
+ let live
636
+ try {
637
+ live = begin()
638
+ } catch (error) {
639
+ __emnapiWasmEnvCleanupPreparing = false
640
+ throw error
641
+ }
642
+ __emnapiWasmEnvCleanupRan = true
643
+ const finishCleanup = () => {
644
+ if (__emnapiWasmEnvCleanupPrepared) {
645
+ // Already closed by a caller that could not yield — the 'exit' teardown
646
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
647
+ // is idempotent, but the flags it lowers are not: running it again here
648
+ // would clear a `preparing` some later barrier had raised.
649
+ return
650
+ }
651
+ __finishParkedWasmEnvCleanup = undefined
652
+ try {
653
+ finish()
654
+ } finally {
655
+ __emnapiWasmEnvCleanupPreparing = false
656
+ }
657
+ __emnapiWasmEnvCleanupPrepared = true
658
+ }
659
+ if (!live || typeof workPending !== 'function') {
660
+ finishCleanup()
661
+ return
662
+ }
663
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
664
+ // a caller that cannot yield is entitled to end this handshake itself.
665
+ __finishParkedWasmEnvCleanup = finishCleanup
666
+ return (async () => {
667
+ // Unbounded, exactly like the async-work drain below. The wait ends when
668
+ // the addon reports its runtime work finished; the turns spent here are
669
+ // what let that happen at all.
670
+ const pace = __createWasmRuntimePollPace()
671
+ for (;;) {
672
+ await __yieldWasmRuntimePollTurn(pace)
673
+ try {
674
+ if (!workPending()) {
675
+ return
676
+ }
677
+ } catch {
678
+ // A trap is the only way this fails, and a trapped instance has no
679
+ // reachable work left. Stop polling and finish.
680
+ return
681
+ }
682
+ }
683
+ })().then(finishCleanup, finishCleanup)
684
+ }
685
+
686
+ // Turns to wait for while the addon still reports queued settlements. Reaching
687
+ // zero is the only success. A counter still nonzero at this bound rejects the
688
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
689
+ // destroying the context over a still-queued settlement — the wait stays
690
+ // bounded either way.
691
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
692
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
693
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
694
+ // call made on this thread (two), plus a margin.
695
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
696
+
697
+ /**
698
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
699
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
700
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
701
+ * macrotask — two coalescing turns later, even for a call made on this very
702
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
703
+ * which drains the queue with a null env and *discards* whatever is still in it.
704
+ *
705
+ * So destroying without yielding first strands exactly the promises the barrier
706
+ * exists to settle. Yield real event-loop turns until the addon reports the
707
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
708
+ * macrotask run.
709
+ *
710
+ * Returns nothing when there is nothing to wait for, which keeps disposal
711
+ * synchronous in the common case.
712
+ *
713
+ * The "already drained" flag is set only once a wait has actually finished.
714
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
715
+ * that throws is enough — and a disposal that rejects stays retryable, so
716
+ * marking the drain complete up front would make the retry skip it and destroy
717
+ * the context with the barrier's settlements still queued.
718
+ *
719
+ * A wait that runs out of turns with the counter still nonzero rejects with
720
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
721
+ * "finished" is indistinguishable from the stranding above, and destroying
722
+ * would discard the very settlement the wait was for. The rejection leaves the
723
+ * flag unset and disposal retryable.
724
+ */
725
+ function __drainWasmEnvCleanup() {
726
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
727
+ return
728
+ }
729
+ if (__emnapiWasmEnvCleanupDrainPromise) {
730
+ return __emnapiWasmEnvCleanupDrainPromise
731
+ }
732
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
733
+ const observable = typeof pending === 'function'
734
+ if (observable) {
735
+ let queued
736
+ try {
737
+ queued = pending()
738
+ } catch {
739
+ __emnapiWasmEnvCleanupDrained = true
740
+ return
741
+ }
742
+ if (!queued) {
743
+ __emnapiWasmEnvCleanupDrained = true
744
+ return
745
+ }
746
+ }
747
+ const limit = observable
748
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
749
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
750
+ const drainPromise = (async () => {
751
+ let queued = 0
752
+ for (let turn = 0; turn < limit; turn++) {
753
+ await new Promise((resolve) => {
754
+ __scheduleMacrotask(resolve)
755
+ })
756
+ if (!observable) {
757
+ continue
758
+ }
759
+ try {
760
+ queued = pending()
761
+ } catch {
762
+ return
763
+ }
764
+ if (!queued) {
765
+ return
766
+ }
767
+ }
768
+ if (!observable) {
769
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
770
+ // contract — there is nothing to consult, so finishing the turns is
771
+ // finishing the drain.
772
+ return
773
+ }
774
+ // The counter is still nonzero after every turn the bound allows. The wait
775
+ // stays bounded — but claiming success here would be indistinguishable from
776
+ // the stranding this drain exists to prevent: disposal would go on to
777
+ // destroy the context, whose cleanup hook discards the still-queued
778
+ // settlement with a null env, and the promise it was for hangs forever.
779
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
780
+ // unset, dispose() (and the rollback) decline to destroy, and a later
781
+ // dispose() runs the drain again — by which time the queue has usually been
782
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
783
+ // attempt at most another bounded wait and a rejection, never a stranded
784
+ // promise; the process-exit teardown still reclaims the context.
785
+ const drainError = new Error(
786
+ 'the wasm environment still reports ' +
787
+ queued +
788
+ ' queued settlement(s) after ' +
789
+ limit +
790
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
791
+ )
792
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
793
+ throw drainError
794
+ })().then(
795
+ (value) => {
796
+ // Set only when the wait actually finished AND the queue was seen empty
797
+ // (or is unobservable): a drain that timed out with settlements still
798
+ // queued rejects above and must stay repeatable.
799
+ __emnapiWasmEnvCleanupDrained = true
800
+ __emnapiWasmEnvCleanupDrainPromise = undefined
801
+ return value
802
+ },
803
+ (error) => {
804
+ __emnapiWasmEnvCleanupDrainPromise = undefined
805
+ throw error
806
+ },
807
+ )
808
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
809
+ return drainPromise
810
+ }
811
+
812
+ function __destroyEmnapiContext() {
813
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
814
+ __emnapiContextDestroyed = true
815
+ return
816
+ }
817
+ if (__emnapiContextDestroyPromise) {
818
+ return __emnapiContextDestroyPromise
819
+ }
820
+
821
+ __prepareWasmEnvCleanup()
822
+ if (__isPreparingWasmEnvCleanup()) {
823
+ // Reached from inside the synchronous barrier — a promise hook one of the
824
+ // settlements above ran, which is the reentrancy the destroy wrapper
825
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
826
+ // no-op and answer `undefined`, and recording that as a completed destroy
827
+ // is what makes the frame that *did* start the barrier skip the real one
828
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
829
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
830
+ // moment it returns. The deferred loader carries the same backstop. A
831
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
832
+ // rather than skipping it.
833
+ return
834
+ }
835
+ const result = __emnapiContext.destroy()
836
+ if (!__isThenable(result)) {
837
+ __emnapiContextDestroyed = true
838
+ return
839
+ }
840
+
841
+ const destroyPromise = Promise.resolve(result).then(
842
+ (value) => {
843
+ __emnapiContextDestroyed = true
844
+ return value
845
+ },
846
+ (error) => {
847
+ __emnapiContextDestroyPromise = undefined
848
+ throw error
849
+ },
850
+ )
851
+ __emnapiContextDestroyPromise = destroyPromise
852
+ return destroyPromise
853
+ }
854
+
855
+ /**
856
+ * Holds the event loop open until `work` settles.
857
+ *
858
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
859
+ * binding cannot keep a process alive, and referencing them again for the
860
+ * termination does not hold either — emnapi unreferences a worker the moment it
861
+ * reports `async-thread-ready`, which for a worker that was still starting
862
+ * lands *after* the termination began. Without a handle of its own, an
863
+ * `await dispose()` with nothing else pending exits the process with its
864
+ * promise unsettled, and everything after the `await` is skipped.
865
+ *
866
+ * The timer is cleared as soon as the work settles, so this never outlives the
867
+ * disposal that asked for it.
868
+ */
869
+ function __keepEventLoopAliveUntil(work) {
870
+ const setTimer = globalThis.setInterval
871
+ const clearTimer = globalThis.clearInterval
872
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
873
+ return work
874
+ }
875
+ let timer
876
+ try {
877
+ timer = setTimer(function () {}, 50)
878
+ } catch {
879
+ return work
880
+ }
881
+ const release = function () {
882
+ try {
883
+ clearTimer(timer)
884
+ } catch {}
885
+ }
886
+ return work.then(
887
+ (value) => {
888
+ release()
889
+ return value
890
+ },
891
+ (error) => {
892
+ release()
893
+ throw error
894
+ },
895
+ )
896
+ }
897
+
898
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
899
+ // ends when the addon reports zero, so this only decides how promptly disposal
900
+ // notices — not how long it waits.
901
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
902
+
903
+ /**
904
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
905
+ * would strand it.
906
+ *
907
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
908
+ * it is observable from JavaScript: the threadless archive resolves
909
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
910
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
911
+ * imports nor exports those symbols and the only brackets a loader could watch
912
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
913
+ * functions. The addon is the one place both flavors go through, so it answers
914
+ * for both, through the same kind of handshake the settlement drain uses:
915
+ *
916
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
917
+ * started. Those completion callbacks run with `napi_cancelled`, which
918
+ * napi-rs turns into a promise rejected with an `AbortError`.
919
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
920
+ * callback. Work already executing refuses cancellation and stays counted
921
+ * until it finishes normally — which it can, because this runs before the
922
+ * barrier, before `Context.destroy()` and before anything is terminated.
923
+ *
924
+ * Both exports are optional: an addon built against a napi crate that predates
925
+ * them drains nothing and keeps the previous behavior, exactly as the
926
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
927
+ *
928
+ * Returns nothing when there is nothing outstanding, which keeps disposal
929
+ * synchronous in the common case. The promise it returns otherwise never
930
+ * rejects.
931
+ *
932
+ * The wait has no deadline, and that is the point: giving up would destroy the
933
+ * environment with a completion callback still owed, which is the stranding
934
+ * this exists to prevent. A task whose `execute` never returns already keeps an
935
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
936
+ * rather than inventing a bound it cannot honor.
937
+ *
938
+ * Safe to call from inside a completion callback, which is reachable: settling
939
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
940
+ * being handed back, a threadsafe-function callback — and that JavaScript can
941
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
942
+ *
943
+ * - The addon keeps a work registered until its completion callback
944
+ * *finishes*, so the count read here is at least one and this takes the
945
+ * polling path instead of declaring the environment drained and tearing it
946
+ * down from inside the frame that is still settling a promise.
947
+ * - The poll is a timer, so it cannot run until the callback has returned to
948
+ * the host — by which time that work has left the registry. The count the
949
+ * next poll reads is the one taken after the callback finished.
950
+ *
951
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
952
+ * nested call joins this disposal rather than starting a second one.
953
+ */
954
+ function __drainWasiAsyncWork() {
955
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
956
+ return __wasiAsyncWorkDrainPromise
957
+ }
958
+ const exports = __napiInstance?.exports
959
+ const pending = exports?.napi_wasm_async_work_pending
960
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
961
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
962
+ return
963
+ }
964
+
965
+ const readPending = () => {
966
+ try {
967
+ return pending()
968
+ } catch (error) {
969
+ // A trap is the only way this call fails: it reads a counter and cannot
970
+ // allocate or call back into JavaScript. A trapped instance can no longer
971
+ // run anything, so its outstanding work is unreachable by definition —
972
+ // there is nothing left to wait for, and refusing to dispose would only
973
+ // keep a dead instance and its stuck counter alive. Best-effort here is
974
+ // the honest answer, and it is what disposal did before this drain
975
+ // existed.
976
+ //
977
+ // Only a trap. Anything else means the export is not what this loader
978
+ // thinks it is, which is a defect worth surfacing rather than disposing
979
+ // over.
980
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
981
+ return 0
982
+ }
983
+ throw error
984
+ }
985
+ }
986
+
987
+ if (!readPending()) {
988
+ return
989
+ }
990
+ try {
991
+ cancelPending()
992
+ } catch {
993
+ // Cancellation is an optimization: it bounds the wait by the work already
994
+ // executing. Failing it only means waiting for the whole queue instead.
995
+ }
996
+ if (!readPending()) {
997
+ return
998
+ }
999
+
1000
+ const drainPromise = __keepEventLoopAliveUntil(
1001
+ (async () => {
1002
+ while (readPending()) {
1003
+ await new Promise((resolve) => {
1004
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1005
+ })
1006
+ }
1007
+ })(),
1008
+ ).then(
1009
+ () => {
1010
+ __wasiAsyncWorkDrainPromise = undefined
1011
+ },
1012
+ (error) => {
1013
+ // A wait that could not run is not a wait that finished. The only way
1014
+ // here is a host whose timers and macrotask primitives all refuse, and
1015
+ // the work is still outstanding — reporting success would destroy the
1016
+ // environment over it, which is the stranding this exists to prevent.
1017
+ // Reject instead: disposal stays retryable, and the context is not
1018
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1019
+ __wasiAsyncWorkDrainPromise = undefined
1020
+ throw error
1021
+ },
1022
+ )
1023
+ __wasiAsyncWorkDrainPromise = drainPromise
1024
+ return drainPromise
1025
+ }
1026
+
1027
+ /**
1028
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1029
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1030
+ * the manager's `exit` listener instead, which reports
1031
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1032
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1033
+ * promise, so disposal never settles and the process dies with an uncaught
1034
+ * exception. Mark the termination through the manager first.
1035
+ *
1036
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1037
+ * the initialization rollback runs on the one path where instantiation never
1038
+ * returned, so `__napiModule` is still undefined there while the workers it
1039
+ * spawned are already registered and loaded.
1040
+ *
1041
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1042
+ */
1043
+ function __terminateWasiWorkers() {
1044
+ const cleanupErrors = []
1045
+ const pending = []
1046
+ const threadManager = __getWasiThreadManager()
1047
+
1048
+ for (const worker of __wasiWorkers) {
1049
+ let result
1050
+ try {
1051
+ if (threadManager) {
1052
+ threadManager.terminateWorker(worker)
1053
+ // `terminateWorker` leaves behind a reporter that logs every message
1054
+ // still queued on the port, which Node flushes on exit. Nothing is
1055
+ // listening for those any more.
1056
+ worker.onmessage = undefined
1057
+ }
1058
+ result = worker.terminate()
1059
+ } catch (error) {
1060
+ cleanupErrors.push(error)
1061
+ continue
1062
+ }
1063
+ if (__isThenable(result)) {
1064
+ pending.push(
1065
+ Promise.resolve(result).then(
1066
+ () => {
1067
+ __wasiWorkers.delete(worker)
1068
+ },
1069
+ (error) => {
1070
+ cleanupErrors.push(error)
1071
+ },
1072
+ ),
1073
+ )
1074
+ } else {
1075
+ __wasiWorkers.delete(worker)
1076
+ }
1077
+ }
1078
+
1079
+ const finish = () => {
1080
+ if (cleanupErrors.length > 0) {
1081
+ throw __createCleanupError(
1082
+ cleanupErrors,
1083
+ 'Failed to terminate WASI workers',
1084
+ )
1085
+ }
1086
+ }
1087
+ return pending.length > 0
1088
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1089
+ : finish()
1090
+ }
1091
+
1092
+ function __finishWasiDisposal() {
1093
+ const workerResult = __terminateWasiWorkers()
1094
+ if (__isThenable(workerResult)) {
1095
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
1096
+ }
1097
+ return __completeWasiDisposal()
1098
+ }
1099
+
1100
+ function __continueWasiDisposal() {
1101
+ const destroyResult = __destroyEmnapiContext()
1102
+ if (__isThenable(destroyResult)) {
1103
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
1104
+ }
1105
+ return __finishWasiDisposal()
1106
+ }
1107
+
1108
+ function __drainWasmEnvForWasiDisposal() {
1109
+ const drainResult = __drainWasmEnvCleanup()
1110
+ if (__isThenable(drainResult)) {
1111
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
1112
+ }
1113
+ return __continueWasiDisposal()
1114
+ }
1115
+
1116
+ function __cleanUpWasmEnvForWasiDisposal() {
1117
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1118
+ // for, when the addon has one — then let the settlements it queued actually
1119
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1120
+ // these back to back is what strands them.
1121
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1122
+ if (__isThenable(prepareResult)) {
1123
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1124
+ }
1125
+ return __drainWasmEnvForWasiDisposal()
1126
+ }
1127
+
1128
+ function __startWasiDisposal() {
1129
+ // Outstanding `napi_async_work` goes first, while the environment is still
1130
+ // completely live: the completion callbacks run addon code, and everything
1131
+ // after this point takes that away from them — the barrier shuts the async
1132
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1133
+ // the pool threads removes what would have reported the work finished.
1134
+ const asyncWorkResult = __drainWasiAsyncWork()
1135
+ if (__isThenable(asyncWorkResult)) {
1136
+ return Promise.resolve(asyncWorkResult).then(
1137
+ __cleanUpWasmEnvForWasiDisposal,
1138
+ )
1139
+ }
1140
+ return __cleanUpWasmEnvForWasiDisposal()
1141
+ }
1142
+
1143
+ /**
1144
+ * Disposes this generated WASI binding.
1145
+ *
1146
+ * Access this function with:
1147
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
1148
+ */
1149
+ function __disposeWasiBinding() {
1150
+ if (__wasiDisposePromise) {
1151
+ return __wasiDisposePromise
1152
+ }
1153
+ if (__wasiDisposed) {
1154
+ return Promise.resolve()
1155
+ }
1156
+
1157
+ let resolveDispose
1158
+ let rejectDispose
1159
+ const disposePromise = new Promise((resolve, reject) => {
1160
+ resolveDispose = resolve
1161
+ rejectDispose = reject
1162
+ })
1163
+ __wasiDisposePromise = disposePromise
1164
+
1165
+ let result
1166
+ try {
1167
+ result = __startWasiDisposal()
1168
+ } catch (error) {
1169
+ __wasiDisposePromise = undefined
1170
+ rejectDispose(error)
1171
+ return disposePromise
1172
+ }
1173
+
1174
+ Promise.resolve(result).then(
1175
+ (value) => {
1176
+ __wasiDisposed = true
1177
+ resolveDispose(value)
1178
+ },
1179
+ (error) => {
1180
+ __wasiDisposePromise = undefined
1181
+ rejectDispose(error)
1182
+ },
1183
+ )
1184
+ return disposePromise
1185
+ }
1186
+
1187
+ function __publishWasiDispose(exports) {
1188
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
1189
+ configurable: false,
1190
+ enumerable: false,
1191
+ value: __disposeWasiBinding,
1192
+ writable: false,
1193
+ })
1194
+ }
1195
+
1196
+ function __finishWasiInitializationRollback(cleanupErrors) {
1197
+ let workerResult
1198
+ try {
1199
+ workerResult = __terminateWasiWorkers()
1200
+ } catch (cleanupError) {
1201
+ cleanupErrors.push(cleanupError)
1202
+ return cleanupErrors
1203
+ }
1204
+ if (__isThenable(workerResult)) {
1205
+ return Promise.resolve(workerResult)
1206
+ .catch((cleanupError) => {
1207
+ cleanupErrors.push(cleanupError)
1208
+ })
1209
+ .then(() => cleanupErrors)
1210
+ }
1211
+ return cleanupErrors
1212
+ }
1213
+
1214
+ function __destroyContextForWasiRollback(cleanupErrors) {
1215
+ let destroyResult
1216
+ try {
1217
+ destroyResult = __destroyEmnapiContext()
1218
+ } catch (cleanupError) {
1219
+ cleanupErrors.push(cleanupError)
1220
+ return __finishWasiInitializationRollback(cleanupErrors)
1221
+ }
1222
+ if (__isThenable(destroyResult)) {
1223
+ return Promise.resolve(destroyResult)
1224
+ .catch((cleanupError) => {
1225
+ cleanupErrors.push(cleanupError)
1226
+ })
1227
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
1228
+ }
1229
+ return __finishWasiInitializationRollback(cleanupErrors)
1230
+ }
1231
+
1232
+ /**
1233
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
1234
+ * hands it to whatever this flavor has that can still reclaim it.
1235
+ */
1236
+ function __retainFailedWasiRollback(cleanupErrors) {
1237
+ try {
1238
+ __retainWasiRollbackForRetry()
1239
+ } catch (cleanupError) {
1240
+ cleanupErrors.push(cleanupError)
1241
+ }
1242
+ return cleanupErrors
1243
+ }
1244
+
1245
+ /**
1246
+ * Initialization can fail *after* registration has already run, and registration
1247
+ * runs with a live environment: a module-init hook can start async work and then
1248
+ * return an error, and the promise it created may already have escaped into
1249
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
1250
+ * path needs the same drain the ordinary disposal does — destroying without
1251
+ * yielding discards the queue with a null env and strands the promise.
1252
+ *
1253
+ * Stays synchronous when nothing is queued, which covers every failure before
1254
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
1255
+ *
1256
+ * A barrier or drain that did *not* finish stops the rollback short of
1257
+ * destroying, which is what `dispose()` already does — a rejected drain there
1258
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
1259
+ * two trades, and not because of what it saves:
1260
+ *
1261
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
1262
+ * threadsafe function's cleanup hook, which drains the queue with a null env
1263
+ * and discards it, so a promise that already escaped into JavaScript hangs
1264
+ * forever with nothing left that could ever settle it.
1265
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
1266
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
1267
+ * which this module's scope holds either way. What stopping short retains is
1268
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
1269
+ * - Retry is not theoretical. A rollback that records a cleanup error is
1270
+ * already kept in the process-wide registry above, so re-`require()`ing this
1271
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
1272
+ * means the replay drains again rather than skipping it. Destroying first is
1273
+ * what makes that retained record useless.
1274
+ *
1275
+ * The residual cost is honest: the CJS flavor hands the context to its
1276
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
1277
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
1278
+ * throws while evaluating is permanently errored, so re-importing rethrows
1279
+ * without re-running this file — and there the context stays until the realm
1280
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
1281
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
1282
+ */
1283
+ function __rollbackWasiInitialization() {
1284
+ // The environment teardown this rollback performs, kept nested so it cannot
1285
+ // be reached without the async-work drain below running first.
1286
+ function __rollbackWasmEnvForWasiInitialization() {
1287
+ const cleanupErrors = []
1288
+ let prepareResult
1289
+ try {
1290
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1291
+ } catch (cleanupError) {
1292
+ cleanupErrors.push(cleanupError)
1293
+ return __retainFailedWasiRollback(cleanupErrors)
1294
+ }
1295
+ if (__isThenable(prepareResult)) {
1296
+ return Promise.resolve(prepareResult).then(
1297
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1298
+ (cleanupError) => {
1299
+ cleanupErrors.push(cleanupError)
1300
+ return __retainFailedWasiRollback(cleanupErrors)
1301
+ },
1302
+ )
1303
+ }
1304
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1305
+ }
1306
+
1307
+ // The settlement drain of the rollback above, reached either straight away or
1308
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1309
+ // did not finish never gets here: it retains instead, exactly as a drain that
1310
+ // did not finish does.
1311
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1312
+ let drainResult
1313
+ try {
1314
+ drainResult = __drainWasmEnvCleanup()
1315
+ } catch (cleanupError) {
1316
+ cleanupErrors.push(cleanupError)
1317
+ return __retainFailedWasiRollback(cleanupErrors)
1318
+ }
1319
+ if (__isThenable(drainResult)) {
1320
+ return Promise.resolve(drainResult).then(
1321
+ () => __destroyContextForWasiRollback(cleanupErrors),
1322
+ (cleanupError) => {
1323
+ cleanupErrors.push(cleanupError)
1324
+ return __retainFailedWasiRollback(cleanupErrors)
1325
+ },
1326
+ )
1327
+ }
1328
+ return __destroyContextForWasiRollback(cleanupErrors)
1329
+ }
1330
+
1331
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1332
+ // work before the load goes on to fail, and this rollback tears down exactly
1333
+ // what those completions need. Settle them while everything is still live,
1334
+ // before the barrier and the teardown above take that away.
1335
+ //
1336
+ // A drain that could not finish leaves async work possibly outstanding, and
1337
+ // destroying the context over it would strand exactly what this rollback is
1338
+ // there to settle. Stop short and retain instead — the same trade
1339
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1340
+ // the context stays reclaimable by a retry or by this flavor's own
1341
+ // last-resort teardown.
1342
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1343
+ __retainFailedWasiRollback([cleanupError])
1344
+ let asyncWorkResult
1345
+ try {
1346
+ asyncWorkResult = __drainWasiAsyncWork()
1347
+ } catch (cleanupError) {
1348
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
1349
+ }
1350
+ if (__isThenable(asyncWorkResult)) {
1351
+ return Promise.resolve(asyncWorkResult).then(
1352
+ __rollbackWasmEnvForWasiInitialization,
1353
+ __retainAfterAsyncWorkDrainFailure,
1354
+ )
1355
+ }
1356
+ return __rollbackWasmEnvForWasiInitialization()
1357
+ }
1358
+
1359
+ const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
1360
+ const __wasiRollbackRegistryKey =
1361
+ typeof __filename === 'string' ? __filename : __wasmFilePath
1362
+
1363
+ function __getWasiRollbackRegistry() {
1364
+ const existing = process[__wasiRollbackRegistrySymbol]
1365
+ if (existing !== undefined) {
1366
+ if (!(existing instanceof Map)) {
1367
+ throw new TypeError(
1368
+ 'The process-wide NAPI-RS WASI rollback registry is invalid',
1369
+ )
1370
+ }
1371
+ return existing
1372
+ }
1373
+ const registry = new Map()
1374
+ Object.defineProperty(process, __wasiRollbackRegistrySymbol, {
1375
+ configurable: false,
1376
+ enumerable: false,
1377
+ value: registry,
1378
+ writable: false,
1379
+ })
1380
+ return registry
1381
+ }
1382
+
1383
+ const __wasiRollbackRegistry = __getWasiRollbackRegistry()
1384
+
1385
+ function __completeWasiInitializationRollback(record, cleanupErrors) {
1386
+ try {
1387
+ if (cleanupErrors.length === 0) {
1388
+ if (
1389
+ __wasiRollbackRegistry.get(__wasiRollbackRegistryKey) === record
1390
+ ) {
1391
+ __wasiRollbackRegistry.delete(__wasiRollbackRegistryKey)
1392
+ }
1393
+ return
1394
+ }
1395
+ record.error = __attachCleanupErrors(record.error, cleanupErrors)
1396
+ } catch (cleanupError) {
1397
+ try {
1398
+ record.error = __createCleanupError(
1399
+ [record.error, cleanupError],
1400
+ 'WASI binding initialization and cleanup failed',
1401
+ )
1402
+ } catch {}
1403
+ } finally {
1404
+ record.active = false
1405
+ record.promise = undefined
1406
+ }
1407
+ }
1408
+
1409
+ function __runWasiInitializationRollback(record) {
1410
+ if (record.active) {
1411
+ return
1412
+ }
1413
+ record.active = true
1414
+
1415
+ let rollbackResult
1416
+ try {
1417
+ rollbackResult = record.rollback()
1418
+ } catch (cleanupError) {
1419
+ __completeWasiInitializationRollback(record, [cleanupError])
1420
+ return
1421
+ }
1422
+
1423
+ if (!__isThenable(rollbackResult)) {
1424
+ __completeWasiInitializationRollback(record, rollbackResult)
1425
+ return
1426
+ }
1427
+
1428
+ record.promise = Promise.resolve(rollbackResult).then(
1429
+ (cleanupErrors) => {
1430
+ __completeWasiInitializationRollback(record, cleanupErrors)
1431
+ },
1432
+ (cleanupError) => {
1433
+ __completeWasiInitializationRollback(record, [cleanupError])
1434
+ },
1435
+ )
1436
+ }
1437
+
1438
+ const __pendingWasiRollback = __wasiRollbackRegistry.get(
1439
+ __wasiRollbackRegistryKey,
1440
+ )
1441
+ if (__pendingWasiRollback !== undefined) {
1442
+ __runWasiInitializationRollback(__pendingWasiRollback)
1443
+ throw __pendingWasiRollback.error
1444
+ }
1445
+
1446
+ let __wasiModule
1447
+ let __napiModule
1448
+ let __wasiExitListenerRegistered = false
1449
+
1450
+ function __removeWasiExitListener() {
1451
+ if (
1452
+ __wasiExitListenerRegistered &&
1453
+ typeof process.removeListener === 'function'
1454
+ ) {
1455
+ process.removeListener('exit', __disposeWasiBindingAtExit)
1456
+ }
1457
+ __wasiExitListenerRegistered = false
1458
+ }
1459
+
1460
+ function __disposeWasiBindingAtExit() {
1461
+ __wasiExitListenerRegistered = false
1462
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
1463
+ // settlements the way __startWasiDisposal does — the process is leaving and
1464
+ // those promises have no observer left anyway. Run the synchronous teardown
1465
+ // directly. Every step is idempotent, which also makes this the synchronous
1466
+ // finish for a disposal that is still waiting for its drain — and, through
1467
+ // __prepareWasmEnvCleanup, for one still parked between the two halves of
1468
+ // the environment cleanup barrier: there are no turns left to poll with, so
1469
+ // this closes that handshake with `…_finish`, which joins.
1470
+ try {
1471
+ __destroyEmnapiContext()
1472
+ } catch {}
1473
+ try {
1474
+ const workerResult = __terminateWasiWorkers()
1475
+ if (__isThenable(workerResult)) {
1476
+ void Promise.resolve(workerResult).catch(() => {})
1477
+ }
1478
+ } catch {}
1479
+ }
1480
+
1481
+ function __registerWasiExitListener() {
1482
+ if (
1483
+ !__wasiExitListenerRegistered &&
1484
+ typeof process.once === 'function'
1485
+ ) {
1486
+ process.once('exit', __disposeWasiBindingAtExit)
1487
+ __wasiExitListenerRegistered = true
1488
+ }
1489
+ }
1490
+
1491
+ __completeWasiDisposal = __removeWasiExitListener
1492
+ // A rollback that could not reach the queued settlements keeps the context so
1493
+ // the registry replay above can retry it. Nothing forces that replay to happen,
1494
+ // so hand the context to the same synchronous teardown a successful load uses:
1495
+ // a process that exits without ever retrying still runs the cleanup hooks. The
1496
+ // handler cannot yield, so it does not settle anything — but by then the process
1497
+ // is leaving and those promises have no observer left anyway.
1498
+ __retainWasiRollbackForRetry = __registerWasiExitListener
1499
+
1500
+ function __captureEmnapiAutoDestroyListener() {
1501
+ if (
1502
+ typeof process.prependListener !== 'function' ||
1503
+ typeof process.removeListener !== 'function'
1504
+ ) {
1505
+ return
1506
+ }
1507
+ let __autoDestroyListener
1508
+ const __captureListener = (__event, __listener) => {
1509
+ if (__event === 'beforeExit' && __autoDestroyListener === undefined) {
1510
+ __autoDestroyListener = __listener
1511
+ }
1512
+ }
1513
+ try {
1514
+ // Run before existing newListener hooks so a hook that registers its own
1515
+ // beforeExit listener cannot be mistaken for emnapi's registration.
1516
+ process.prependListener('newListener', __captureListener)
1517
+ } catch {
1518
+ return
1519
+ }
1520
+ return () => {
1521
+ try {
1522
+ process.removeListener('newListener', __captureListener)
1523
+ } catch {}
1524
+ if (__autoDestroyListener !== undefined) {
1525
+ try {
1526
+ process.removeListener('beforeExit', __autoDestroyListener)
1527
+ } catch {}
1528
+ }
1529
+ }
1530
+ }
1531
+
1532
+ try {
1533
+ const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
1534
+ try {
1535
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1536
+ __emnapiCreateContext({ autoDestroy: false }),
1537
+ __prepareWasmEnvCleanup,
1538
+ __isPreparingWasmEnvCleanup,
1539
+ )
1540
+ // emnapi 2.x still registers an unconditional once-listener for
1541
+ // beforeExit that auto-destroys the context, and suppressDestroy() only
1542
+ // neutralizes its callback without removing it. This loader owns cleanup
1543
+ // through its 'exit' listener, so emnapi's listener is captured and
1544
+ // removed; suppressDestroy() remains the safety net when removal fails.
1545
+ __emnapiContext.suppressDestroy()
1546
+ } finally {
1547
+ // Remove only the exact emnapi callback captured above.
1548
+ __finishAutoDestroyCapture?.()
1549
+ }
1550
+
1551
+ ;({
1552
+ instance: __napiInstance,
1553
+ module: __wasiModule,
1554
+ napiModule: __napiModule,
1555
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
1556
+ context: __emnapiContext,
1557
+ asyncWorkPoolSize: 0,
1558
+ plugins: [
1559
+ __captureWasiThreadManager,
1560
+ __emnapiAsyncWorkPlugin,
1561
+ __emnapiTSFNPlugin,
1562
+ ],
1563
+ wasi: __wasi,
1564
+ overwriteImports(importObject) {
1565
+ importObject.env = {
1566
+ ...importObject.env,
1567
+ ...importObject.napi,
1568
+ ...importObject.emnapi,
1569
+ memory: __wasmMemory,
1570
+ }
1571
+ return importObject
1572
+ },
1573
+ beforeInit({ instance }) {
1574
+ __napiInstance = instance
1575
+ for (const name of Object.keys(instance.exports)) {
1576
+ if (name.startsWith('__napi_register__')) {
1577
+ instance.exports[name]()
1578
+ }
1579
+ }
1580
+ },
1581
+ }))
1582
+ __publishWasiDispose(__napiModule.exports)
1583
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
1584
+ // export does not travel with it, so carry the marker on the binding itself
1585
+ // too. Three things pin the stamp to exactly this spot:
1586
+ // - inside this `try`, because the guard throws on a
1587
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
1588
+ // catch below tears the environment — context, workers, exit listener —
1589
+ // back down;
1590
+ // - after the async runtime host install, which hands this same object to
1591
+ // addon-provided registration functions that may put anything on it;
1592
+ // - assigning onto the loader's own `module.exports`, which is still the
1593
+ // original object here, so an addon accessor with a refusing setter is
1594
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
1595
+ // export detection — reads the static `module.exports.<name> =` either
1596
+ // way, and the later `module.exports = __napiModule.exports` does not
1597
+ // undo that.
1598
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
1599
+ __registerWasiExitListener()
1600
+ } catch (error) {
1601
+ const rollback = {
1602
+ active: false,
1603
+ error,
1604
+ promise: undefined,
1605
+ rollback: __rollbackWasiInitialization,
1606
+ }
1607
+ __wasiRollbackRegistry.set(__wasiRollbackRegistryKey, rollback)
1608
+ __runWasiInitializationRollback(rollback)
1609
+ throw rollback.error
1610
+ }
1611
+ module.exports = __napiModule.exports
1612
+ module.exports.apiUrl = __napiModule.exports.apiUrl
1613
+ module.exports.encodePath = __napiModule.exports.encodePath
1614
+ module.exports.infoUrl = __napiModule.exports.infoUrl
1615
+ module.exports.optionExpires = __napiModule.exports.optionExpires
1616
+ module.exports.optionFormat = __napiModule.exports.optionFormat
1617
+ module.exports.optionGravity = __napiModule.exports.optionGravity
1618
+ module.exports.optionHeight = __napiModule.exports.optionHeight
1619
+ module.exports.optionPreset = __napiModule.exports.optionPreset
1620
+ module.exports.optionQuality = __napiModule.exports.optionQuality
1621
+ module.exports.optionRaw = __napiModule.exports.optionRaw
1622
+ module.exports.optionResize = __napiModule.exports.optionResize
1623
+ module.exports.optionWidth = __napiModule.exports.optionWidth
1624
+ module.exports.publicUrl = __napiModule.exports.publicUrl
1625
+ module.exports.roundedExpiry = __napiModule.exports.roundedExpiry
1626
+ module.exports.signUrl = __napiModule.exports.signUrl