@petrea/wasm 0.0.0 → 0.5.1

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,1209 @@
1
+ // napi-rs-artifact-metadata:{"version":2,"rootEntry":"index.js","exports":["transpileAsync","transpileNativeSync","transpileUtf16Async","transpileUtf16Sync"],"managedRootEntries":["browser.js","index.js","binding.wasm","binding.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, 'binding.wasm32-wasip1.wasm')
86
+ const __wasmDebugFilePath = __nodePath.join(__dirname, 'binding.wasm32-wasip1.debug.wasm')
87
+
88
+ if (__nodeFs.existsSync(__wasmDebugFilePath)) {
89
+ __wasmFilePath = __wasmDebugFilePath
90
+ } else if (!__nodeFs.existsSync(__wasmFilePath)) {
91
+ const __wasiPackageEntry = require.resolve('@petrea/binding-wasm32-wasip1')
92
+ const __packagedWasmFilePath = __nodePath.join(
93
+ __nodePath.dirname(__wasiPackageEntry),
94
+ 'binding.wasm32-wasip1.wasm',
95
+ )
96
+ if (!__nodeFs.existsSync(__packagedWasmFilePath)) {
97
+ throw new Error(
98
+ '@petrea/binding-wasm32-wasip1 is installed but is missing binding.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
+ let __emnapiWasmEnvCleanupRan = false
144
+ let __emnapiWasmEnvCleanupDrained = false
145
+ let __emnapiWasmEnvCleanupDrainPromise
146
+ let __wasiDisposed = false
147
+ let __wasiAsyncWorkDrainPromise
148
+ let __wasiDisposePromise
149
+ let __completeWasiDisposal = function () {}
150
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
151
+ // that stopped short of destroying the context. See
152
+ // `__rollbackWasiInitialization`.
153
+ let __retainWasiRollbackForRetry = function () {}
154
+
155
+ function __isThenable(value) {
156
+ return (
157
+ value !== null &&
158
+ (typeof value === 'object' || typeof value === 'function') &&
159
+ typeof value.then === 'function'
160
+ )
161
+ }
162
+
163
+ function __createCleanupError(errors, message) {
164
+ if (errors.length === 1) {
165
+ return errors[0]
166
+ }
167
+ const __AggregateError = globalThis.AggregateError
168
+ if (typeof __AggregateError === 'function') {
169
+ return new __AggregateError(errors, message)
170
+ }
171
+ const error = new Error(message)
172
+ error.errors = errors
173
+ return error
174
+ }
175
+
176
+ function __attachCleanupErrors(error, cleanupErrors) {
177
+ if (cleanupErrors.length === 0) {
178
+ return error
179
+ }
180
+ const cleanupError = __createCleanupError(
181
+ cleanupErrors,
182
+ 'WASI binding cleanup failed',
183
+ )
184
+ try {
185
+ if (
186
+ error &&
187
+ (typeof error === 'object' || typeof error === 'function')
188
+ ) {
189
+ if (error.cause === undefined) {
190
+ error.cause = cleanupError
191
+ if (error.cause === cleanupError) {
192
+ return error
193
+ }
194
+ }
195
+ if (Array.isArray(error.cleanupErrors)) {
196
+ error.cleanupErrors.push(cleanupError)
197
+ return error
198
+ } else {
199
+ const attachedCleanupErrors = [cleanupError]
200
+ error.cleanupErrors = attachedCleanupErrors
201
+ if (error.cleanupErrors === attachedCleanupErrors) {
202
+ return error
203
+ }
204
+ }
205
+ }
206
+ } catch {}
207
+ const aggregate = __createCleanupError(
208
+ [error, cleanupError],
209
+ 'WASI binding initialization and cleanup failed',
210
+ )
211
+ try {
212
+ aggregate.cause = error
213
+ } catch {}
214
+ return aggregate
215
+ }
216
+
217
+ function __wrapEmnapiContextDestroyForSettlement(
218
+ context,
219
+ prepareEnvCleanup,
220
+ isPreparingEnvCleanup,
221
+ ) {
222
+ let destroy
223
+ try {
224
+ destroy = context.destroy
225
+ } catch {
226
+ return context
227
+ }
228
+ if (typeof destroy !== 'function') {
229
+ return context
230
+ }
231
+ try {
232
+ Object.defineProperty(context, 'destroy', {
233
+ configurable: true,
234
+ enumerable: false,
235
+ writable: true,
236
+ value: function () {
237
+ // Reentered from a promise hook that fired inside the barrier: the
238
+ // frame running it destroys as soon as it returns.
239
+ if (isPreparingEnvCleanup?.()) {
240
+ return
241
+ }
242
+ prepareEnvCleanup?.()
243
+ return Reflect.apply(destroy, this, arguments)
244
+ },
245
+ })
246
+ } catch {}
247
+ return context
248
+ }
249
+
250
+ function __isPreparingWasmEnvCleanup() {
251
+ return __emnapiWasmEnvCleanupPreparing
252
+ }
253
+
254
+ function __prepareWasmEnvCleanup() {
255
+ if (__emnapiWasmEnvCleanupPrepared || __emnapiWasmEnvCleanupPreparing) {
256
+ return
257
+ }
258
+ const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
259
+ if (typeof prepare === 'function') {
260
+ // The addon settles the promises it cancels synchronously, under a
261
+ // non-reentrant lifecycle mutex: anything a promise hook calls from in
262
+ // here must not reach this export again.
263
+ __emnapiWasmEnvCleanupPreparing = true
264
+ try {
265
+ prepare()
266
+ } finally {
267
+ __emnapiWasmEnvCleanupPreparing = false
268
+ }
269
+ __emnapiWasmEnvCleanupRan = true
270
+ }
271
+ __emnapiWasmEnvCleanupPrepared = true
272
+ }
273
+
274
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
275
+ // on, so the drain turns below interleave with that dispatch instead of racing
276
+ // ahead of it on a faster queue.
277
+ const __scheduleMacrotask = (function () {
278
+ if (typeof setImmediate === 'function') {
279
+ return function (callback) {
280
+ setImmediate(callback)
281
+ }
282
+ }
283
+ const __MessageChannel = globalThis.MessageChannel
284
+ if (typeof __MessageChannel === 'function') {
285
+ return function (callback) {
286
+ const channel = new __MessageChannel()
287
+ channel.port1.onmessage = function () {
288
+ channel.port1.onmessage = null
289
+ try {
290
+ channel.port1.close()
291
+ } catch {}
292
+ try {
293
+ channel.port2.close()
294
+ } catch {}
295
+ callback()
296
+ }
297
+ channel.port2.postMessage(null)
298
+ }
299
+ }
300
+ return function (callback) {
301
+ setTimeout(callback, 0)
302
+ }
303
+ })()
304
+
305
+ // A real, *referenced* timer, for waits that must let the whole host make
306
+ // progress between looks — the async-work drain polls the addon rather than
307
+ // interleaving with the @emnapi/core dispatch, so a zero-delay macrotask there
308
+ // would spin the loop instead of yielding it. Falls back to the macrotask
309
+ // scheduler on a host without timers.
310
+ function __scheduleTimer(callback, delay) {
311
+ const setTimer = globalThis.setTimeout
312
+ if (typeof setTimer !== 'function') {
313
+ __scheduleMacrotask(callback)
314
+ return
315
+ }
316
+ try {
317
+ setTimer(callback, delay)
318
+ } catch {
319
+ __scheduleMacrotask(callback)
320
+ }
321
+ }
322
+
323
+ // Turns to wait for while the addon still reports queued settlements. Reaching
324
+ // zero is the only success. A counter still nonzero at this bound rejects the
325
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
326
+ // destroying the context over a still-queued settlement — the wait stays
327
+ // bounded either way.
328
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
329
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
330
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
331
+ // call made on this thread (two), plus a margin.
332
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
333
+
334
+ /**
335
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
336
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
337
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
338
+ * macrotask — two coalescing turns later, even for a call made on this very
339
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
340
+ * which drains the queue with a null env and *discards* whatever is still in it.
341
+ *
342
+ * So destroying without yielding first strands exactly the promises the barrier
343
+ * exists to settle. Yield real event-loop turns until the addon reports the
344
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
345
+ * macrotask run.
346
+ *
347
+ * Returns nothing when there is nothing to wait for, which keeps disposal
348
+ * synchronous in the common case.
349
+ *
350
+ * The "already drained" flag is set only once a wait has actually finished.
351
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
352
+ * that throws is enough — and a disposal that rejects stays retryable, so
353
+ * marking the drain complete up front would make the retry skip it and destroy
354
+ * the context with the barrier's settlements still queued.
355
+ *
356
+ * A wait that runs out of turns with the counter still nonzero rejects with
357
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
358
+ * "finished" is indistinguishable from the stranding above, and destroying
359
+ * would discard the very settlement the wait was for. The rejection leaves the
360
+ * flag unset and disposal retryable.
361
+ */
362
+ function __drainWasmEnvCleanup() {
363
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
364
+ return
365
+ }
366
+ if (__emnapiWasmEnvCleanupDrainPromise) {
367
+ return __emnapiWasmEnvCleanupDrainPromise
368
+ }
369
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
370
+ const observable = typeof pending === 'function'
371
+ if (observable) {
372
+ let queued
373
+ try {
374
+ queued = pending()
375
+ } catch {
376
+ __emnapiWasmEnvCleanupDrained = true
377
+ return
378
+ }
379
+ if (!queued) {
380
+ __emnapiWasmEnvCleanupDrained = true
381
+ return
382
+ }
383
+ }
384
+ const limit = observable
385
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
386
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
387
+ const drainPromise = (async () => {
388
+ let queued = 0
389
+ for (let turn = 0; turn < limit; turn++) {
390
+ await new Promise((resolve) => {
391
+ __scheduleMacrotask(resolve)
392
+ })
393
+ if (!observable) {
394
+ continue
395
+ }
396
+ try {
397
+ queued = pending()
398
+ } catch {
399
+ return
400
+ }
401
+ if (!queued) {
402
+ return
403
+ }
404
+ }
405
+ if (!observable) {
406
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
407
+ // contract — there is nothing to consult, so finishing the turns is
408
+ // finishing the drain.
409
+ return
410
+ }
411
+ // The counter is still nonzero after every turn the bound allows. The wait
412
+ // stays bounded — but claiming success here would be indistinguishable from
413
+ // the stranding this drain exists to prevent: disposal would go on to
414
+ // destroy the context, whose cleanup hook discards the still-queued
415
+ // settlement with a null env, and the promise it was for hangs forever.
416
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
417
+ // unset, dispose() (and the rollback) decline to destroy, and a later
418
+ // dispose() runs the drain again — by which time the queue has usually been
419
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
420
+ // attempt at most another bounded wait and a rejection, never a stranded
421
+ // promise; the process-exit teardown still reclaims the context.
422
+ const drainError = new Error(
423
+ 'the wasm environment still reports ' +
424
+ queued +
425
+ ' queued settlement(s) after ' +
426
+ limit +
427
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
428
+ )
429
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
430
+ throw drainError
431
+ })().then(
432
+ (value) => {
433
+ // Set only when the wait actually finished AND the queue was seen empty
434
+ // (or is unobservable): a drain that timed out with settlements still
435
+ // queued rejects above and must stay repeatable.
436
+ __emnapiWasmEnvCleanupDrained = true
437
+ __emnapiWasmEnvCleanupDrainPromise = undefined
438
+ return value
439
+ },
440
+ (error) => {
441
+ __emnapiWasmEnvCleanupDrainPromise = undefined
442
+ throw error
443
+ },
444
+ )
445
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
446
+ return drainPromise
447
+ }
448
+
449
+ function __destroyEmnapiContext() {
450
+ if (__emnapiContextDestroyed || __emnapiContext === undefined) {
451
+ __emnapiContextDestroyed = true
452
+ return
453
+ }
454
+ if (__emnapiContextDestroyPromise) {
455
+ return __emnapiContextDestroyPromise
456
+ }
457
+
458
+ __prepareWasmEnvCleanup()
459
+ const result = __emnapiContext.destroy()
460
+ if (!__isThenable(result)) {
461
+ __emnapiContextDestroyed = true
462
+ return
463
+ }
464
+
465
+ const destroyPromise = Promise.resolve(result).then(
466
+ (value) => {
467
+ __emnapiContextDestroyed = true
468
+ return value
469
+ },
470
+ (error) => {
471
+ __emnapiContextDestroyPromise = undefined
472
+ throw error
473
+ },
474
+ )
475
+ __emnapiContextDestroyPromise = destroyPromise
476
+ return destroyPromise
477
+ }
478
+
479
+ /**
480
+ * Holds the event loop open until `work` settles.
481
+ *
482
+ * Nothing else can: the pool workers are deliberately unreferenced so an idle
483
+ * binding cannot keep a process alive, and referencing them again for the
484
+ * termination does not hold either — emnapi unreferences a worker the moment it
485
+ * reports `async-thread-ready`, which for a worker that was still starting
486
+ * lands *after* the termination began. Without a handle of its own, an
487
+ * `await dispose()` with nothing else pending exits the process with its
488
+ * promise unsettled, and everything after the `await` is skipped.
489
+ *
490
+ * The timer is cleared as soon as the work settles, so this never outlives the
491
+ * disposal that asked for it.
492
+ */
493
+ function __keepEventLoopAliveUntil(work) {
494
+ const setTimer = globalThis.setInterval
495
+ const clearTimer = globalThis.clearInterval
496
+ if (typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
497
+ return work
498
+ }
499
+ let timer
500
+ try {
501
+ timer = setTimer(function () {}, 50)
502
+ } catch {
503
+ return work
504
+ }
505
+ const release = function () {
506
+ try {
507
+ clearTimer(timer)
508
+ } catch {}
509
+ }
510
+ return work.then(
511
+ (value) => {
512
+ release()
513
+ return value
514
+ },
515
+ (error) => {
516
+ release()
517
+ throw error
518
+ },
519
+ )
520
+ }
521
+
522
+ // How often to re-read `napi_wasm_async_work_pending` while waiting. The wait
523
+ // ends when the addon reports zero, so this only decides how promptly disposal
524
+ // notices — not how long it waits.
525
+ const __WASI_ASYNC_WORK_POLL_INTERVAL_MS = 1
526
+
527
+ /**
528
+ * Settles this addon's outstanding `napi_async_work` before the teardown that
529
+ * would strand it.
530
+ *
531
+ * `napi_prepare_wasm_env_cleanup` does not cover async work, and nothing about
532
+ * it is observable from JavaScript: the threadless archive resolves
533
+ * `napi_*_async_work` through the `@emnapi/core` plugins, but the threaded one
534
+ * links the C `async_work.c` on the uv threadpool, so there the wasm neither
535
+ * imports nor exports those symbols and the only brackets a loader could watch
536
+ * (`_emnapi_ctx_*_waiting_request_counter`) are shared with threadsafe
537
+ * functions. The addon is the one place both flavors go through, so it answers
538
+ * for both, through the same kind of handshake the settlement drain uses:
539
+ *
540
+ * - `napi_wasm_cancel_pending_async_work()` cancels what no thread has
541
+ * started. Those completion callbacks run with `napi_cancelled`, which
542
+ * napi-rs turns into a promise rejected with an `AbortError`.
543
+ * - `napi_wasm_async_work_pending()` counts what is still owed a completion
544
+ * callback. Work already executing refuses cancellation and stays counted
545
+ * until it finishes normally — which it can, because this runs before the
546
+ * barrier, before `Context.destroy()` and before anything is terminated.
547
+ *
548
+ * Both exports are optional: an addon built against a napi crate that predates
549
+ * them drains nothing and keeps the previous behavior, exactly as the
550
+ * `napi_wasm_env_cleanup_pending` handshake degrades.
551
+ *
552
+ * Returns nothing when there is nothing outstanding, which keeps disposal
553
+ * synchronous in the common case. The promise it returns otherwise never
554
+ * rejects.
555
+ *
556
+ * The wait has no deadline, and that is the point: giving up would destroy the
557
+ * environment with a completion callback still owed, which is the stranding
558
+ * this exists to prevent. A task whose `execute` never returns already keeps an
559
+ * *undisposed* process alive in exactly the same way, so disposal inherits that
560
+ * rather than inventing a bound it cannot honor.
561
+ *
562
+ * Safe to call from inside a completion callback, which is reachable: settling
563
+ * a task runs addon code that can re-enter JavaScript — a setter on the value
564
+ * being handed back, a threadsafe-function callback — and that JavaScript can
565
+ * call `dispose()`. Two things make it terminate rather than wait on itself:
566
+ *
567
+ * - The addon keeps a work registered until its completion callback
568
+ * *finishes*, so the count read here is at least one and this takes the
569
+ * polling path instead of declaring the environment drained and tearing it
570
+ * down from inside the frame that is still settling a promise.
571
+ * - The poll is a timer, so it cannot run until the callback has returned to
572
+ * the host — by which time that work has left the registry. The count the
573
+ * next poll reads is the one taken after the callback finished.
574
+ *
575
+ * `__disposeWasiBinding` hands every caller the same in-flight promise, so the
576
+ * nested call joins this disposal rather than starting a second one.
577
+ */
578
+ function __drainWasiAsyncWork() {
579
+ if (__wasiAsyncWorkDrainPromise !== undefined) {
580
+ return __wasiAsyncWorkDrainPromise
581
+ }
582
+ const exports = __napiInstance?.exports
583
+ const pending = exports?.napi_wasm_async_work_pending
584
+ const cancelPending = exports?.napi_wasm_cancel_pending_async_work
585
+ if (typeof pending !== 'function' || typeof cancelPending !== 'function') {
586
+ return
587
+ }
588
+
589
+ const readPending = () => {
590
+ try {
591
+ return pending()
592
+ } catch (error) {
593
+ // A trap is the only way this call fails: it reads a counter and cannot
594
+ // allocate or call back into JavaScript. A trapped instance can no longer
595
+ // run anything, so its outstanding work is unreachable by definition —
596
+ // there is nothing left to wait for, and refusing to dispose would only
597
+ // keep a dead instance and its stuck counter alive. Best-effort here is
598
+ // the honest answer, and it is what disposal did before this drain
599
+ // existed.
600
+ //
601
+ // Only a trap. Anything else means the export is not what this loader
602
+ // thinks it is, which is a defect worth surfacing rather than disposing
603
+ // over.
604
+ if (error instanceof globalThis.WebAssembly.RuntimeError) {
605
+ return 0
606
+ }
607
+ throw error
608
+ }
609
+ }
610
+
611
+ if (!readPending()) {
612
+ return
613
+ }
614
+ try {
615
+ cancelPending()
616
+ } catch {
617
+ // Cancellation is an optimization: it bounds the wait by the work already
618
+ // executing. Failing it only means waiting for the whole queue instead.
619
+ }
620
+ if (!readPending()) {
621
+ return
622
+ }
623
+
624
+ const drainPromise = __keepEventLoopAliveUntil(
625
+ (async () => {
626
+ while (readPending()) {
627
+ await new Promise((resolve) => {
628
+ __scheduleTimer(resolve, __WASI_ASYNC_WORK_POLL_INTERVAL_MS)
629
+ })
630
+ }
631
+ })(),
632
+ ).then(
633
+ () => {
634
+ __wasiAsyncWorkDrainPromise = undefined
635
+ },
636
+ (error) => {
637
+ // A wait that could not run is not a wait that finished. The only way
638
+ // here is a host whose timers and macrotask primitives all refuse, and
639
+ // the work is still outstanding — reporting success would destroy the
640
+ // environment over it, which is the stranding this exists to prevent.
641
+ // Reject instead: disposal stays retryable, and the context is not
642
+ // destroyed. Clearing the memo first is what makes the retry re-run this.
643
+ __wasiAsyncWorkDrainPromise = undefined
644
+ throw error
645
+ },
646
+ )
647
+ __wasiAsyncWorkDrainPromise = drainPromise
648
+ return drainPromise
649
+ }
650
+
651
+ /**
652
+ * `@emnapi/wasi-threads` counts a worker exit as expected only when its own
653
+ * thread manager performed the termination. A bare `worker.terminate()` reaches
654
+ * the manager's `exit` listener instead, which reports
655
+ * `worker (tid = N) sent an error! ... stopped with exit code 1` and rethrows
656
+ * inside the emit — aborting the `once('exit')` that backs the terminate
657
+ * promise, so disposal never settles and the process dies with an uncaught
658
+ * exception. Mark the termination through the manager first.
659
+ *
660
+ * The manager comes from `__getWasiThreadManager`, not from `__napiModule`:
661
+ * the initialization rollback runs on the one path where instantiation never
662
+ * returned, so `__napiModule` is still undefined there while the workers it
663
+ * spawned are already registered and loaded.
664
+ *
665
+ * Not `terminateAllThreads()`: that one recreates the pool it just shut down.
666
+ */
667
+ function __terminateWasiWorkers() {
668
+ const cleanupErrors = []
669
+ const pending = []
670
+ const threadManager = __getWasiThreadManager()
671
+
672
+ for (const worker of __wasiWorkers) {
673
+ let result
674
+ try {
675
+ if (threadManager) {
676
+ threadManager.terminateWorker(worker)
677
+ // `terminateWorker` leaves behind a reporter that logs every message
678
+ // still queued on the port, which Node flushes on exit. Nothing is
679
+ // listening for those any more.
680
+ worker.onmessage = undefined
681
+ }
682
+ result = worker.terminate()
683
+ } catch (error) {
684
+ cleanupErrors.push(error)
685
+ continue
686
+ }
687
+ if (__isThenable(result)) {
688
+ pending.push(
689
+ Promise.resolve(result).then(
690
+ () => {
691
+ __wasiWorkers.delete(worker)
692
+ },
693
+ (error) => {
694
+ cleanupErrors.push(error)
695
+ },
696
+ ),
697
+ )
698
+ } else {
699
+ __wasiWorkers.delete(worker)
700
+ }
701
+ }
702
+
703
+ const finish = () => {
704
+ if (cleanupErrors.length > 0) {
705
+ throw __createCleanupError(
706
+ cleanupErrors,
707
+ 'Failed to terminate WASI workers',
708
+ )
709
+ }
710
+ }
711
+ return pending.length > 0
712
+ ? __keepEventLoopAliveUntil(Promise.all(pending)).then(finish)
713
+ : finish()
714
+ }
715
+
716
+ function __finishWasiDisposal() {
717
+ const workerResult = __terminateWasiWorkers()
718
+ if (__isThenable(workerResult)) {
719
+ return Promise.resolve(workerResult).then(__completeWasiDisposal)
720
+ }
721
+ return __completeWasiDisposal()
722
+ }
723
+
724
+ function __continueWasiDisposal() {
725
+ const destroyResult = __destroyEmnapiContext()
726
+ if (__isThenable(destroyResult)) {
727
+ return Promise.resolve(destroyResult).then(__finishWasiDisposal)
728
+ }
729
+ return __finishWasiDisposal()
730
+ }
731
+
732
+ function __cleanUpWasmEnvForWasiDisposal() {
733
+ // Run the pre-teardown barrier, then let the settlements it queued actually
734
+ // reach JavaScript, and only then destroy the environment. Doing these two
735
+ // back to back is what strands them.
736
+ __prepareWasmEnvCleanup()
737
+ const drainResult = __drainWasmEnvCleanup()
738
+ if (__isThenable(drainResult)) {
739
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
740
+ }
741
+ return __continueWasiDisposal()
742
+ }
743
+
744
+ function __startWasiDisposal() {
745
+ // Outstanding `napi_async_work` goes first, while the environment is still
746
+ // completely live: the completion callbacks run addon code, and everything
747
+ // after this point takes that away from them — the barrier shuts the async
748
+ // runtime down, `Context.destroy()` stops JavaScript calls, and terminating
749
+ // the pool threads removes what would have reported the work finished.
750
+ const asyncWorkResult = __drainWasiAsyncWork()
751
+ if (__isThenable(asyncWorkResult)) {
752
+ return Promise.resolve(asyncWorkResult).then(
753
+ __cleanUpWasmEnvForWasiDisposal,
754
+ )
755
+ }
756
+ return __cleanUpWasmEnvForWasiDisposal()
757
+ }
758
+
759
+ /**
760
+ * Disposes this generated WASI binding.
761
+ *
762
+ * Access this function with:
763
+ * binding[Symbol.for('napi.rs.wasi.dispose')]()
764
+ */
765
+ function __disposeWasiBinding() {
766
+ if (__wasiDisposePromise) {
767
+ return __wasiDisposePromise
768
+ }
769
+ if (__wasiDisposed) {
770
+ return Promise.resolve()
771
+ }
772
+
773
+ let resolveDispose
774
+ let rejectDispose
775
+ const disposePromise = new Promise((resolve, reject) => {
776
+ resolveDispose = resolve
777
+ rejectDispose = reject
778
+ })
779
+ __wasiDisposePromise = disposePromise
780
+
781
+ let result
782
+ try {
783
+ result = __startWasiDisposal()
784
+ } catch (error) {
785
+ __wasiDisposePromise = undefined
786
+ rejectDispose(error)
787
+ return disposePromise
788
+ }
789
+
790
+ Promise.resolve(result).then(
791
+ (value) => {
792
+ __wasiDisposed = true
793
+ resolveDispose(value)
794
+ },
795
+ (error) => {
796
+ __wasiDisposePromise = undefined
797
+ rejectDispose(error)
798
+ },
799
+ )
800
+ return disposePromise
801
+ }
802
+
803
+ function __publishWasiDispose(exports) {
804
+ Object.defineProperty(exports, __wasiDisposeSymbol, {
805
+ configurable: false,
806
+ enumerable: false,
807
+ value: __disposeWasiBinding,
808
+ writable: false,
809
+ })
810
+ }
811
+
812
+ function __finishWasiInitializationRollback(cleanupErrors) {
813
+ let workerResult
814
+ try {
815
+ workerResult = __terminateWasiWorkers()
816
+ } catch (cleanupError) {
817
+ cleanupErrors.push(cleanupError)
818
+ return cleanupErrors
819
+ }
820
+ if (__isThenable(workerResult)) {
821
+ return Promise.resolve(workerResult)
822
+ .catch((cleanupError) => {
823
+ cleanupErrors.push(cleanupError)
824
+ })
825
+ .then(() => cleanupErrors)
826
+ }
827
+ return cleanupErrors
828
+ }
829
+
830
+ function __destroyContextForWasiRollback(cleanupErrors) {
831
+ let destroyResult
832
+ try {
833
+ destroyResult = __destroyEmnapiContext()
834
+ } catch (cleanupError) {
835
+ cleanupErrors.push(cleanupError)
836
+ return __finishWasiInitializationRollback(cleanupErrors)
837
+ }
838
+ if (__isThenable(destroyResult)) {
839
+ return Promise.resolve(destroyResult)
840
+ .catch((cleanupError) => {
841
+ cleanupErrors.push(cleanupError)
842
+ })
843
+ .then(() => __finishWasiInitializationRollback(cleanupErrors))
844
+ }
845
+ return __finishWasiInitializationRollback(cleanupErrors)
846
+ }
847
+
848
+ /**
849
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
850
+ * hands it to whatever this flavor has that can still reclaim it.
851
+ */
852
+ function __retainFailedWasiRollback(cleanupErrors) {
853
+ try {
854
+ __retainWasiRollbackForRetry()
855
+ } catch (cleanupError) {
856
+ cleanupErrors.push(cleanupError)
857
+ }
858
+ return cleanupErrors
859
+ }
860
+
861
+ /**
862
+ * Initialization can fail *after* registration has already run, and registration
863
+ * runs with a live environment: a module-init hook can start async work and then
864
+ * return an error, and the promise it created may already have escaped into
865
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
866
+ * path needs the same drain the ordinary disposal does — destroying without
867
+ * yielding discards the queue with a null env and strands the promise.
868
+ *
869
+ * Stays synchronous when nothing is queued, which covers every failure before
870
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
871
+ *
872
+ * A barrier or drain that did *not* finish stops the rollback short of
873
+ * destroying, which is what `dispose()` already does — a rejected drain there
874
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
875
+ * two trades, and not because of what it saves:
876
+ *
877
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
878
+ * threadsafe function's cleanup hook, which drains the queue with a null env
879
+ * and discards it, so a promise that already escaped into JavaScript hangs
880
+ * forever with nothing left that could ever settle it.
881
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
882
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
883
+ * which this module's scope holds either way. What stopping short retains is
884
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
885
+ * - Retry is not theoretical. A rollback that records a cleanup error is
886
+ * already kept in the process-wide registry above, so re-`require()`ing this
887
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
888
+ * means the replay drains again rather than skipping it. Destroying first is
889
+ * what makes that retained record useless.
890
+ *
891
+ * The residual cost is honest: the CJS flavor hands the context to its
892
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
893
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
894
+ * throws while evaluating is permanently errored, so re-importing rethrows
895
+ * without re-running this file — and there the context stays until the realm
896
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
897
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
898
+ */
899
+ function __rollbackWasiInitialization() {
900
+ // The environment teardown this rollback performs, kept nested so it cannot
901
+ // be reached without the async-work drain below running first.
902
+ function __rollbackWasmEnvForWasiInitialization() {
903
+ const cleanupErrors = []
904
+ let drainResult
905
+ let settlementsUnreached = false
906
+ try {
907
+ __prepareWasmEnvCleanup()
908
+ drainResult = __drainWasmEnvCleanup()
909
+ } catch (cleanupError) {
910
+ cleanupErrors.push(cleanupError)
911
+ settlementsUnreached = true
912
+ }
913
+ if (__isThenable(drainResult)) {
914
+ return Promise.resolve(drainResult).then(
915
+ () => __destroyContextForWasiRollback(cleanupErrors),
916
+ (cleanupError) => {
917
+ cleanupErrors.push(cleanupError)
918
+ return __retainFailedWasiRollback(cleanupErrors)
919
+ },
920
+ )
921
+ }
922
+ if (settlementsUnreached) {
923
+ return __retainFailedWasiRollback(cleanupErrors)
924
+ }
925
+ return __destroyContextForWasiRollback(cleanupErrors)
926
+ }
927
+
928
+ // Same reason as `__startWasiDisposal`: a module-init hook can start async
929
+ // work before the load goes on to fail, and this rollback tears down exactly
930
+ // what those completions need. Settle them while everything is still live,
931
+ // before the barrier and the teardown above take that away.
932
+ //
933
+ // A drain that could not finish leaves async work possibly outstanding, and
934
+ // destroying the context over it would strand exactly what this rollback is
935
+ // there to settle. Stop short and retain instead — the same trade
936
+ // `__rollbackWasmEnvForWasiInitialization` makes for the settlement drain, so
937
+ // the context stays reclaimable by a retry or by this flavor's own
938
+ // last-resort teardown.
939
+ const __retainAfterAsyncWorkDrainFailure = (cleanupError) =>
940
+ __retainFailedWasiRollback([cleanupError])
941
+ let asyncWorkResult
942
+ try {
943
+ asyncWorkResult = __drainWasiAsyncWork()
944
+ } catch (cleanupError) {
945
+ return __retainAfterAsyncWorkDrainFailure(cleanupError)
946
+ }
947
+ if (__isThenable(asyncWorkResult)) {
948
+ return Promise.resolve(asyncWorkResult).then(
949
+ __rollbackWasmEnvForWasiInitialization,
950
+ __retainAfterAsyncWorkDrainFailure,
951
+ )
952
+ }
953
+ return __rollbackWasmEnvForWasiInitialization()
954
+ }
955
+
956
+ const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
957
+ const __wasiRollbackRegistryKey =
958
+ typeof __filename === 'string' ? __filename : __wasmFilePath
959
+
960
+ function __getWasiRollbackRegistry() {
961
+ const existing = process[__wasiRollbackRegistrySymbol]
962
+ if (existing !== undefined) {
963
+ if (!(existing instanceof Map)) {
964
+ throw new TypeError(
965
+ 'The process-wide NAPI-RS WASI rollback registry is invalid',
966
+ )
967
+ }
968
+ return existing
969
+ }
970
+ const registry = new Map()
971
+ Object.defineProperty(process, __wasiRollbackRegistrySymbol, {
972
+ configurable: false,
973
+ enumerable: false,
974
+ value: registry,
975
+ writable: false,
976
+ })
977
+ return registry
978
+ }
979
+
980
+ const __wasiRollbackRegistry = __getWasiRollbackRegistry()
981
+
982
+ function __completeWasiInitializationRollback(record, cleanupErrors) {
983
+ try {
984
+ if (cleanupErrors.length === 0) {
985
+ if (
986
+ __wasiRollbackRegistry.get(__wasiRollbackRegistryKey) === record
987
+ ) {
988
+ __wasiRollbackRegistry.delete(__wasiRollbackRegistryKey)
989
+ }
990
+ return
991
+ }
992
+ record.error = __attachCleanupErrors(record.error, cleanupErrors)
993
+ } catch (cleanupError) {
994
+ try {
995
+ record.error = __createCleanupError(
996
+ [record.error, cleanupError],
997
+ 'WASI binding initialization and cleanup failed',
998
+ )
999
+ } catch {}
1000
+ } finally {
1001
+ record.active = false
1002
+ record.promise = undefined
1003
+ }
1004
+ }
1005
+
1006
+ function __runWasiInitializationRollback(record) {
1007
+ if (record.active) {
1008
+ return
1009
+ }
1010
+ record.active = true
1011
+
1012
+ let rollbackResult
1013
+ try {
1014
+ rollbackResult = record.rollback()
1015
+ } catch (cleanupError) {
1016
+ __completeWasiInitializationRollback(record, [cleanupError])
1017
+ return
1018
+ }
1019
+
1020
+ if (!__isThenable(rollbackResult)) {
1021
+ __completeWasiInitializationRollback(record, rollbackResult)
1022
+ return
1023
+ }
1024
+
1025
+ record.promise = Promise.resolve(rollbackResult).then(
1026
+ (cleanupErrors) => {
1027
+ __completeWasiInitializationRollback(record, cleanupErrors)
1028
+ },
1029
+ (cleanupError) => {
1030
+ __completeWasiInitializationRollback(record, [cleanupError])
1031
+ },
1032
+ )
1033
+ }
1034
+
1035
+ const __pendingWasiRollback = __wasiRollbackRegistry.get(
1036
+ __wasiRollbackRegistryKey,
1037
+ )
1038
+ if (__pendingWasiRollback !== undefined) {
1039
+ __runWasiInitializationRollback(__pendingWasiRollback)
1040
+ throw __pendingWasiRollback.error
1041
+ }
1042
+
1043
+ let __wasiModule
1044
+ let __napiModule
1045
+ let __wasiExitListenerRegistered = false
1046
+
1047
+ function __removeWasiExitListener() {
1048
+ if (
1049
+ __wasiExitListenerRegistered &&
1050
+ typeof process.removeListener === 'function'
1051
+ ) {
1052
+ process.removeListener('exit', __disposeWasiBindingAtExit)
1053
+ }
1054
+ __wasiExitListenerRegistered = false
1055
+ }
1056
+
1057
+ function __disposeWasiBindingAtExit() {
1058
+ __wasiExitListenerRegistered = false
1059
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
1060
+ // settlements the way __startWasiDisposal does — the process is leaving and
1061
+ // those promises have no observer left anyway. Run the synchronous teardown
1062
+ // directly. Every step is idempotent, which also makes this the synchronous
1063
+ // finish for a disposal that is still waiting for its drain.
1064
+ try {
1065
+ __destroyEmnapiContext()
1066
+ } catch {}
1067
+ try {
1068
+ const workerResult = __terminateWasiWorkers()
1069
+ if (__isThenable(workerResult)) {
1070
+ void Promise.resolve(workerResult).catch(() => {})
1071
+ }
1072
+ } catch {}
1073
+ }
1074
+
1075
+ function __registerWasiExitListener() {
1076
+ if (
1077
+ !__wasiExitListenerRegistered &&
1078
+ typeof process.once === 'function'
1079
+ ) {
1080
+ process.once('exit', __disposeWasiBindingAtExit)
1081
+ __wasiExitListenerRegistered = true
1082
+ }
1083
+ }
1084
+
1085
+ __completeWasiDisposal = __removeWasiExitListener
1086
+ // A rollback that could not reach the queued settlements keeps the context so
1087
+ // the registry replay above can retry it. Nothing forces that replay to happen,
1088
+ // so hand the context to the same synchronous teardown a successful load uses:
1089
+ // a process that exits without ever retrying still runs the cleanup hooks. The
1090
+ // handler cannot yield, so it does not settle anything — but by then the process
1091
+ // is leaving and those promises have no observer left anyway.
1092
+ __retainWasiRollbackForRetry = __registerWasiExitListener
1093
+
1094
+ function __captureEmnapiAutoDestroyListener() {
1095
+ if (
1096
+ typeof process.prependListener !== 'function' ||
1097
+ typeof process.removeListener !== 'function'
1098
+ ) {
1099
+ return
1100
+ }
1101
+ let __autoDestroyListener
1102
+ const __captureListener = (__event, __listener) => {
1103
+ if (__event === 'beforeExit' && __autoDestroyListener === undefined) {
1104
+ __autoDestroyListener = __listener
1105
+ }
1106
+ }
1107
+ try {
1108
+ // Run before existing newListener hooks so a hook that registers its own
1109
+ // beforeExit listener cannot be mistaken for emnapi's registration.
1110
+ process.prependListener('newListener', __captureListener)
1111
+ } catch {
1112
+ return
1113
+ }
1114
+ return () => {
1115
+ try {
1116
+ process.removeListener('newListener', __captureListener)
1117
+ } catch {}
1118
+ if (__autoDestroyListener !== undefined) {
1119
+ try {
1120
+ process.removeListener('beforeExit', __autoDestroyListener)
1121
+ } catch {}
1122
+ }
1123
+ }
1124
+ }
1125
+
1126
+ try {
1127
+ const __finishAutoDestroyCapture = __captureEmnapiAutoDestroyListener()
1128
+ try {
1129
+ __emnapiContext = __wrapEmnapiContextDestroyForSettlement(
1130
+ __emnapiCreateContext({ autoDestroy: false }),
1131
+ __prepareWasmEnvCleanup,
1132
+ __isPreparingWasmEnvCleanup,
1133
+ )
1134
+ // emnapi 2.x still registers an unconditional once-listener for
1135
+ // beforeExit that auto-destroys the context, and suppressDestroy() only
1136
+ // neutralizes its callback without removing it. This loader owns cleanup
1137
+ // through its 'exit' listener, so emnapi's listener is captured and
1138
+ // removed; suppressDestroy() remains the safety net when removal fails.
1139
+ __emnapiContext.suppressDestroy()
1140
+ } finally {
1141
+ // Remove only the exact emnapi callback captured above.
1142
+ __finishAutoDestroyCapture?.()
1143
+ }
1144
+
1145
+ ;({
1146
+ instance: __napiInstance,
1147
+ module: __wasiModule,
1148
+ napiModule: __napiModule,
1149
+ } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
1150
+ context: __emnapiContext,
1151
+ asyncWorkPoolSize: 0,
1152
+ plugins: [
1153
+ __captureWasiThreadManager,
1154
+ __emnapiAsyncWorkPlugin,
1155
+ __emnapiTSFNPlugin,
1156
+ ],
1157
+ wasi: __wasi,
1158
+ overwriteImports(importObject) {
1159
+ importObject.env = {
1160
+ ...importObject.env,
1161
+ ...importObject.napi,
1162
+ ...importObject.emnapi,
1163
+ memory: __wasmMemory,
1164
+ }
1165
+ return importObject
1166
+ },
1167
+ beforeInit({ instance }) {
1168
+ __napiInstance = instance
1169
+ for (const name of Object.keys(instance.exports)) {
1170
+ if (name.startsWith('__napi_register__')) {
1171
+ instance.exports[name]()
1172
+ }
1173
+ }
1174
+ },
1175
+ }))
1176
+ __publishWasiDispose(__napiModule.exports)
1177
+ // The CommonJS tail below aliases `__napiModule.exports`; a named module
1178
+ // export does not travel with it, so carry the marker on the binding itself
1179
+ // too. Three things pin the stamp to exactly this spot:
1180
+ // - inside this `try`, because the guard throws on a
1181
+ // `#[napi(module_exports)]` hook that claimed the name, and only the
1182
+ // catch below tears the environment — context, workers, exit listener —
1183
+ // back down;
1184
+ // - after the async runtime host install, which hands this same object to
1185
+ // addon-provided registration functions that may put anything on it;
1186
+ // - assigning onto the loader's own `module.exports`, which is still the
1187
+ // original object here, so an addon accessor with a refusing setter is
1188
+ // never written through. `cjs-module-lexer` — Node's CJS -> ESM named
1189
+ // export detection — reads the static `module.exports.<name> =` either
1190
+ // way, and the later `module.exports = __napiModule.exports` does not
1191
+ // undo that.
1192
+ module.exports.__napiBindingTarget = __napiStampBindingTarget(__napiModule.exports, __napiBindingTarget)
1193
+ __registerWasiExitListener()
1194
+ } catch (error) {
1195
+ const rollback = {
1196
+ active: false,
1197
+ error,
1198
+ promise: undefined,
1199
+ rollback: __rollbackWasiInitialization,
1200
+ }
1201
+ __wasiRollbackRegistry.set(__wasiRollbackRegistryKey, rollback)
1202
+ __runWasiInitializationRollback(rollback)
1203
+ throw rollback.error
1204
+ }
1205
+ module.exports = __napiModule.exports
1206
+ module.exports.transpileAsync = __napiModule.exports.transpileAsync
1207
+ module.exports.transpileNativeSync = __napiModule.exports.transpileNativeSync
1208
+ module.exports.transpileUtf16Async = __napiModule.exports.transpileUtf16Async
1209
+ module.exports.transpileUtf16Sync = __napiModule.exports.transpileUtf16Sync