@frdt/frdt 0.2.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/frdt.wasi.cjs ADDED
@@ -0,0 +1,2144 @@
1
+ // napi-rs-artifact-metadata:{"version":2,"rootEntry":"index.js","exports":["Document","Import","Slot","summarize","versionDate"],"managedRootEntries":["browser.js","index.js","frdt.wasm","frdt.debug.wasm"]}
2
+ /* eslint-disable */
3
+ /* auto-generated by NAPI-RS */
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
+
55
+ const __nodeFs = require('node:fs')
56
+ const __nodePath = require('node:path')
57
+ const { WASI: __nodeWASI } = require('node:wasi')
58
+ const { Worker } = require('node:worker_threads')
59
+
60
+ const {
61
+ emnapiAsyncWorkPlugin: __emnapiAsyncWorkPlugin,
62
+ emnapiTSFNPlugin: __emnapiTSFNPlugin,
63
+ createOnMessage: __wasmCreateOnMessageForFsProxy,
64
+ instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync,
65
+ } = require('@napi-rs/wasm-runtime')
66
+ const { createContext: __emnapiCreateContext } = require('@emnapi/runtime')
67
+
68
+ function __getWasiWorkerExecArgv() {
69
+ const __workerExecArgv = []
70
+ for (let __index = 0; __index < process.execArgv.length; __index += 1) {
71
+ const __arg = process.execArgv[__index]
72
+ if (
73
+ __arg === '--input-type' ||
74
+ __arg === '--eval' ||
75
+ __arg === '-e' ||
76
+ __arg === '--print' ||
77
+ __arg === '-p'
78
+ ) {
79
+ __index += 1
80
+ continue
81
+ }
82
+ if (
83
+ __arg.startsWith('--input-type=') ||
84
+ __arg.startsWith('--eval=') ||
85
+ __arg.startsWith('--print=')
86
+ ) {
87
+ continue
88
+ }
89
+ __workerExecArgv.push(__arg)
90
+ }
91
+ return __workerExecArgv
92
+ }
93
+
94
+ function __isInvalidWasiWorkerExecArgv(errorMessage, argument) {
95
+ const __equalsIndex = argument.indexOf('=')
96
+ const __argumentName =
97
+ __equalsIndex === -1 ? argument : argument.slice(0, __equalsIndex)
98
+ return (
99
+ errorMessage.includes(': ' + __argumentName + ',') ||
100
+ errorMessage.includes(': ' + __argumentName + '=') ||
101
+ errorMessage.endsWith(': ' + __argumentName) ||
102
+ errorMessage.includes(', ' + __argumentName + ',') ||
103
+ errorMessage.includes(', ' + __argumentName + '=') ||
104
+ errorMessage.endsWith(', ' + __argumentName)
105
+ )
106
+ }
107
+
108
+ function __removeInvalidWasiWorkerExecArgv(execArgv, error) {
109
+ if (typeof error.message !== 'string') {
110
+ return
111
+ }
112
+ const __workerExecArgv = []
113
+ let __removed = false
114
+ for (let __index = 0; __index < execArgv.length; __index += 1) {
115
+ const __arg = execArgv[__index]
116
+ if (
117
+ __arg.startsWith('-') &&
118
+ __isInvalidWasiWorkerExecArgv(error.message, __arg)
119
+ ) {
120
+ __removed = true
121
+ if (
122
+ !__arg.includes('=') &&
123
+ __index + 1 < execArgv.length &&
124
+ !execArgv[__index + 1].startsWith('-')
125
+ ) {
126
+ __index += 1
127
+ }
128
+ continue
129
+ }
130
+ __workerExecArgv.push(__arg)
131
+ }
132
+ return __removed ? __workerExecArgv : undefined
133
+ }
134
+
135
+ function __createWasiWorker(filename) {
136
+ let __workerExecArgv = __getWasiWorkerExecArgv()
137
+ while (true) {
138
+ try {
139
+ return new Worker(filename, {
140
+ env: process.env,
141
+ execArgv: __workerExecArgv,
142
+ workerData: {
143
+ hostRoot: __hostRoot,
144
+ rootDir: __rootDir,
145
+ crashFlag: __wasiThreadCrashFlag,
146
+ crashReport: __wasiThreadCrashReport,
147
+ addonCrashFlag: __wasiAddonCrashFlag,
148
+ },
149
+ })
150
+ } catch (error) {
151
+ if (!error || error.code !== 'ERR_WORKER_INVALID_EXEC_ARGV') {
152
+ throw error
153
+ }
154
+ const __nextWorkerExecArgv =
155
+ __removeInvalidWasiWorkerExecArgv(__workerExecArgv, error)
156
+ if (!__nextWorkerExecArgv) {
157
+ throw error
158
+ }
159
+ __workerExecArgv = __nextWorkerExecArgv
160
+ }
161
+ }
162
+ }
163
+
164
+ // Set to 1 by a pool worker (see wasi-worker.mjs) right before it reports that
165
+ // its wasm thread died. Shared memory, so this thread reads it synchronously even
166
+ // while the worker's 'error' event is still queued behind the code that is
167
+ // exiting right now.
168
+ const __wasiThreadCrashFlag = new Int32Array(new SharedArrayBuffer(4))
169
+ // Written by the first pool worker whose wasm thread dies, before it raises the
170
+ // flag: its error and `threadId` (layout in wasi-worker.mjs). Read without
171
+ // waiting for any event, see `__readWasiThreadCrashReport`.
172
+ const __wasiThreadCrashReport = new SharedArrayBuffer(4096)
173
+ let __wasiThreadCrashReportRead
174
+ // The first error a pool worker reported through its 'error' event, and that
175
+ // worker's `threadId`. See `__getWasiThreadCrashError`.
176
+ let __wasiThreadCrashWorkerError
177
+ let __wasiThreadCrashWorkerId
178
+ let __wasiThreadCrashError
179
+ // Raised while `__runWasiInitializationRollbackSteps` runs, so its polls and
180
+ // steps stop after a crash the way a public disposal's do.
181
+ let __wasiInitializationRollbackActive = false
182
+ let __wasiThreadCrashed = false
183
+
184
+ // A view of the addon's crash flag, one word of the shared wasm memory, for the
185
+ // pool workers: they raise it when their wasm thread dies, and the shutdown
186
+ // waits inside the cleanup calls on this thread then trap instead of waiting on
187
+ // the dead thread for good. Undefined for an addon built with an older napi.
188
+ let __wasiAddonCrashFlag
189
+
190
+ function __captureWasiAddonCrashFlag(instance) {
191
+ try {
192
+ const getAddress = instance.exports.napi_wasm_thread_crash_flag_address
193
+ if (typeof getAddress !== 'function') {
194
+ return
195
+ }
196
+ const address = getAddress() >>> 0
197
+ const buffer = __sharedMemory.buffer
198
+ if (address === 0 || address % 4 !== 0 || address + 4 > buffer.byteLength) {
199
+ return
200
+ }
201
+ __wasiAddonCrashFlag = new Int32Array(buffer, address, 1)
202
+ } catch {}
203
+ }
204
+
205
+ /**
206
+ * Whether any wasm thread of this binding has died: a trap or an uncaught error
207
+ * in a pool worker, including one that failed to load after its thread spawn
208
+ * had already been reported as started.
209
+ *
210
+ * After that the shared wasm state cannot be trusted: a lock the dead thread
211
+ * held stays held, and a join or park that waits on it — the async runtime's
212
+ * `finish_shutdown` waiting for the dead thread's work to go idle — blocks
213
+ * this thread forever in a raw `memory.atomic.wait32`, which neither
214
+ * emnapi's crash check nor a signal can interrupt.
215
+ */
216
+ function __hasWasiThreadCrashed() {
217
+ if (__wasiThreadCrashed || Atomics.load(__wasiThreadCrashFlag, 0) !== 0) {
218
+ return true
219
+ }
220
+ const manager = __getWasiThreadManager()
221
+ return Boolean(manager && manager._fatalError)
222
+ }
223
+
224
+ let __wasiThreadCrashDisposePromise
225
+
226
+ /**
227
+ * Stores the first error a pool worker reported, with the worker's id. Called
228
+ * from the loader's own 'error' listener, which runs before emnapi's.
229
+ */
230
+ function __recordWasiThreadCrashError(error, workerId) {
231
+ if (__wasiThreadCrashWorkerError !== undefined || error === undefined) {
232
+ return
233
+ }
234
+ __wasiThreadCrashWorkerError = error
235
+ __wasiThreadCrashWorkerId = workerId
236
+ __fillWasiThreadCrashError()
237
+ }
238
+
239
+ /**
240
+ * The error in the shared crash report, rebuilt once it is complete: the
241
+ * worker writes it before it raises the flag, so it is there as soon as the
242
+ * crash is seen. Plain JavaScript over shared memory; never enters wasm.
243
+ */
244
+ function __readWasiThreadCrashReport() {
245
+ if (__wasiThreadCrashReportRead !== undefined) {
246
+ return __wasiThreadCrashReportRead
247
+ }
248
+ try {
249
+ const header = new Int32Array(__wasiThreadCrashReport, 0, 3)
250
+ if (Atomics.load(header, 0) !== 2) {
251
+ return
252
+ }
253
+ const length = Atomics.load(header, 1)
254
+ const threadId = Atomics.load(header, 2)
255
+ let error
256
+ if (length > 0) {
257
+ // Copied out of shared memory: TextDecoder does not take a shared view.
258
+ const bytes = new Uint8Array(__wasiThreadCrashReport, 12, length).slice()
259
+ const report = JSON.parse(new TextDecoder().decode(bytes))
260
+ error = new Error(String(report.message))
261
+ if (typeof report.name === 'string') {
262
+ error.name = report.name
263
+ }
264
+ if (typeof report.stack === 'string') {
265
+ error.stack = report.stack
266
+ }
267
+ }
268
+ __wasiThreadCrashReportRead = { error, threadId }
269
+ } catch {
270
+ __wasiThreadCrashReportRead = { error: undefined, threadId: 0 }
271
+ }
272
+ return __wasiThreadCrashReportRead
273
+ }
274
+
275
+ /**
276
+ * The one error every crash path of this binding reports, created on first
277
+ * use.
278
+ *
279
+ * The shared flag is raised before this thread has processed the worker's
280
+ * 'error' event, and once the workers are terminated that event is often
281
+ * never delivered, so neither it nor emnapi's `_fatalError` can be counted
282
+ * on. The cause is filled in from the first source that has it: the error the
283
+ * 'error' listener kept, else the worker's shared crash report, else
284
+ * `_fatalError` — here, and again from the 'error' listener when it arrives
285
+ * later. Until then the error carries only its message.
286
+ */
287
+ function __getWasiThreadCrashError() {
288
+ if (__wasiThreadCrashError === undefined) {
289
+ __wasiThreadCrashError = new Error(
290
+ 'napi-rs: WASI binding cannot be disposed after a worker thread crashed',
291
+ )
292
+ }
293
+ __fillWasiThreadCrashError()
294
+ return __wasiThreadCrashError
295
+ }
296
+
297
+ function __fillWasiThreadCrashError() {
298
+ const crashError = __wasiThreadCrashError
299
+ if (crashError === undefined) {
300
+ return
301
+ }
302
+ try {
303
+ if (crashError.cause === undefined) {
304
+ let cause = __wasiThreadCrashWorkerError
305
+ if (cause === undefined) {
306
+ const report = __readWasiThreadCrashReport()
307
+ cause = report ? report.error : undefined
308
+ }
309
+ if (cause === undefined) {
310
+ const manager = __getWasiThreadManager()
311
+ cause = manager ? manager._fatalError : undefined
312
+ }
313
+ if (cause !== undefined && cause !== null) {
314
+ crashError.cause = cause
315
+ }
316
+ }
317
+ if (crashError.workerThreadId === undefined) {
318
+ let workerId = __wasiThreadCrashWorkerId
319
+ if (workerId === undefined) {
320
+ const report = __readWasiThreadCrashReport()
321
+ workerId = report && report.threadId > 0 ? report.threadId : undefined
322
+ }
323
+ if (workerId !== undefined) {
324
+ crashError.workerThreadId = workerId
325
+ }
326
+ }
327
+ } catch {}
328
+ }
329
+
330
+ /**
331
+ * Let the event loop drain after a wasm thread died, without entering wasm.
332
+ *
333
+ * emnapi's `Context` keeps a `NodejsWaitingRequestCounter` on Node: a
334
+ * `MessagePort` (`refCounter.refHandle`) that it refs when the count of
335
+ * in-flight async work and threadsafe-function requests leaves zero and unrefs
336
+ * when it comes back. The requests the dead thread held never complete, so the
337
+ * count never returns to zero and the port holds the process open for good.
338
+ * `Context.destroy()` would not release it either — and it runs cleanup
339
+ * hooks, which is exactly what must not happen now. So unref the port directly.
340
+ * The count is left as is: it stays above zero, so a later request never refs
341
+ * the port again.
342
+ *
343
+ * The field is private in emnapi's typings, so read it defensively; a context
344
+ * without it (a non-Node host, a future emnapi) is left alone.
345
+ */
346
+ function __releaseEmnapiWaitingRequestHandle() {
347
+ try {
348
+ const refCounter = __emnapiContext && __emnapiContext.refCounter
349
+ const refHandle = refCounter && refCounter.refHandle
350
+ if (refHandle && typeof refHandle.unref === 'function') {
351
+ refHandle.unref()
352
+ }
353
+ } catch {}
354
+ }
355
+
356
+ /**
357
+ * The public disposer after a wasm thread died. The normal chain drains async
358
+ * work, runs the environment cleanup barrier and destroys the context — every
359
+ * one of those re-enters wasm, and the barrier's shutdown waits for the dead
360
+ * thread's work in the same raw atomic wait `__disposeWasiBindingAtExit`
361
+ * avoids. An app that handled the worker's error and then disposes would block
362
+ * there for good. Only stop the workers, then reject: the binding was not
363
+ * cleaned up and cannot be, so reporting success would be a lie. The context
364
+ * is not destroyed — only its waiting-request port is unrefed, so the process
365
+ * can exit on its own — and the 'exit' listener takes its short path too.
366
+ *
367
+ * Latched: every later call returns the same promise.
368
+ */
369
+ function __disposeWasiBindingAfterThreadCrash() {
370
+ if (__wasiThreadCrashDisposePromise) {
371
+ return __wasiThreadCrashDisposePromise
372
+ }
373
+ __releaseEmnapiWaitingRequestHandle()
374
+ let workerResult
375
+ try {
376
+ workerResult = __terminateWasiWorkers()
377
+ } catch (terminateError) {
378
+ workerResult = Promise.reject(terminateError)
379
+ }
380
+ // Built at settlement, after the workers stopped: by then the 'error' event
381
+ // has usually delivered the worker's error.
382
+ __wasiThreadCrashDisposePromise = Promise.resolve(workerResult).then(
383
+ () => {
384
+ throw __getWasiThreadCrashError()
385
+ },
386
+ (terminateError) => {
387
+ throw __attachCleanupErrors(__getWasiThreadCrashError(), [
388
+ terminateError,
389
+ ])
390
+ },
391
+ )
392
+ return __wasiThreadCrashDisposePromise
393
+ }
394
+
395
+ /**
396
+ * Stops a public disposal that a thread crash overtook.
397
+ *
398
+ * The check at the top of `__disposeWasiBinding` only sees a crash that came
399
+ * first. A thread that dies once the chain is running leaves it polling for
400
+ * work the dead thread still counts — the async-work drain for
401
+ * `napi_wasm_async_work_pending`, the barrier's poll for
402
+ * `napi_wasm_runtime_work_pending` — and neither count ever reaches zero, so
403
+ * the poll's referenced timers keep the process alive forever with the
404
+ * disposal promise pending. Each poll turn and each step boundary calls this,
405
+ * and the throw ends the chain before anything re-enters wasm again; the
406
+ * disposer then settles it through `__settleWasiDisposalAfterThreadCrash`.
407
+ *
408
+ * The initialization rollback runs the same polls and steps, so they stop while
409
+ * it runs too; its wrapper, `__rollbackWasiInitialization`, then ends it
410
+ * through `__rollbackWasiInitializationAfterThreadCrash`. A bare poll with
411
+ * neither in flight is left alone.
412
+ */
413
+ function __abortWasiDisposalIfThreadCrashed() {
414
+ if (
415
+ (__wasiDisposePromise !== undefined ||
416
+ __wasiInitializationRollbackActive) &&
417
+ __hasWasiThreadCrashed()
418
+ ) {
419
+ throw new Error(
420
+ 'napi-rs: WASI disposal stopped because a worker thread crashed',
421
+ )
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Settles an in-flight public disposal whose chain failed after a thread
427
+ * died — stopped by `__abortWasiDisposalIfThreadCrashed` or failing any other
428
+ * way — through the crash disposal: it releases the waiting-request port,
429
+ * terminates the workers and rejects with the same error an entry-time crash
430
+ * gets. `__wasiDisposePromise` stays set, so this caller, every caller that
431
+ * joined it and every later one hold the same promise. Returns false when no
432
+ * thread died, leaving the ordinary failure handling alone.
433
+ */
434
+ function __settleWasiDisposalAfterThreadCrash(resolve, reject) {
435
+ if (!__hasWasiThreadCrashed()) {
436
+ return false
437
+ }
438
+ __disposeWasiBindingAfterThreadCrash().then(resolve, reject)
439
+ return true
440
+ }
441
+
442
+ /**
443
+ * Ends an initialization rollback after a wasm thread died, without entering
444
+ * wasm: the barrier, its finish and `Context.destroy()` are skipped, and the
445
+ * crash disposal releases the waiting-request port and terminates the workers,
446
+ * once. The initialization error itself is left to propagate: the crash error
447
+ * is returned as the rollback's cleanup error, so
448
+ * `__completeWasiInitializationRollback` attaches it — as the cause when the
449
+ * error has none — and keeps the record, since the context was not destroyed.
450
+ */
451
+ function __rollbackWasiInitializationAfterThreadCrash() {
452
+ const crashError = __getWasiThreadCrashError()
453
+ // Its rejection is `crashError` itself, which the caller reports.
454
+ void __disposeWasiBindingAfterThreadCrash().catch(() => {})
455
+ return [crashError]
456
+ }
457
+
458
+ const __cwd = process.cwd()
459
+ const __rootDir = __nodePath.parse(__cwd).root
460
+ const __hostRoot =
461
+ process.platform === 'android' ? __cwd : __rootDir
462
+
463
+ const __wasi = new __nodeWASI({
464
+ version: 'preview1',
465
+ env: process.env,
466
+ preopens: {
467
+ [__rootDir]: __hostRoot,
468
+ [__hostRoot]: __hostRoot,
469
+ },
470
+ })
471
+
472
+ const __sharedMemory = new WebAssembly.Memory({
473
+ initial: 4000,
474
+ maximum: 65536,
475
+ shared: true,
476
+ })
477
+
478
+ let __wasmFilePath = __nodePath.join(__dirname, 'frdt.wasm32-wasi.wasm')
479
+ const __wasmDebugFilePath = __nodePath.join(__dirname, 'frdt.wasm32-wasi.debug.wasm')
480
+
481
+ if (__nodeFs.existsSync(__wasmDebugFilePath)) {
482
+ __wasmFilePath = __wasmDebugFilePath
483
+ } else if (!__nodeFs.existsSync(__wasmFilePath)) {
484
+ const __wasiPackageEntry = require.resolve('@frdt/binding-wasm32-wasi')
485
+ const __packagedWasmFilePath = __nodePath.join(
486
+ __nodePath.dirname(__wasiPackageEntry),
487
+ 'frdt.wasm32-wasi.wasm',
488
+ )
489
+ if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
490
+ throw new Error(
491
+ '@frdt/binding-wasm32-wasi is installed but is missing frdt.wasm32-wasi.wasm.',
492
+ )
493
+ }
494
+ __wasmFilePath = __packagedWasmFilePath
495
+ }
496
+
497
+ const __wasmFile = __nodeFs.readFileSync(__wasmFilePath)
498
+ let __emnapiContext
499
+
500
+ const __wasiDisposeSymbol = Symbol.for('napi.rs.wasi.dispose')
501
+ const __wasiWorkers = new Set()
502
+ // The thread manager has to be reachable *before* anything that can throw
503
+ // during load or registration. Initialization can fail after the pool has
504
+ // already spawned workers, and the rollback still has to mark their
505
+ // terminations as expected — but `__napiModule` is assigned only when
506
+ // instantiation RETURNS, so on exactly that path it is still undefined. A
507
+ // plugin factory runs while the emnapi module is being created, before the
508
+ // wasm is loaded and before any registration function runs, and its context
509
+ // carries the very same manager instance.
510
+ let __wasiThreadManager
511
+
512
+ function __captureWasiThreadManager(context) {
513
+ if (context && context.PThread) {
514
+ __wasiThreadManager = context.PThread
515
+ }
516
+ return {}
517
+ }
518
+
519
+ function __getWasiThreadManager() {
520
+ const manager =
521
+ __wasiThreadManager !== undefined
522
+ ? __wasiThreadManager
523
+ : __napiModule
524
+ ? __napiModule.PThread
525
+ : undefined
526
+ if (manager && typeof manager.terminateWorker === 'function') {
527
+ return manager
528
+ }
529
+ return undefined
530
+ }
531
+ let __napiInstance
532
+ let __emnapiContextDestroyed = false
533
+ let __emnapiContextDestroyPromise
534
+ let __emnapiWasmEnvCleanupPrepared = false
535
+ let __emnapiWasmEnvCleanupPreparing = false
536
+ // The closer for a barrier that is parked between `…_begin` and `…_finish`,
537
+ // set only while that window is open. `__emnapiWasmEnvCleanupPreparing` cannot
538
+ // tell those two apart on its own: it is raised both for a purely synchronous
539
+ // frame — which must not be re-entered, and which nothing outside it can
540
+ // finish — and across this window, which spans real event-loop turns, so a
541
+ // caller that cannot yield can land in the middle of one. That caller can close
542
+ // this window, because `…_finish` is idempotent and joins, which is exactly
543
+ // what the single call does. See `__prepareWasmEnvCleanup`.
544
+ let __finishParkedWasmEnvCleanup
545
+ // Raised while a caller that can still yield is driving the barrier, so the
546
+ // queue it leaves behind is expected rather than lost. See
547
+ // `__reportUnreachedWasmEnvSettlements`.
548
+ let __emnapiWasmEnvCleanupYielding = false
549
+ let __emnapiWasmEnvSettlementLossReported = false
550
+ let __emnapiWasmEnvCleanupRan = false
551
+ let __emnapiWasmEnvCleanupDrained = false
552
+ let __emnapiWasmEnvCleanupDrainPromise
553
+ let __wasiDisposed = false
554
+ let __wasiAsyncWorkDrainPromise
555
+ let __wasiDisposePromise
556
+ let __completeWasiDisposal = function () {}
557
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
558
+ // that stopped short of destroying the context. See
559
+ // `__rollbackWasiInitialization`.
560
+ let __retainWasiRollbackForRetry = function () {}
561
+
562
+ function __isThenable(value) {
563
+ return (
564
+ value !== null &&
565
+ (typeof value === 'object' || typeof value === 'function') &&
566
+ typeof value.then === 'function'
567
+ )
568
+ }
569
+
570
+ function __createCleanupError(errors, message) {
571
+ if (errors.length === 1) {
572
+ return errors[0]
573
+ }
574
+ const __AggregateError = globalThis.AggregateError
575
+ if (typeof __AggregateError === 'function') {
576
+ return new __AggregateError(errors, message)
577
+ }
578
+ const error = new Error(message)
579
+ error.errors = errors
580
+ return error
581
+ }
582
+
583
+ function __attachCleanupErrors(error, cleanupErrors) {
584
+ if (cleanupErrors.length === 0) {
585
+ return error
586
+ }
587
+ const cleanupError = __createCleanupError(
588
+ cleanupErrors,
589
+ 'WASI binding cleanup failed',
590
+ )
591
+ try {
592
+ if (
593
+ error &&
594
+ (typeof error === 'object' || typeof error === 'function')
595
+ ) {
596
+ if (error.cause === undefined) {
597
+ error.cause = cleanupError
598
+ if (error.cause === cleanupError) {
599
+ return error
600
+ }
601
+ }
602
+ if (Array.isArray(error.cleanupErrors)) {
603
+ error.cleanupErrors.push(cleanupError)
604
+ return error
605
+ } else {
606
+ const attachedCleanupErrors = [cleanupError]
607
+ error.cleanupErrors = attachedCleanupErrors
608
+ if (error.cleanupErrors === attachedCleanupErrors) {
609
+ return error
610
+ }
611
+ }
612
+ }
613
+ } catch {}
614
+ const aggregate = __createCleanupError(
615
+ [error, cleanupError],
616
+ 'WASI binding initialization and cleanup failed',
617
+ )
618
+ try {
619
+ aggregate.cause = error
620
+ } catch {}
621
+ return aggregate
622
+ }
623
+
624
+ function __wrapEmnapiContextDestroyForSettlement(
625
+ context,
626
+ prepareEnvCleanup,
627
+ isPreparingEnvCleanup,
628
+ ) {
629
+ let destroy
630
+ try {
631
+ destroy = context.destroy
632
+ } catch {
633
+ return context
634
+ }
635
+ if (typeof destroy !== 'function') {
636
+ return context
637
+ }
638
+ try {
639
+ Object.defineProperty(context, 'destroy', {
640
+ configurable: true,
641
+ enumerable: false,
642
+ writable: true,
643
+ value: function () {
644
+ // Reentered from a promise hook that fired inside the barrier: the
645
+ // frame running it destroys as soon as it returns.
646
+ if (isPreparingEnvCleanup?.()) {
647
+ return
648
+ }
649
+ prepareEnvCleanup?.()
650
+ return Reflect.apply(destroy, this, arguments)
651
+ },
652
+ })
653
+ } catch {}
654
+ return context
655
+ }
656
+
657
+ function __isPreparingWasmEnvCleanup() {
658
+ return __emnapiWasmEnvCleanupPreparing
659
+ }
660
+
661
+ function __prepareWasmEnvCleanup() {
662
+ if (__emnapiWasmEnvCleanupPrepared) {
663
+ return
664
+ }
665
+ // A handshake parked between its two halves is one this frame can close, and
666
+ // must: every caller of this function is about to destroy the context, and
667
+ // the turns the poll is waiting for will not come — an 'exit' teardown is
668
+ // the last thing the process runs, and `Context.destroy()` takes the
669
+ // environment away. Closing it here runs `…_finish`, which is the call that joins, so
670
+ // this degrades to exactly the single call below. Leaving it open instead
671
+ // destroys the context with the barrier still raised, the runtime never
672
+ // joined and the workers never drained.
673
+ const finishParked = __finishParkedWasmEnvCleanup
674
+ if (finishParked !== undefined) {
675
+ finishParked()
676
+ __reportUnreachedWasmEnvSettlements()
677
+ return
678
+ }
679
+ if (__emnapiWasmEnvCleanupPreparing) {
680
+ return
681
+ }
682
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
683
+ if (typeof prepare === 'function') {
684
+ // The addon settles the promises it cancels synchronously, under a
685
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
686
+ // here must not reach this export again.
687
+ __emnapiWasmEnvCleanupPreparing = true
688
+ try {
689
+ prepare()
690
+ } finally {
691
+ __emnapiWasmEnvCleanupPreparing = false
692
+ }
693
+ __emnapiWasmEnvCleanupRan = true
694
+ __reportUnreachedWasmEnvSettlements()
695
+ }
696
+ __emnapiWasmEnvCleanupPrepared = true
697
+ }
698
+
699
+ /**
700
+ * Say so when the barrier leaves settlements queued and nothing is left that
701
+ * could deliver them.
702
+ *
703
+ * Only the disposal chain yields the event-loop turns @emnapi/core needs to
704
+ * dispatch its queue. Every other caller of the barrier destroys in the same
705
+ * turn — a raw `Context.destroy()`, the 'exit' teardown — and
706
+ * `Context.destroy()` runs the threadsafe function's cleanup hook, which drains
707
+ * that queue with a null env and discards it. The promises those settlements
708
+ * were for then hang forever, silently.
709
+ *
710
+ * Loud, once, and never throwing: this runs from inside `Context.destroy()`,
711
+ * emnapi's own beforeExit destroy included, where throwing would take the whole
712
+ * teardown down with it. Destroying anyway is still the right trade — the queue
713
+ * is already unreachable by then.
714
+ */
715
+ function __reportUnreachedWasmEnvSettlements() {
716
+ if (__emnapiWasmEnvCleanupYielding || __emnapiWasmEnvSettlementLossReported) {
717
+ return
718
+ }
719
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
720
+ if (typeof pending !== 'function') {
721
+ return
722
+ }
723
+ let queued
724
+ try {
725
+ queued = pending()
726
+ } catch {
727
+ return
728
+ }
729
+ if (!queued) {
730
+ return
731
+ }
732
+ __emnapiWasmEnvSettlementLossReported = true
733
+ try {
734
+ const consoleHost = globalThis.console
735
+ if (consoleHost && typeof consoleHost.error === 'function') {
736
+ consoleHost.error(
737
+ "napi-rs: the wasm environment is being destroyed with " +
738
+ queued +
739
+ " 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.",
740
+ )
741
+ }
742
+ } catch {}
743
+ }
744
+
745
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
746
+ // on, so the drain turns below interleave with that dispatch instead of racing
747
+ // ahead of it on a faster queue.
748
+ const __scheduleMacrotask = (function () {
749
+ if (typeof setImmediate === 'function') {
750
+ return function (callback) {
751
+ setImmediate(callback)
752
+ }
753
+ }
754
+ const __MessageChannel = globalThis.MessageChannel
755
+ if (typeof __MessageChannel === 'function') {
756
+ return function (callback) {
757
+ const channel = new __MessageChannel()
758
+ channel.port1.onmessage = function () {
759
+ channel.port1.onmessage = null
760
+ try {
761
+ channel.port1.close()
762
+ } catch {}
763
+ try {
764
+ channel.port2.close()
765
+ } catch {}
766
+ callback()
767
+ }
768
+ channel.port2.postMessage(null)
769
+ }
770
+ }
771
+ return function (callback) {
772
+ setTimeout(callback, 0)
773
+ }
774
+ })()
775
+
776
+ // A real, *referenced* timer, for waits that must let the whole host make
777
+ // progress between looks — the async-work drain polls the addon rather than
778
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
779
+ // would spin the loop instead of yielding it. Falls back to the macrotask
780
+ // scheduler on a host without timers.
781
+ function __scheduleTimer(callback, delay) {
782
+ const setTimer = globalThis.setTimeout
783
+ if (typeof setTimer !== 'function') {
784
+ __scheduleMacrotask(callback)
785
+ return
786
+ }
787
+ try {
788
+ setTimer(callback, delay)
789
+ } catch {
790
+ __scheduleMacrotask(callback)
791
+ }
792
+ }
793
+
794
+ // A real, referenced timer rather than a zero-delay macrotask, for the same
795
+ // reason the async-work drain uses one: this polls the addon instead of
796
+ // interleaving with the @emnapi/core dispatch, so a zero-delay turn would spin
797
+ // the loop instead of yielding it.
798
+ const __WASM_RUNTIME_WORK_POLL_INTERVAL_MS = 1
799
+ // Arrivals it takes before the poll paces on the host's timers alone. One
800
+ // proves nothing: a timer armed before the host's timers stopped still fires.
801
+ const __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS = 2
802
+ // How long a parked turn's own timer must already have been due before a
803
+ // backup that runs calls it dropped. Slack, not a deadline: a timer is due
804
+ // against the event loop's clock, which is read once per iteration, while
805
+ // these are `Date.now()` readings taken part-way through one, so the two
806
+ // drift apart by however long the loop has been inside the current iteration.
807
+ const __WASM_RUNTIME_WORK_POLL_STALL_MS = 50
808
+ // How long a backup itself waits. What is left of it after the slack and one
809
+ // interval — 149 ms — has to cover the *two* poll turns that can separate a
810
+ // parked turn from the last backup armed while the host's timers still
811
+ // worked, so the ceiling on a single turn is half of it. See the invariant on
812
+ // `__armWasmRuntimePollStallBackup`.
813
+ const __WASM_RUNTIME_WORK_POLL_BACKUP_MS = 200
814
+
815
+ /**
816
+ * Pacing state for one runtime-work poll.
817
+ *
818
+ * Per poll, never per module: whether the host's timers arrive is not a
819
+ * property of the module. A host can lose its timers between two disposals,
820
+ * and in the deferred shape every instance shares this module — one healthy
821
+ * instance must not disarm the fallback for the next one.
822
+ */
823
+ function __createWasmRuntimePollPace() {
824
+ return {
825
+ // Timers armed by *this* poll that have actually arrived.
826
+ arrivals: 0,
827
+ // The turn waiting on a timer alone *right now* — undefined whenever no
828
+ // turn is parked — and when that turn's own timer came due.
829
+ settleTurn: undefined,
830
+ turnTimerDueAt: 0,
831
+ }
832
+ }
833
+
834
+ /**
835
+ * The backup that ends a turn whose timer is never going to arrive.
836
+ *
837
+ * Once the poll paces on the timer alone it has nothing left to fall back on
838
+ * if the host's timers stop mid-poll: the turn that armed the dead timer is
839
+ * the turn that parks, and a parked poll schedules nothing that could notice.
840
+ * So every turn arms one of these before it yields, and each one compares due
841
+ * times instead of measuring how long the parked turn has been waiting.
842
+ *
843
+ * Invariant: a parked turn is ended by the newest backup that was armed while
844
+ * the host's timers still worked, and a backup ends a turn only when that
845
+ * turn's own timer was already due a whole window before the backup itself.
846
+ * Neither half turns on how far apart the arms happen to fall — what bounds
847
+ * the rescue is how far back that newest live backup is:
848
+ *
849
+ * - *Ends it.* Hosts run timers in due order, so a backup that runs while a
850
+ * turn due a whole window earlier is still parked proves that turn's timer
851
+ * was dropped rather than merely late. That same comparison is what leaves a
852
+ * healthy host alone: there the turn's timer has already run and cleared
853
+ * `settleTurn` before any backup due after it can look.
854
+ * - *Two turns back, not one.* A turn that ended does not prove its own timer
855
+ * arrived: until `…_TRUSTED_ARRIVALS` is reached every turn arms both
856
+ * primitives and the macrotask wins, so such a turn can end with its own
857
+ * timer — and the backup armed one line before it — already dead. The
858
+ * arrival that then flips the poll onto the timer alone can itself be a
859
+ * timer armed before the host's timers died. So the turn that parks can sit
860
+ * two turns past the last live arm, and the newest live backup is due
861
+ * `…_BACKUP_MS` less *two* turn lengths after that turn's own timer.
862
+ * Arming on every turn is what holds it to two, rather than however far back
863
+ * a throttle last let one through.
864
+ * - *Ceiling.* Coverage therefore holds while two consecutive poll turns fit
865
+ * inside `…_BACKUP_MS` less the slack and one interval: 149 ms, so 74 ms
866
+ * per turn (measured: a 74 ms turn is still rescued, a 75 ms one parks).
867
+ * Past that the turn stays parked and the disposal promise never settles.
868
+ * The bound is deliberate: reaching it takes a host that drops timers
869
+ * mid-poll *and* keeps every poll turn busy for more than 74 ms, and neither
870
+ * Node nor WebContainer — the hosts that run the threaded artifact — does
871
+ * the second.
872
+ *
873
+ * The poll then goes back to arming both primitives until two fresh arrivals
874
+ * prove the timers again. A host that stops running the timers it has
875
+ * *already* accepted leaves nothing to fire, and the disposal promise stays
876
+ * pending rather than wedging the thread — the same outcome as a blocking
877
+ * closure that never returns. Unreferenced wherever the host allows it: the
878
+ * poll's own turn timers are what keep the loop alive, never these.
879
+ */
880
+ function __armWasmRuntimePollStallBackup(pace) {
881
+ const setTimer = globalThis.setTimeout
882
+ if (typeof setTimer !== 'function') {
883
+ // Nothing to back up: `__scheduleTimer` is on the macrotask channel
884
+ // already, and that one cannot park.
885
+ return
886
+ }
887
+ // Read before arming, so this never claims to be due earlier than the timer
888
+ // actually is: a backup ends a turn only when it is provably due after it.
889
+ const dueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_BACKUP_MS
890
+ let handle
891
+ try {
892
+ handle = setTimer(() => {
893
+ const settleTurn = pace.settleTurn
894
+ if (
895
+ !settleTurn ||
896
+ pace.turnTimerDueAt > dueAt - __WASM_RUNTIME_WORK_POLL_STALL_MS
897
+ ) {
898
+ // No turn is parked, or the parked one's timer came due too close to
899
+ // this backup to call it dropped — it may still arrive, and the turn
900
+ // that armed it armed a backup due a whole window after *that*.
901
+ return
902
+ }
903
+ pace.arrivals = 0
904
+ pace.settleTurn = undefined
905
+ settleTurn()
906
+ }, __WASM_RUNTIME_WORK_POLL_BACKUP_MS)
907
+ } catch {
908
+ return
909
+ }
910
+ if (handle && typeof handle.unref === 'function') {
911
+ try {
912
+ handle.unref()
913
+ } catch {}
914
+ }
915
+ }
916
+
917
+ /**
918
+ * One turn of the runtime-work poll.
919
+ *
920
+ * `__scheduleTimer` falls back to the macrotask scheduler when `setTimeout` is
921
+ * missing or throws, but not when it is present, returns a handle and never
922
+ * fires — fake timers in a test suite that disposes from an `afterEach`, or a
923
+ * host whose timers belong to an IO context that is already gone. That host
924
+ * would park this poll forever, and the poll is unbounded, so nothing would
925
+ * ever call `…_finish`.
926
+ *
927
+ * Arm both primitives until timers armed by this poll have arrived twice, and
928
+ * let whichever lands first end the turn; the loser resolves nothing. A host
929
+ * with working timers therefore pays the double arming for the first turn or
930
+ * two — the macrotask wins the race, but the timers behind it still arrive and
931
+ * are counted — and paces on the timer alone from then on, instead of spinning
932
+ * the loop on a zero-delay queue. A host whose timers never arrive keeps both,
933
+ * and the macrotask is what keeps the poll moving. A host whose timers stop
934
+ * after proving themselves is caught by `__armWasmRuntimePollStallBackup`,
935
+ * which ends the parked turn and puts this poll back on both.
936
+ */
937
+ function __yieldWasmRuntimePollTurn(pace) {
938
+ // Armed before the turn yields, and by every turn: what rescues a parked
939
+ // turn has to have been armed while the host's timers still worked, and the
940
+ // turn that parks is the one whose own timer is already dead.
941
+ __armWasmRuntimePollStallBackup(pace)
942
+ return new Promise((resolve) => {
943
+ let settled = false
944
+ const settle = () => {
945
+ if (settled) {
946
+ return
947
+ }
948
+ settled = true
949
+ if (pace.settleTurn === settle) {
950
+ // Nothing is parked any more: a backup running later must not read a
951
+ // due time this turn has already answered.
952
+ pace.settleTurn = undefined
953
+ }
954
+ resolve()
955
+ }
956
+ __scheduleTimer(() => {
957
+ pace.arrivals++
958
+ settle()
959
+ }, __WASM_RUNTIME_WORK_POLL_INTERVAL_MS)
960
+ // Read next to the arming it describes; see
961
+ // `__armWasmRuntimePollStallBackup` for what the two due times mean.
962
+ const turnTimerDueAt = Date.now() + __WASM_RUNTIME_WORK_POLL_INTERVAL_MS
963
+ if (pace.arrivals < __WASM_RUNTIME_WORK_POLL_TRUSTED_ARRIVALS) {
964
+ __scheduleMacrotask(settle)
965
+ return
966
+ }
967
+ // Paced by the timer alone from here; the backup is what ends this turn if
968
+ // the timer never arrives.
969
+ pace.settleTurn = settle
970
+ pace.turnTimerDueAt = turnTimerDueAt
971
+ })
972
+ }
973
+
974
+ /**
975
+ * The barrier for callers that can yield: `__prepareWasmEnvCleanup` with real
976
+ * event-loop turns in the middle.
977
+ *
978
+ * `napi_prepare_wasm_env_cleanup` waits — it returns only once the addon's
979
+ * async runtime has quiesced, and on `wasm32-wasip1-threads` the thread it
980
+ * waits on is this one, the only thread that can give a running blocking
981
+ * closure the JavaScript turn *it* is waiting for. A single call there can wait
982
+ * for work that can never finish. The addon's two-phase form splits that:
983
+ * `…_begin` stops the runtime without joining and reports whether anything is
984
+ * still live, `napi_wasm_runtime_work_pending` answers that question again
985
+ * without blocking, and `…_finish` joins. The turns yielded in between are the
986
+ * entire point.
987
+ *
988
+ * The poll has no deadline, for the same reason the async-work drain below has
989
+ * none: giving up means calling `…_finish`, which joins on this thread, and the
990
+ * work it would join is the work that is waiting for a turn from this thread —
991
+ * so a bound does not end the wait, it only moves it somewhere the JavaScript
992
+ * thread can no longer be reached. A blocking closure that never returns keeps
993
+ * the disposal promise pending instead, exactly as a task whose `execute` never
994
+ * returns already keeps an *undisposed* process alive. The host contract is in
995
+ * `crates/async-runtime/README.md`: a blocking closure must never wait on a
996
+ * JavaScript turn. The process-exit path still blocks in `…_finish`, because it
997
+ * has no turns left to give (see `__prepareWasmEnvCleanup`).
998
+ *
999
+ * Feature-detected like every other export in this teardown, so an addon built
1000
+ * against a napi crate that predates the split keeps the single blocking call.
1001
+ * Returns nothing whenever the handshake finished without yielding, which keeps
1002
+ * an idle disposal synchronous.
1003
+ */
1004
+ function __prepareWasmEnvCleanupWithTurns() {
1005
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
1006
+ return
1007
+ }
1008
+ const exports = __napiInstance?.exports
1009
+ const begin = exports?.napi_prepare_wasm_env_cleanup_begin
1010
+ const finish = exports?.napi_prepare_wasm_env_cleanup_finish
1011
+ if (typeof begin !== 'function' || typeof finish !== 'function') {
1012
+ // No split to use. The settlement drain still follows this, so the queue
1013
+ // the single call leaves behind is expected rather than lost.
1014
+ __emnapiWasmEnvCleanupYielding = true
1015
+ try {
1016
+ __prepareWasmEnvCleanup()
1017
+ } finally {
1018
+ __emnapiWasmEnvCleanupYielding = false
1019
+ }
1020
+ return
1021
+ }
1022
+ const workPending = exports?.napi_wasm_runtime_work_pending
1023
+ // The in-flight flag stays raised across the turns below, so a `destroy()`
1024
+ // from one of the JavaScript handlers they run is the same no-op it is inside
1025
+ // the single call: the barrier is up and the runtime is mid-teardown, and
1026
+ // destroying between the halves would strand exactly what this delivers.
1027
+ __emnapiWasmEnvCleanupPreparing = true
1028
+ let live
1029
+ try {
1030
+ live = begin()
1031
+ } catch (error) {
1032
+ __emnapiWasmEnvCleanupPreparing = false
1033
+ throw error
1034
+ }
1035
+ __emnapiWasmEnvCleanupRan = true
1036
+ const finishCleanup = () => {
1037
+ if (__emnapiWasmEnvCleanupPrepared) {
1038
+ // Already closed by a caller that could not yield — the 'exit' teardown
1039
+ // reached `__prepareWasmEnvCleanup` while this poll was parked. `…_finish`
1040
+ // is idempotent, but the flags it lowers are not: running it again here
1041
+ // would clear a `preparing` some later barrier had raised.
1042
+ return
1043
+ }
1044
+ __finishParkedWasmEnvCleanup = undefined
1045
+ try {
1046
+ finish()
1047
+ } finally {
1048
+ __emnapiWasmEnvCleanupPreparing = false
1049
+ }
1050
+ __emnapiWasmEnvCleanupPrepared = true
1051
+ }
1052
+ if (!live || typeof workPending !== 'function') {
1053
+ finishCleanup()
1054
+ return
1055
+ }
1056
+ // Publish the closer before yielding: from here until `finishCleanup` runs,
1057
+ // a caller that cannot yield is entitled to end this handshake itself.
1058
+ __finishParkedWasmEnvCleanup = finishCleanup
1059
+ const finishCleanupUnlessCrashed = () => {
1060
+ try {
1061
+ __abortWasiDisposalIfThreadCrashed()
1062
+ } catch (error) {
1063
+ __finishParkedWasmEnvCleanup = undefined
1064
+ throw error
1065
+ }
1066
+ finishCleanup()
1067
+ }
1068
+ return (async () => {
1069
+ // Unbounded, exactly like the async-work drain below. The wait ends when
1070
+ // the addon reports its runtime work finished; the turns spent here are
1071
+ // what let that happen at all.
1072
+ const pace = __createWasmRuntimePollPace()
1073
+ for (;;) {
1074
+ await __yieldWasmRuntimePollTurn(pace)
1075
+ __abortWasiDisposalIfThreadCrashed()
1076
+ try {
1077
+ if (!workPending()) {
1078
+ return
1079
+ }
1080
+ } catch {
1081
+ // A trap is the only way this fails, and a trapped instance has no
1082
+ // reachable work left. Stop polling and finish.
1083
+ return
1084
+ }
1085
+ }
1086
+ })().then(finishCleanupUnlessCrashed, finishCleanupUnlessCrashed)
1087
+ }
1088
+
1089
+ // Turns to wait for while the addon still reports queued settlements. Reaching
1090
+ // zero is the only success. A counter still nonzero at this bound rejects the
1091
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
1092
+ // destroying the context over a still-queued settlement — the wait stays
1093
+ // bounded either way.
1094
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
1095
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
1096
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
1097
+ // call made on this thread (two), plus a margin.
1098
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
1099
+
1100
+ /**
1101
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
1102
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
1103
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
1104
+ * macrotask — two coalescing turns later, even for a call made on this very
1105
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
1106
+ * which drains the queue with a null env and *discards* whatever is still in it.
1107
+ *
1108
+ * So destroying without yielding first strands exactly the promises the barrier
1109
+ * exists to settle. Yield real event-loop turns until the addon reports the
1110
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
1111
+ * macrotask run.
1112
+ *
1113
+ * Returns nothing when there is nothing to wait for, which keeps disposal
1114
+ * synchronous in the common case.
1115
+ *
1116
+ * The "already drained" flag is set only once a wait has actually finished.
1117
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
1118
+ * that throws is enough — and a disposal that rejects stays retryable, so
1119
+ * marking the drain complete up front would make the retry skip it and destroy
1120
+ * the context with the barrier's settlements still queued.
1121
+ *
1122
+ * A wait that runs out of turns with the counter still nonzero rejects with
1123
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
1124
+ * "finished" is indistinguishable from the stranding above, and destroying
1125
+ * would discard the very settlement the wait was for. The rejection leaves the
1126
+ * flag unset and disposal retryable.
1127
+ */
1128
+ function __drainWasmEnvCleanup() {
1129
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
1130
+ return
1131
+ }
1132
+ if (__emnapiWasmEnvCleanupDrainPromise) {
1133
+ return __emnapiWasmEnvCleanupDrainPromise
1134
+ }
1135
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
1136
+ const observable = typeof pending === 'function'
1137
+ if (observable) {
1138
+ let queued
1139
+ try {
1140
+ queued = pending()
1141
+ } catch {
1142
+ __emnapiWasmEnvCleanupDrained = true
1143
+ return
1144
+ }
1145
+ if (!queued) {
1146
+ __emnapiWasmEnvCleanupDrained = true
1147
+ return
1148
+ }
1149
+ }
1150
+ const limit = observable
1151
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
1152
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
1153
+ const drainPromise = (async () => {
1154
+ let queued = 0
1155
+ for (let turn = 0; turn < limit; turn++) {
1156
+ await new Promise((resolve) => {
1157
+ __scheduleMacrotask(resolve)
1158
+ })
1159
+ if (!observable) {
1160
+ continue
1161
+ }
1162
+ try {
1163
+ queued = pending()
1164
+ } catch {
1165
+ return
1166
+ }
1167
+ if (!queued) {
1168
+ return
1169
+ }
1170
+ }
1171
+ if (!observable) {
1172
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
1173
+ // contract — there is nothing to consult, so finishing the turns is
1174
+ // finishing the drain.
1175
+ return
1176
+ }
1177
+ // The counter is still nonzero after every turn the bound allows. The wait
1178
+ // stays bounded — but claiming success here would be indistinguishable from
1179
+ // the stranding this drain exists to prevent: disposal would go on to
1180
+ // destroy the context, whose cleanup hook discards the still-queued
1181
+ // settlement with a null env, and the promise it was for hangs forever.
1182
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
1183
+ // unset, dispose() (and the rollback) decline to destroy, and a later
1184
+ // dispose() runs the drain again — by which time the queue has usually been
1185
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
1186
+ // attempt at most another bounded wait and a rejection, never a stranded
1187
+ // promise; the process-exit teardown still reclaims the context.
1188
+ const drainError = new Error(
1189
+ 'the wasm environment still reports ' +
1190
+ queued +
1191
+ ' queued settlement(s) after ' +
1192
+ limit +
1193
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
1194
+ )
1195
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
1196
+ throw drainError
1197
+ })().then(
1198
+ (value) => {
1199
+ // Set only when the wait actually finished AND the queue was seen empty
1200
+ // (or is unobservable): a drain that timed out with settlements still
1201
+ // queued rejects above and must stay repeatable.
1202
+ __emnapiWasmEnvCleanupDrained = true
1203
+ __emnapiWasmEnvCleanupDrainPromise = undefined
1204
+ return value
1205
+ },
1206
+ (error) => {
1207
+ __emnapiWasmEnvCleanupDrainPromise = undefined
1208
+ throw error
1209
+ },
1210
+ )
1211
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
1212
+ return drainPromise
1213
+ }
1214
+
1215
+ function __destroyEmnapiContext() {
1216
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
1217
+ __emnapiContextDestroyed = true
1218
+ return
1219
+ }
1220
+ if (__emnapiContextDestroyPromise) {
1221
+ return __emnapiContextDestroyPromise
1222
+ }
1223
+
1224
+ __prepareWasmEnvCleanup()
1225
+ if (__isPreparingWasmEnvCleanup()) {
1226
+ // Reached from inside the synchronous barrier — a promise hook one of the
1227
+ // settlements above ran, which is the reentrancy the destroy wrapper
1228
+ // exists for. `Context.destroy()` below would hit that wrapper's in-flight
1229
+ // no-op and answer `undefined`, and recording that as a completed destroy
1230
+ // is what makes the frame that *did* start the barrier skip the real one
1231
+ // afterwards, leaving the context retained with its cleanup hooks unrun.
1232
+ // Refuse instead: nothing is flagged, and that frame destroys for real the
1233
+ // moment it returns. The deferred loader carries the same backstop. A
1234
+ // parked handshake cannot get here — `__prepareWasmEnvCleanup` closes one
1235
+ // rather than skipping it.
1236
+ return
1237
+ }
1238
+ const result = __emnapiContext.destroy()
1239
+ if (!__isThenable(result)) {
1240
+ __emnapiContextDestroyed = true
1241
+ return
1242
+ }
1243
+
1244
+ const destroyPromise = Promise.resolve(result).then(
1245
+ (value) => {
1246
+ __emnapiContextDestroyed = true
1247
+ return value
1248
+ },
1249
+ (error) => {
1250
+ __emnapiContextDestroyPromise = undefined
1251
+ throw error
1252
+ },
1253
+ )
1254
+ __emnapiContextDestroyPromise = destroyPromise
1255
+ return destroyPromise
1256
+ }
1257
+
1258
+ /**
1259
+ * Holds the event loop open until `work` settles.
1260
+ *
1261
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
1262
+ * binding cannot keep a process alive, and referencing them again for the
1263
+ * termination does not hold either — emnapi unreferences a worker the moment it
1264
+ * reports `async-thread-ready`, which for a worker that was still starting
1265
+ * lands *after* the termination began. Without a handle of its own, an
1266
+ * `await dispose()` with nothing else pending exits the process with its
1267
+ * promise unsettled, and everything after the `await` is skipped.
1268
+ *
1269
+ * The timer is cleared as soon as the work settles, so this never outlives the
1270
+ * disposal that asked for it.
1271
+ */
1272
+ function __keepEventLoopAliveUntil(work) {
1273
+ const setTimer = globalThis.setInterval
1274
+ const clearTimer = globalThis.clearInterval
1275
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
1276
+ return work
1277
+ }
1278
+ let timer
1279
+ try {
1280
+ timer = setTimer(function () {}, 50)
1281
+ } catch {
1282
+ return work
1283
+ }
1284
+ const release = function () {
1285
+ try {
1286
+ clearTimer(timer)
1287
+ } catch {}
1288
+ }
1289
+ return work.then(
1290
+ (value) => {
1291
+ release()
1292
+ return value
1293
+ },
1294
+ (error) => {
1295
+ release()
1296
+ throw error
1297
+ },
1298
+ )
1299
+ }
1300
+
1301
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
1302
+ // ends when the addon reports zero, so this only decides how promptly disposal
1303
+ // notices — not how long it waits.
1304
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
1305
+
1306
+ /**
1307
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
1308
+ * would strand it.
1309
+ *
1310
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
1311
+ * it is observable from JavaScript: the threadless archive resolves
1312
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
1313
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
1314
+ * imports nor exports those symbols and the only brackets a loader could watch
1315
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
1316
+ * functions. The addon is the one place both flavors go through, so it answers
1317
+ * for both, through the same kind of handshake the settlement drain uses:
1318
+ *
1319
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
1320
+ * started. Those completion callbacks run with `napi_cancelled`, which
1321
+ * napi-rs turns into a promise rejected with an `AbortError`.
1322
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
1323
+ * callback. Work already executing refuses cancellation and stays counted
1324
+ * until it finishes normally — which it can, because this runs before the
1325
+ * barrier, before `Context.destroy()` and before anything is terminated.
1326
+ *
1327
+ * Both exports are optional: an addon built against a napi crate that predates
1328
+ * them drains nothing and keeps the previous behavior, exactly as the
1329
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
1330
+ *
1331
+ * Returns nothing when there is nothing outstanding, which keeps disposal
1332
+ * synchronous in the common case. The promise it returns otherwise never
1333
+ * rejects.
1334
+ *
1335
+ * The wait has no deadline, and that is the point: giving up would destroy the
1336
+ * environment with a completion callback still owed, which is the stranding
1337
+ * this exists to prevent. A task whose `execute` never returns already keeps an
1338
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
1339
+ * rather than inventing a bound it cannot honor.
1340
+ *
1341
+ * Safe to call from inside a completion callback, which is reachable: settling
1342
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
1343
+ * being handed back, a threadsafe-function callback — and that JavaScript can
1344
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
1345
+ *
1346
+ * - The addon keeps a work registered until its completion callback
1347
+ * *finishes*, so the count read here is at least one and this takes the
1348
+ * polling path instead of declaring the environment drained and tearing it
1349
+ * down from inside the frame that is still settling a promise.
1350
+ * - The poll is a timer, so it cannot run until the callback has returned to
1351
+ * the host — by which time that work has left the registry. The count the
1352
+ * next poll reads is the one taken after the callback finished.
1353
+ *
1354
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
1355
+ * nested call joins this disposal rather than starting a second one.
1356
+ */
1357
+ function __drainWasiAsyncWork() {
1358
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
1359
+ return __wasiAsyncWorkDrainPromise
1360
+ }
1361
+ const exports = __napiInstance?.exports
1362
+ const pending = exports?.napi_wasm_async_work_pending
1363
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
1364
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
1365
+ return
1366
+ }
1367
+
1368
+ const readPending = () => {
1369
+ try {
1370
+ return pending()
1371
+ } catch (error) {
1372
+ // A trap is the only way this call fails: it reads a counter and cannot
1373
+ // allocate or call back into JavaScript. A trapped instance can no longer
1374
+ // run anything, so its outstanding work is unreachable by definition —
1375
+ // there is nothing left to wait for, and refusing to dispose would only
1376
+ // keep a dead instance and its stuck counter alive. Best-effort here is
1377
+ // the honest answer, and it is what disposal did before this drain
1378
+ // existed.
1379
+ //
1380
+ // Only a trap. Anything else means the export is not what this loader
1381
+ // thinks it is, which is a defect worth surfacing rather than disposing
1382
+ // over.
1383
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
1384
+ return 0
1385
+ }
1386
+ throw error
1387
+ }
1388
+ }
1389
+
1390
+ if (!readPending()) {
1391
+ return
1392
+ }
1393
+ try {
1394
+ cancelPending()
1395
+ } catch {
1396
+ // Cancellation is an optimization: it bounds the wait by the work already
1397
+ // executing. Failing it only means waiting for the whole queue instead.
1398
+ }
1399
+ if (!readPending()) {
1400
+ return
1401
+ }
1402
+
1403
+ const drainPromise = __keepEventLoopAliveUntil(
1404
+ (async () => {
1405
+ while (readPending()) {
1406
+ await new Promise((resolve) => {
1407
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
1408
+ })
1409
+ __abortWasiDisposalIfThreadCrashed()
1410
+ }
1411
+ })(),
1412
+ ).then(
1413
+ () => {
1414
+ __wasiAsyncWorkDrainPromise = undefined
1415
+ },
1416
+ (error) => {
1417
+ // A wait that could not run is not a wait that finished. The only way
1418
+ // here is a host whose timers and macrotask primitives all refuse, and
1419
+ // the work is still outstanding — reporting success would destroy the
1420
+ // environment over it, which is the stranding this exists to prevent.
1421
+ // Reject instead: disposal stays retryable, and the context is not
1422
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
1423
+ __wasiAsyncWorkDrainPromise = undefined
1424
+ throw error
1425
+ },
1426
+ )
1427
+ __wasiAsyncWorkDrainPromise = drainPromise
1428
+ return drainPromise
1429
+ }
1430
+
1431
+ /**
1432
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
1433
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
1434
+ * the manager's `exit` listener instead, which reports
1435
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
1436
+ * inside the emit — aborting the `once('exit')` that backs the terminate
1437
+ * promise, so disposal never settles and the process dies with an uncaught
1438
+ * exception. Mark the termination through the manager first.
1439
+ *
1440
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
1441
+ * the initialization rollback runs on the one path where instantiation never
1442
+ * returned, so `__napiModule` is still undefined there while the workers it
1443
+ * spawned are already registered and loaded.
1444
+ *
1445
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
1446
+ */
1447
+ function __terminateWasiWorkers() {
1448
+ const cleanupErrors = []
1449
+ const pending = []
1450
+ const threadManager = __getWasiThreadManager()
1451
+
1452
+ for (const worker of __wasiWorkers) {
1453
+ let result
1454
+ try {
1455
+ if (threadManager) {
1456
+ threadManager.terminateWorker(worker)
1457
+ // `terminateWorker` leaves behind a reporter that logs every message
1458
+ // still queued on the port, which Node flushes on exit. Nothing is
1459
+ // listening for those any more.
1460
+ worker.onmessage = undefined
1461
+ }
1462
+ result = worker.terminate()
1463
+ } catch (error) {
1464
+ cleanupErrors.push(error)
1465
+ continue
1466
+ }
1467
+ if (__isThenable(result)) {
1468
+ pending.push(
1469
+ Promise.resolve(result).then(
1470
+ () => {
1471
+ __wasiWorkers.delete(worker)
1472
+ },
1473
+ (error) => {
1474
+ cleanupErrors.push(error)
1475
+ },
1476
+ ),
1477
+ )
1478
+ } else {
1479
+ __wasiWorkers.delete(worker)
1480
+ }
1481
+ }
1482
+
1483
+ const finish = () => {
1484
+ if (cleanupErrors.length > 0) {
1485
+ throw __createCleanupError(
1486
+ cleanupErrors,
1487
+ 'Failed to terminate WASI workers',
1488
+ )
1489
+ }
1490
+ }
1491
+ return pending.length > 0
1492
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
1493
+ : finish()
1494
+ }
1495
+
1496
+ function __finishWasiDisposal() {
1497
+ const workerResult = __terminateWasiWorkers()
1498
+ if (__isThenable(workerResult)) {
1499
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
1500
+ }
1501
+ return __completeWasiDisposal()
1502
+ }
1503
+
1504
+ function __continueWasiDisposal() {
1505
+ __abortWasiDisposalIfThreadCrashed()
1506
+ const destroyResult = __destroyEmnapiContext()
1507
+ if (__isThenable(destroyResult)) {
1508
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
1509
+ }
1510
+ return __finishWasiDisposal()
1511
+ }
1512
+
1513
+ function __drainWasmEnvForWasiDisposal() {
1514
+ __abortWasiDisposalIfThreadCrashed()
1515
+ const drainResult = __drainWasmEnvCleanup()
1516
+ if (__isThenable(drainResult)) {
1517
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
1518
+ }
1519
+ return __continueWasiDisposal()
1520
+ }
1521
+
1522
+ function __cleanUpWasmEnvForWasiDisposal() {
1523
+ __abortWasiDisposalIfThreadCrashed()
1524
+ // Run the pre-teardown barrier — yielding the turns its two-phase form asks
1525
+ // for, when the addon has one — then let the settlements it queued actually
1526
+ // reach JavaScript, and only then destroy the environment. Doing any two of
1527
+ // these back to back is what strands them.
1528
+ const prepareResult = __prepareWasmEnvCleanupWithTurns()
1529
+ if (__isThenable(prepareResult)) {
1530
+ return Promise.resolve(prepareResult).then(__drainWasmEnvForWasiDisposal)
1531
+ }
1532
+ return __drainWasmEnvForWasiDisposal()
1533
+ }
1534
+
1535
+ function __startWasiDisposal() {
1536
+ // Outstanding `napi_async_work` goes first, while the environment is still
1537
+ // completely live: the completion callbacks run addon code, and everything
1538
+ // after this point takes that away from them — the barrier shuts the async
1539
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
1540
+ // the pool threads removes what would have reported the work finished.
1541
+ const asyncWorkResult = __drainWasiAsyncWork()
1542
+ if (__isThenable(asyncWorkResult)) {
1543
+ return Promise.resolve(asyncWorkResult).then(
1544
+ __cleanUpWasmEnvForWasiDisposal,
1545
+ )
1546
+ }
1547
+ return __cleanUpWasmEnvForWasiDisposal()
1548
+ }
1549
+
1550
+ /**
1551
+ * Disposes this generated WASI binding.
1552
+ *
1553
+ * Access this function with:
1554
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
1555
+ */
1556
+ function __disposeWasiBinding() {
1557
+ if (__wasiDisposePromise) {
1558
+ return __wasiDisposePromise
1559
+ }
1560
+ if (!__wasiDisposed && __hasWasiThreadCrashed()) {
1561
+ return __disposeWasiBindingAfterThreadCrash()
1562
+ }
1563
+ if (__wasiDisposed) {
1564
+ return Promise.resolve()
1565
+ }
1566
+
1567
+ let resolveDispose
1568
+ let rejectDispose
1569
+ const disposePromise = new Promise((resolve, reject) => {
1570
+ resolveDispose = resolve
1571
+ rejectDispose = reject
1572
+ })
1573
+ __wasiDisposePromise = disposePromise
1574
+
1575
+ let result
1576
+ try {
1577
+ result = __startWasiDisposal()
1578
+ } catch (error) {
1579
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1580
+ return disposePromise
1581
+ }
1582
+ __wasiDisposePromise = undefined
1583
+ rejectDispose(error)
1584
+ return disposePromise
1585
+ }
1586
+
1587
+ Promise.resolve(result).then(
1588
+ (value) => {
1589
+ __wasiDisposed = true
1590
+ resolveDispose(value)
1591
+ },
1592
+ (error) => {
1593
+ if (__settleWasiDisposalAfterThreadCrash(resolveDispose, rejectDispose)) {
1594
+ return
1595
+ }
1596
+ __wasiDisposePromise = undefined
1597
+ rejectDispose(error)
1598
+ },
1599
+ )
1600
+ return disposePromise
1601
+ }
1602
+
1603
+ function __publishWasiDispose(exports) {
1604
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
1605
+ configurable: false,
1606
+ enumerable: false,
1607
+ value: __disposeWasiBinding,
1608
+ writable: false,
1609
+ })
1610
+ }
1611
+
1612
+ function __finishWasiInitializationRollback(cleanupErrors) {
1613
+ let workerResult
1614
+ try {
1615
+ workerResult = __terminateWasiWorkers()
1616
+ } catch (cleanupError) {
1617
+ cleanupErrors.push(cleanupError)
1618
+ return cleanupErrors
1619
+ }
1620
+ if (__isThenable(workerResult)) {
1621
+ return Promise.resolve(workerResult)
1622
+ .catch((cleanupError) => {
1623
+ cleanupErrors.push(cleanupError)
1624
+ })
1625
+ .then(() => cleanupErrors)
1626
+ }
1627
+ return cleanupErrors
1628
+ }
1629
+
1630
+ function __destroyContextForWasiRollback(cleanupErrors) {
1631
+ __abortWasiDisposalIfThreadCrashed()
1632
+ let destroyResult
1633
+ try {
1634
+ destroyResult = __destroyEmnapiContext()
1635
+ } catch (cleanupError) {
1636
+ cleanupErrors.push(cleanupError)
1637
+ return __finishWasiInitializationRollback(cleanupErrors)
1638
+ }
1639
+ if (__isThenable(destroyResult)) {
1640
+ return Promise.resolve(destroyResult)
1641
+ .catch((cleanupError) => {
1642
+ cleanupErrors.push(cleanupError)
1643
+ })
1644
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
1645
+ }
1646
+ return __finishWasiInitializationRollback(cleanupErrors)
1647
+ }
1648
+
1649
+ /**
1650
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
1651
+ * hands it to whatever this flavor has that can still reclaim it.
1652
+ */
1653
+ function __retainFailedWasiRollback(cleanupErrors) {
1654
+ try {
1655
+ __retainWasiRollbackForRetry()
1656
+ } catch (cleanupError) {
1657
+ cleanupErrors.push(cleanupError)
1658
+ }
1659
+ return cleanupErrors
1660
+ }
1661
+
1662
+ /**
1663
+ * Initialization can fail *after* registration has already run, and registration
1664
+ * runs with a live environment: a module-init hook can start async work and then
1665
+ * return an error, and the promise it created may already have escaped into
1666
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
1667
+ * path needs the same drain the ordinary disposal does — destroying without
1668
+ * yielding discards the queue with a null env and strands the promise.
1669
+ *
1670
+ * Stays synchronous when nothing is queued, which covers every failure before
1671
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
1672
+ *
1673
+ * A barrier or drain that did *not* finish stops the rollback short of
1674
+ * destroying, which is what `dispose()` already does — a rejected drain there
1675
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
1676
+ * two trades, and not because of what it saves:
1677
+ *
1678
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
1679
+ * threadsafe function's cleanup hook, which drains the queue with a null env
1680
+ * and discards it, so a promise that already escaped into JavaScript hangs
1681
+ * forever with nothing left that could ever settle it.
1682
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
1683
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
1684
+ * which this module's scope holds either way. What stopping short retains is
1685
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
1686
+ * - Retry is not theoretical. A rollback that records a cleanup error is
1687
+ * already kept in the process-wide registry above, so re-`require()`ing this
1688
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
1689
+ * means the replay drains again rather than skipping it. Destroying first is
1690
+ * what makes that retained record useless.
1691
+ *
1692
+ * The residual cost is honest: the CJS flavor hands the context to its
1693
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
1694
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
1695
+ * throws while evaluating is permanently errored, so re-importing rethrows
1696
+ * without re-running this file — and there the context stays until the realm
1697
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
1698
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
1699
+ */
1700
+ function __runWasiInitializationRollbackSteps() {
1701
+ // The environment teardown this rollback performs, kept nested so it cannot
1702
+ // be reached without the async-work drain below running first.
1703
+ function __rollbackWasmEnvForWasiInitialization() {
1704
+ __abortWasiDisposalIfThreadCrashed()
1705
+ const cleanupErrors = []
1706
+ let prepareResult
1707
+ try {
1708
+ prepareResult = __prepareWasmEnvCleanupWithTurns()
1709
+ } catch (cleanupError) {
1710
+ cleanupErrors.push(cleanupError)
1711
+ return __retainFailedWasiRollback(cleanupErrors)
1712
+ }
1713
+ if (__isThenable(prepareResult)) {
1714
+ return Promise.resolve(prepareResult).then(
1715
+ () => __drainWasmEnvForWasiRollback(cleanupErrors),
1716
+ (cleanupError) => {
1717
+ cleanupErrors.push(cleanupError)
1718
+ return __retainFailedWasiRollback(cleanupErrors)
1719
+ },
1720
+ )
1721
+ }
1722
+ return __drainWasmEnvForWasiRollback(cleanupErrors)
1723
+ }
1724
+
1725
+ // The settlement drain of the rollback above, reached either straight away or
1726
+ // after the barrier's two-phase form has yielded its turns. A barrier that
1727
+ // did not finish never gets here: it retains instead, exactly as a drain that
1728
+ // did not finish does.
1729
+ function __drainWasmEnvForWasiRollback(cleanupErrors) {
1730
+ __abortWasiDisposalIfThreadCrashed()
1731
+ let drainResult
1732
+ try {
1733
+ drainResult = __drainWasmEnvCleanup()
1734
+ } catch (cleanupError) {
1735
+ cleanupErrors.push(cleanupError)
1736
+ return __retainFailedWasiRollback(cleanupErrors)
1737
+ }
1738
+ if (__isThenable(drainResult)) {
1739
+ return Promise.resolve(drainResult).then(
1740
+ () => __destroyContextForWasiRollback(cleanupErrors),
1741
+ (cleanupError) => {
1742
+ cleanupErrors.push(cleanupError)
1743
+ return __retainFailedWasiRollback(cleanupErrors)
1744
+ },
1745
+ )
1746
+ }
1747
+ return __destroyContextForWasiRollback(cleanupErrors)
1748
+ }
1749
+
1750
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
1751
+ // work before the load goes on to fail, and this rollback tears down exactly
1752
+ // what those completions need. Settle them while everything is still live,
1753
+ // before the barrier and the teardown above take that away.
1754
+ //
1755
+ // A drain that could not finish leaves async work possibly outstanding, and
1756
+ // destroying the context over it would strand exactly what this rollback is
1757
+ // there to settle. Stop short and retain instead — the same trade
1758
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
1759
+ // the context stays reclaimable by a retry or by this flavor's own
1760
+ // last-resort teardown.
1761
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
1762
+ __retainFailedWasiRollback([cleanupError])
1763
+ let asyncWorkResult
1764
+ try {
1765
+ asyncWorkResult = __drainWasiAsyncWork()
1766
+ } catch (cleanupError) {
1767
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
1768
+ }
1769
+ if (__isThenable(asyncWorkResult)) {
1770
+ return Promise.resolve(asyncWorkResult).then(
1771
+ __rollbackWasmEnvForWasiInitialization,
1772
+ __retainAfterAsyncWorkDrainFailure,
1773
+ )
1774
+ }
1775
+ return __rollbackWasmEnvForWasiInitialization()
1776
+ }
1777
+
1778
+ /**
1779
+ * The rollback above, stopped when a wasm thread has died.
1780
+ *
1781
+ * Its polls wait for work the dead thread still counts, so they never end, and
1782
+ * the barrier's `…_finish` and `Context.destroy()` would re-enter wasm
1783
+ * and wait on that thread for good. While the rollback runs, the poll turns
1784
+ * and step boundaries stop it (`__abortWasiDisposalIfThreadCrashed`), and a
1785
+ * crash seen before, during or after it ends it through
1786
+ * `__rollbackWasiInitializationAfterThreadCrash`. Without a crash the
1787
+ * result — synchronous or not — is passed through unchanged.
1788
+ */
1789
+ function __rollbackWasiInitialization() {
1790
+ if (__hasWasiThreadCrashed()) {
1791
+ return __rollbackWasiInitializationAfterThreadCrash()
1792
+ }
1793
+ __wasiInitializationRollbackActive = true
1794
+ let result
1795
+ try {
1796
+ result = __runWasiInitializationRollbackSteps()
1797
+ } catch (error) {
1798
+ __wasiInitializationRollbackActive = false
1799
+ if (__hasWasiThreadCrashed()) {
1800
+ return __rollbackWasiInitializationAfterThreadCrash()
1801
+ }
1802
+ throw error
1803
+ }
1804
+ if (!__isThenable(result)) {
1805
+ __wasiInitializationRollbackActive = false
1806
+ return __hasWasiThreadCrashed()
1807
+ ? __rollbackWasiInitializationAfterThreadCrash()
1808
+ : result
1809
+ }
1810
+ return Promise.resolve(result).then(
1811
+ (cleanupErrors) => {
1812
+ __wasiInitializationRollbackActive = false
1813
+ return __hasWasiThreadCrashed()
1814
+ ? __rollbackWasiInitializationAfterThreadCrash()
1815
+ : cleanupErrors
1816
+ },
1817
+ (error) => {
1818
+ __wasiInitializationRollbackActive = false
1819
+ if (__hasWasiThreadCrashed()) {
1820
+ return __rollbackWasiInitializationAfterThreadCrash()
1821
+ }
1822
+ throw error
1823
+ },
1824
+ )
1825
+ }
1826
+
1827
+ const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
1828
+ const __wasiRollbackRegistryKey =
1829
+ typeof __filename === 'string' ? __filename : __wasmFilePath
1830
+
1831
+ function __getWasiRollbackRegistry() {
1832
+ const existing = process[__wasiRollbackRegistrySymbol]
1833
+ if (existing !== undefined) {
1834
+ if (!(existing instanceof Map)) {
1835
+ throw new TypeError(
1836
+ 'The process-wide NAPI-RS WASI rollback registry is invalid',
1837
+ )
1838
+ }
1839
+ return existing
1840
+ }
1841
+ const registry = new Map()
1842
+ Object.defineProperty(process, __wasiRollbackRegistrySymbol, {
1843
+ configurable: false,
1844
+ enumerable: false,
1845
+ value: registry,
1846
+ writable: false,
1847
+ })
1848
+ return registry
1849
+ }
1850
+
1851
+ const __wasiRollbackRegistry = __getWasiRollbackRegistry()
1852
+
1853
+ function __completeWasiInitializationRollback(record, cleanupErrors) {
1854
+ try {
1855
+ if (cleanupErrors.length === 0) {
1856
+ if (
1857
+ __wasiRollbackRegistry.get(__wasiRollbackRegistryKey) === record
1858
+ ) {
1859
+ __wasiRollbackRegistry.delete(__wasiRollbackRegistryKey)
1860
+ }
1861
+ return
1862
+ }
1863
+ record.error = __attachCleanupErrors(record.error, cleanupErrors)
1864
+ } catch (cleanupError) {
1865
+ try {
1866
+ record.error = __createCleanupError(
1867
+ [record.error, cleanupError],
1868
+ 'WASI binding initialization and cleanup failed',
1869
+ )
1870
+ } catch {}
1871
+ } finally {
1872
+ record.active = false
1873
+ record.promise = undefined
1874
+ }
1875
+ }
1876
+
1877
+ function __runWasiInitializationRollback(record) {
1878
+ if (record.active) {
1879
+ return
1880
+ }
1881
+ record.active = true
1882
+
1883
+ let rollbackResult
1884
+ try {
1885
+ rollbackResult = record.rollback()
1886
+ } catch (cleanupError) {
1887
+ __completeWasiInitializationRollback(record, [cleanupError])
1888
+ return
1889
+ }
1890
+
1891
+ if (!__isThenable(rollbackResult)) {
1892
+ __completeWasiInitializationRollback(record, rollbackResult)
1893
+ return
1894
+ }
1895
+
1896
+ record.promise = Promise.resolve(rollbackResult).then(
1897
+ (cleanupErrors) => {
1898
+ __completeWasiInitializationRollback(record, cleanupErrors)
1899
+ },
1900
+ (cleanupError) => {
1901
+ __completeWasiInitializationRollback(record, [cleanupError])
1902
+ },
1903
+ )
1904
+ }
1905
+
1906
+ const __pendingWasiRollback = __wasiRollbackRegistry.get(
1907
+ __wasiRollbackRegistryKey,
1908
+ )
1909
+ if (__pendingWasiRollback !== undefined) {
1910
+ __runWasiInitializationRollback(__pendingWasiRollback)
1911
+ throw __pendingWasiRollback.error
1912
+ }
1913
+
1914
+ let __wasiModule
1915
+ let __napiModule
1916
+ let __wasiExitListenerRegistered = false
1917
+
1918
+ function __removeWasiExitListener() {
1919
+ if (
1920
+ __wasiExitListenerRegistered &&
1921
+ typeof process.removeListener === 'function'
1922
+ ) {
1923
+ process.removeListener('exit', __disposeWasiBindingAtExit)
1924
+ }
1925
+ __wasiExitListenerRegistered = false
1926
+ }
1927
+
1928
+ function __disposeWasiBindingAtExit() {
1929
+ __wasiExitListenerRegistered = false
1930
+ if (__hasWasiThreadCrashed()) {
1931
+ // Never re-enter wasm after a thread died: the environment cleanup joins
1932
+ // the dead thread's work and would hang the exit forever — SIGTERM
1933
+ // included, since its JavaScript listener never gets a turn. Stop the
1934
+ // workers and leave.
1935
+ try {
1936
+ void Promise.resolve(__terminateWasiWorkers()).catch(() => {})
1937
+ } catch {}
1938
+ return
1939
+ }
1940
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
1941
+ // settlements the way __startWasiDisposal does — the process is leaving and
1942
+ // those promises have no observer left anyway. Run the synchronous teardown
1943
+ // directly. Every step is idempotent, which also makes this the synchronous
1944
+ // finish for a disposal that is still waiting for its drain — and, through
1945
+ // __prepareWasmEnvCleanup, for one still parked between the two halves of
1946
+ // the environment cleanup barrier: there are no turns left to poll with, so
1947
+ // this closes that handshake with `…_finish`, which joins.
1948
+ try {
1949
+ __destroyEmnapiContext()
1950
+ } catch {}
1951
+ try {
1952
+ const workerResult = __terminateWasiWorkers()
1953
+ if (__isThenable(workerResult)) {
1954
+ void Promise.resolve(workerResult).catch(() => {})
1955
+ }
1956
+ } catch {}
1957
+ }
1958
+
1959
+ function __registerWasiExitListener() {
1960
+ if (
1961
+ !__wasiExitListenerRegistered &&
1962
+ typeof process.once === 'function'
1963
+ ) {
1964
+ process.once('exit', __disposeWasiBindingAtExit)
1965
+ __wasiExitListenerRegistered = true
1966
+ }
1967
+ }
1968
+
1969
+ __completeWasiDisposal = __removeWasiExitListener
1970
+ // A rollback that could not reach the queued settlements keeps the context so
1971
+ // the registry replay above can retry it. Nothing forces that replay to happen,
1972
+ // so hand the context to the same synchronous teardown a successful load uses:
1973
+ // a process that exits without ever retrying still runs the cleanup hooks. The
1974
+ // handler cannot yield, so it does not settle anything — but by then the process
1975
+ // is leaving and those promises have no observer left anyway.
1976
+ __retainWasiRollbackForRetry = __registerWasiExitListener
1977
+
1978
+ function __captureEmnapiAutoDestroyListener() {
1979
+ if (
1980
+ typeof process.prependListener !== 'function' ||
1981
+ typeof process.removeListener !== 'function'
1982
+ ) {
1983
+ return
1984
+ }
1985
+ let __autoDestroyListener
1986
+ const __captureListener = (__event, __listener) => {
1987
+ if (__event === 'beforeExit' && __autoDestroyListener === undefined) {
1988
+ __autoDestroyListener = __listener
1989
+ }
1990
+ }
1991
+ try {
1992
+ // Run before existing newListener hooks so a hook that registers its own
1993
+ // beforeExit listener cannot be mistaken for emnapi's registration.
1994
+ process.prependListener('newListener', __captureListener)
1995
+ } catch {
1996
+ return
1997
+ }
1998
+ return () => {
1999
+ try {
2000
+ process.removeListener('newListener', __captureListener)
2001
+ } catch {}
2002
+ if (__autoDestroyListener !== undefined) {
2003
+ try {
2004
+ process.removeListener('beforeExit', __autoDestroyListener)
2005
+ } catch {}
2006
+ }
2007
+ }
2008
+ }
2009
+
2010
+ try {
2011
+ const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
2012
+ try {
2013
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
2014
+ __emnapiCreateContext({ autoDestroy: false }),
2015
+ __prepareWasmEnvCleanup,
2016
+ __isPreparingWasmEnvCleanup,
2017
+ )
2018
+ // emnapi 2.x still registers an unconditional once-listener for
2019
+ // beforeExit that auto-destroys the context, and suppressDestroy() only
2020
+ // neutralizes its callback without removing it. This loader owns cleanup
2021
+ // through its 'exit' listener, so emnapi's listener is captured and
2022
+ // removed; suppressDestroy() remains the safety net when removal fails.
2023
+ __emnapiContext.suppressDestroy()
2024
+ } finally {
2025
+ // Remove only the exact emnapi callback captured above.
2026
+ __finishAutoDestroyCapture?.()
2027
+ }
2028
+
2029
+ ;({
2030
+ instance: __napiInstance,
2031
+ module: __wasiModule,
2032
+ napiModule: __napiModule,
2033
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
2034
+ context: __emnapiContext,
2035
+ asyncWorkPoolSize: (function () {
2036
+ const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE)
2037
+ // NaN > 0 is false
2038
+ if (threadsSizeFromEnv > 0) {
2039
+ return threadsSizeFromEnv
2040
+ } else {
2041
+ return 4
2042
+ }
2043
+ })(),
2044
+ reuseWorker: true,
2045
+ plugins: [
2046
+ __captureWasiThreadManager,
2047
+ __emnapiAsyncWorkPlugin,
2048
+ __emnapiTSFNPlugin,
2049
+ ],
2050
+ wasi: __wasi,
2051
+ onCreateWorker() {
2052
+ const worker = __createWasiWorker(__nodePath.join(__dirname, 'wasi-worker.mjs'))
2053
+ __wasiWorkers.add(worker)
2054
+ // Registered before emnapi's own listeners, which rethrow the error.
2055
+ worker.on('error', (error) => {
2056
+ __wasiThreadCrashed = true
2057
+ __recordWasiThreadCrashError(error, worker.threadId)
2058
+ })
2059
+ worker.onmessage = ({ data }) => {
2060
+ __wasmCreateOnMessageForFsProxy(__nodeFs)(data)
2061
+ }
2062
+
2063
+ // The main thread of Node.js waits for all the active handles before exiting.
2064
+ // But Rust threads are never waited without `thread::join`.
2065
+ // So here we hack the code of Node.js to prevent the workers from being referenced (active).
2066
+ // According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415,
2067
+ // a worker is consist of two handles: kPublicPort and kHandle.
2068
+ {
2069
+ const kPublicPort = Object.getOwnPropertySymbols(worker).find((s) =>
2070
+ s.toString().includes('kPublicPort'),
2071
+ )
2072
+ if (kPublicPort) {
2073
+ worker[kPublicPort].ref = () => {}
2074
+ }
2075
+
2076
+ const kHandle = Object.getOwnPropertySymbols(worker).find((s) =>
2077
+ s.toString().includes('kHandle'),
2078
+ )
2079
+ if (kHandle) {
2080
+ worker[kHandle].ref = () => {}
2081
+ }
2082
+
2083
+ worker.unref()
2084
+ // These stubs stay in place for the worker's whole life, disposal
2085
+ // included: `__keepEventLoopAliveUntil` is what holds the process open
2086
+ // while a termination is pending, precisely because a worker's own
2087
+ // references cannot be relied on for it.
2088
+ }
2089
+ return worker
2090
+ },
2091
+ overwriteImports(importObject) {
2092
+ importObject.env = {
2093
+ ...importObject.env,
2094
+ ...importObject.napi,
2095
+ ...importObject.emnapi,
2096
+ memory: __sharedMemory,
2097
+ }
2098
+ return importObject
2099
+ },
2100
+ beforeInit({ instance }) {
2101
+ __napiInstance = instance
2102
+ __captureWasiAddonCrashFlag(instance)
2103
+ for (const name of Object.keys(instance.exports)) {
2104
+ if (name.startsWith('__napi_register__')) {
2105
+ instance.exports[name]()
2106
+ }
2107
+ }
2108
+ },
2109
+ }))
2110
+ __publishWasiDispose(__napiModule.exports)
2111
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
2112
+ // export does not travel with it, so carry the marker on the binding itself
2113
+ // too. Three things pin the stamp to exactly this spot:
2114
+ // - inside this `try`, because the guard throws on a
2115
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
2116
+ // catch below tears the environment — context, workers, exit listener —
2117
+ // back down;
2118
+ // - after the async runtime host install, which hands this same object to
2119
+ // addon-provided registration functions that may put anything on it;
2120
+ // - assigning onto the loader's own `module.exports`, which is still the
2121
+ // original object here, so an addon accessor with a refusing setter is
2122
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
2123
+ // export detection — reads the static `module.exports.<name> =` either
2124
+ // way, and the later `module.exports = __napiModule.exports` does not
2125
+ // undo that.
2126
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
2127
+ __registerWasiExitListener()
2128
+ } catch (error) {
2129
+ const rollback = {
2130
+ active: false,
2131
+ error,
2132
+ promise: undefined,
2133
+ rollback: __rollbackWasiInitialization,
2134
+ }
2135
+ __wasiRollbackRegistry.set(__wasiRollbackRegistryKey, rollback)
2136
+ __runWasiInitializationRollback(rollback)
2137
+ throw rollback.error
2138
+ }
2139
+ module.exports = __napiModule.exports
2140
+ module.exports.Document = __napiModule.exports.Document
2141
+ module.exports.Import = __napiModule.exports.Import
2142
+ module.exports.Slot = __napiModule.exports.Slot
2143
+ module.exports.summarize = __napiModule.exports.summarize
2144
+ module.exports.versionDate = __napiModule.exports.versionDate