@rolldown/binding-wasm32-wasi 1.2.3 → 1.2.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rolldown/binding-wasm32-wasi",
3
- "version": "1.2.3",
3
+ "version": "1.2.5",
4
4
  "main": "rolldown-binding.wasi.cjs",
5
5
  "files": [
6
6
  "rolldown-binding.wasm32-wasi.wasm",
@@ -37,8 +37,8 @@
37
37
  "browser": "rolldown-binding.wasi-browser.js",
38
38
  "type": "module",
39
39
  "dependencies": {
40
- "@napi-rs/wasm-runtime": "~1.2.2",
41
- "@emnapi/core": "2.0.0-alpha.3",
42
- "@emnapi/runtime": "2.0.0-alpha.3"
40
+ "@napi-rs/wasm-runtime": "~1.2.3",
41
+ "@emnapi/core": "2.0.0-alpha.4",
42
+ "@emnapi/runtime": "2.0.0-alpha.4"
43
43
  }
44
44
  }
@@ -38,6 +38,11 @@ const __sharedMemory = new WebAssembly.Memory({
38
38
  maximum: 65536,
39
39
  shared: true,
40
40
  })
41
+ const __asyncWorkPoolSize = 4
42
+ const __workerPoolSize = Math.max(
43
+ 2,
44
+ globalThis.navigator?.hardwareConcurrency ?? 4,
45
+ )
41
46
 
42
47
  let __emnapiContext
43
48
 
@@ -47,9 +52,16 @@ let __napiInstance
47
52
  let __emnapiContextDestroyed = false
48
53
  let __emnapiContextDestroyPromise
49
54
  let __emnapiWasmEnvCleanupPrepared = false
55
+ let __emnapiWasmEnvCleanupRan = false
56
+ let __emnapiWasmEnvCleanupDrained = false
57
+ let __emnapiWasmEnvCleanupDrainPromise
50
58
  let __wasiDisposed = false
51
59
  let __wasiDisposePromise
52
60
  let __completeWasiDisposal = function() {}
61
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
62
+ // that stopped short of destroying the context. See
63
+ // `__rollbackWasiInitialization`.
64
+ let __retainWasiRollbackForRetry = function() {}
53
65
 
54
66
  function __isThenable(value) {
55
67
  return (
@@ -120,10 +132,168 @@ function __prepareWasmEnvCleanup() {
120
132
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
121
133
  if (typeof prepare === 'function') {
122
134
  prepare()
135
+ __emnapiWasmEnvCleanupRan = true
123
136
  }
124
137
  __emnapiWasmEnvCleanupPrepared = true
125
138
  }
126
139
 
140
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
141
+ // on, so the drain turns below interleave with that dispatch instead of racing
142
+ // ahead of it on a faster queue.
143
+ const __scheduleMacrotask = (function () {
144
+ if (typeof setImmediate === 'function') {
145
+ return function (callback) {
146
+ setImmediate(callback)
147
+ }
148
+ }
149
+ const __MessageChannel = globalThis.MessageChannel
150
+ if (typeof __MessageChannel === 'function') {
151
+ return function (callback) {
152
+ const channel = new __MessageChannel()
153
+ channel.port1.onmessage = function () {
154
+ channel.port1.onmessage = null
155
+ try {
156
+ channel.port1.close()
157
+ } catch {}
158
+ try {
159
+ channel.port2.close()
160
+ } catch {}
161
+ callback()
162
+ }
163
+ channel.port2.postMessage(null)
164
+ }
165
+ }
166
+ return function (callback) {
167
+ setTimeout(callback, 0)
168
+ }
169
+ })()
170
+
171
+ // Turns to wait for while the addon still reports queued settlements. Reaching
172
+ // zero is the only success. A counter still nonzero at this bound rejects the
173
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
174
+ // destroying the context over a still-queued settlement — the wait stays
175
+ // bounded either way.
176
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
177
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
178
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
179
+ // call made on this thread (two), plus a margin.
180
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
181
+
182
+ /**
183
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
184
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
185
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
186
+ * macrotask — two coalescing turns later, even for a call made on this very
187
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
188
+ * which drains the queue with a null env and *discards* whatever is still in it.
189
+ *
190
+ * So destroying without yielding first strands exactly the promises the barrier
191
+ * exists to settle. Yield real event-loop turns until the addon reports the
192
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
193
+ * macrotask run.
194
+ *
195
+ * Returns nothing when there is nothing to wait for, which keeps disposal
196
+ * synchronous in the common case.
197
+ *
198
+ * The "already drained" flag is set only once a wait has actually finished.
199
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
200
+ * that throws is enough — and a disposal that rejects stays retryable, so
201
+ * marking the drain complete up front would make the retry skip it and destroy
202
+ * the context with the barrier's settlements still queued.
203
+ *
204
+ * A wait that runs out of turns with the counter still nonzero rejects with
205
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
206
+ * "finished" is indistinguishable from the stranding above, and destroying
207
+ * would discard the very settlement the wait was for. The rejection leaves the
208
+ * flag unset and disposal retryable.
209
+ */
210
+ function __drainWasmEnvCleanup() {
211
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
212
+ return
213
+ }
214
+ if (__emnapiWasmEnvCleanupDrainPromise) {
215
+ return __emnapiWasmEnvCleanupDrainPromise
216
+ }
217
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
218
+ const observable = typeof pending === 'function'
219
+ if (observable) {
220
+ let queued
221
+ try {
222
+ queued = pending()
223
+ } catch {
224
+ __emnapiWasmEnvCleanupDrained = true
225
+ return
226
+ }
227
+ if (!queued) {
228
+ __emnapiWasmEnvCleanupDrained = true
229
+ return
230
+ }
231
+ }
232
+ const limit = observable
233
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
234
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
235
+ const drainPromise = (async () => {
236
+ let queued = 0
237
+ for (let turn = 0; turn < limit; turn++) {
238
+ await new Promise((resolve) => {
239
+ __scheduleMacrotask(resolve)
240
+ })
241
+ if (!observable) {
242
+ continue
243
+ }
244
+ try {
245
+ queued = pending()
246
+ } catch {
247
+ return
248
+ }
249
+ if (!queued) {
250
+ return
251
+ }
252
+ }
253
+ if (!observable) {
254
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
255
+ // contract — there is nothing to consult, so finishing the turns is
256
+ // finishing the drain.
257
+ return
258
+ }
259
+ // The counter is still nonzero after every turn the bound allows. The wait
260
+ // stays bounded — but claiming success here would be indistinguishable from
261
+ // the stranding this drain exists to prevent: disposal would go on to
262
+ // destroy the context, whose cleanup hook discards the still-queued
263
+ // settlement with a null env, and the promise it was for hangs forever.
264
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
265
+ // unset, dispose() (and the rollback) decline to destroy, and a later
266
+ // dispose() runs the drain again — by which time the queue has usually been
267
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
268
+ // attempt at most another bounded wait and a rejection, never a stranded
269
+ // promise; the process-exit teardown still reclaims the context.
270
+ const drainError = new Error(
271
+ 'the wasm environment still reports ' +
272
+ queued +
273
+ ' queued settlement(s) after ' +
274
+ limit +
275
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
276
+ )
277
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
278
+ throw drainError
279
+ })().then(
280
+ (value) => {
281
+ // Set only when the wait actually finished AND the queue was seen empty
282
+ // (or is unobservable): a drain that timed out with settlements still
283
+ // queued rejects above and must stay repeatable.
284
+ __emnapiWasmEnvCleanupDrained = true
285
+ __emnapiWasmEnvCleanupDrainPromise = undefined
286
+ return value
287
+ },
288
+ (error) => {
289
+ __emnapiWasmEnvCleanupDrainPromise = undefined
290
+ throw error
291
+ },
292
+ )
293
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
294
+ return drainPromise
295
+ }
296
+
127
297
  function __destroyEmnapiContext() {
128
298
  if (__emnapiContextDestroyed || __emnapiContext === undefined) {
129
299
  __emnapiContextDestroyed = true
@@ -201,7 +371,7 @@ function __finishWasiDisposal() {
201
371
  return __completeWasiDisposal()
202
372
  }
203
373
 
204
- function __startWasiDisposal() {
374
+ function __continueWasiDisposal() {
205
375
  const destroyResult = __destroyEmnapiContext()
206
376
  if (__isThenable(destroyResult)) {
207
377
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -209,6 +379,18 @@ function __startWasiDisposal() {
209
379
  return __finishWasiDisposal()
210
380
  }
211
381
 
382
+ function __startWasiDisposal() {
383
+ // Run the pre-teardown barrier, then let the settlements it queued actually
384
+ // reach JavaScript, and only then destroy the environment. Doing these two
385
+ // back to back is what strands them.
386
+ __prepareWasmEnvCleanup()
387
+ const drainResult = __drainWasmEnvCleanup()
388
+ if (__isThenable(drainResult)) {
389
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
390
+ }
391
+ return __continueWasiDisposal()
392
+ }
393
+
212
394
  /**
213
395
  * Disposes this generated WASI binding.
214
396
  *
@@ -280,8 +462,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
280
462
  return cleanupErrors
281
463
  }
282
464
 
283
- function __rollbackWasiInitialization() {
284
- const cleanupErrors = []
465
+ function __destroyContextForWasiRollback(cleanupErrors) {
285
466
  let destroyResult
286
467
  try {
287
468
  destroyResult = __destroyEmnapiContext()
@@ -299,6 +480,83 @@ function __rollbackWasiInitialization() {
299
480
  return __finishWasiInitializationRollback(cleanupErrors)
300
481
  }
301
482
 
483
+ /**
484
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
485
+ * hands it to whatever this flavor has that can still reclaim it.
486
+ */
487
+ function __retainFailedWasiRollback(cleanupErrors) {
488
+ try {
489
+ __retainWasiRollbackForRetry()
490
+ } catch (cleanupError) {
491
+ cleanupErrors.push(cleanupError)
492
+ }
493
+ return cleanupErrors
494
+ }
495
+
496
+ /**
497
+ * Initialization can fail *after* registration has already run, and registration
498
+ * runs with a live environment: a module-init hook can start async work and then
499
+ * return an error, and the promise it created may already have escaped into
500
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
501
+ * path needs the same drain the ordinary disposal does — destroying without
502
+ * yielding discards the queue with a null env and strands the promise.
503
+ *
504
+ * Stays synchronous when nothing is queued, which covers every failure before
505
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
506
+ *
507
+ * A barrier or drain that did *not* finish stops the rollback short of
508
+ * destroying, which is what `dispose()` already does — a rejected drain there
509
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
510
+ * two trades, and not because of what it saves:
511
+ *
512
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
513
+ * threadsafe function's cleanup hook, which drains the queue with a null env
514
+ * and discards it, so a promise that already escaped into JavaScript hangs
515
+ * forever with nothing left that could ever settle it.
516
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
517
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
518
+ * which this module's scope holds either way. What stopping short retains is
519
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
520
+ * - Retry is not theoretical. A rollback that records a cleanup error is
521
+ * already kept in the process-wide registry above, so re-`require()`ing this
522
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
523
+ * means the replay drains again rather than skipping it. Destroying first is
524
+ * what makes that retained record useless.
525
+ *
526
+ * The residual cost is honest: the CJS flavor hands the context to its
527
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
528
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
529
+ * throws while evaluating is permanently errored, so re-importing rethrows
530
+ * without re-running this file — and there the context stays until the realm
531
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
532
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
533
+ */
534
+ function __rollbackWasiInitialization() {
535
+ const cleanupErrors = []
536
+ let drainResult
537
+ let settlementsUnreached = false
538
+ try {
539
+ __prepareWasmEnvCleanup()
540
+ drainResult = __drainWasmEnvCleanup()
541
+ } catch (cleanupError) {
542
+ cleanupErrors.push(cleanupError)
543
+ settlementsUnreached = true
544
+ }
545
+ if (__isThenable(drainResult)) {
546
+ return Promise.resolve(drainResult).then(
547
+ () => __destroyContextForWasiRollback(cleanupErrors),
548
+ (cleanupError) => {
549
+ cleanupErrors.push(cleanupError)
550
+ return __retainFailedWasiRollback(cleanupErrors)
551
+ },
552
+ )
553
+ }
554
+ if (settlementsUnreached) {
555
+ return __retainFailedWasiRollback(cleanupErrors)
556
+ }
557
+ return __destroyContextForWasiRollback(cleanupErrors)
558
+ }
559
+
302
560
  let __wasiModule
303
561
  let __napiModule
304
562
 
@@ -312,7 +570,8 @@ try {
312
570
  napiModule: __napiModule,
313
571
  } = await __emnapiInstantiateNapiModule(__wasmFile, {
314
572
  context: __emnapiContext,
315
- asyncWorkPoolSize: 4,
573
+ asyncWorkPoolSize: __asyncWorkPoolSize,
574
+ reuseWorker: { size: __asyncWorkPoolSize + __workerPoolSize },
316
575
  plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
317
576
  wasi: __wasi,
318
577
  onCreateWorker() {
@@ -424,8 +683,10 @@ export const collapseSourcemaps = __napiModule.exports.collapseSourcemaps
424
683
  export const enhancedTransform = __napiModule.exports.enhancedTransform
425
684
  export const enhancedTransformSync = __napiModule.exports.enhancedTransformSync
426
685
  export const FilterTokenKind = __napiModule.exports.FilterTokenKind
686
+ export const getNativeMemoryStats = __napiModule.exports.getNativeMemoryStats
427
687
  export const initTraceSubscriber = __napiModule.exports.initTraceSubscriber
428
688
  export const registerPlugins = __napiModule.exports.registerPlugins
689
+ export const resetNativeMemoryStats = __napiModule.exports.resetNativeMemoryStats
429
690
  export const resolveTsconfig = __napiModule.exports.resolveTsconfig
430
691
  export const shutdownAsyncRuntime = __napiModule.exports.shutdownAsyncRuntime
431
692
  export const startAsyncRuntime = __napiModule.exports.startAsyncRuntime
@@ -1,4 +1,4 @@
1
- // napi-rs-artifact-metadata:{"version":2,"rootEntry":"binding.cjs","exports":["LegalCommentsMode","minify","minifySync","Severity","ParseResult","ExportExportNameKind","ExportImportNameKind","ExportLocalNameKind","ImportNameKind","parse","parseSync","rawTransferSupported","ResolverFactory","EnforceExtension","ModuleType","sync","HelperMode","isolatedDeclaration","isolatedDeclarationSync","moduleRunnerTransform","moduleRunnerTransformSync","transform","transformSync","BindingBundleEndEventData","BindingBundleErrorEventData","BindingBundler","BindingCallableBuiltinPlugin","BindingChunkingContext","BindingDecodedMap","BindingDevEngine","BindingLoadPluginContext","BindingMagicString","BindingModuleInfo","BindingNormalizedOptions","BindingOutputAsset","BindingOutputChunk","BindingPluginContext","BindingRenderedChunk","BindingRenderedChunkMeta","BindingRenderedModule","BindingSourceMap","BindingTransformPluginContext","BindingWatcher","BindingWatcherBundler","BindingWatcherChangeData","BindingWatcherEvent","ParallelJsPluginRegistry","TraceSubscriberGuard","TsconfigCache","BindingAttachDebugInfo","BindingBuiltinPluginName","BindingChunkModuleOrderBy","BindingErrorStage","BindingLogLevel","BindingPluginOrder","BindingPropertyReadSideEffects","BindingPropertyWriteSideEffects","BindingRebuildStrategy","collapseSourcemaps","enhancedTransform","enhancedTransformSync","FilterTokenKind","initTraceSubscriber","registerPlugins","resolveTsconfig","shutdownAsyncRuntime","startAsyncRuntime"],"managedRootEntries":["browser.js","binding.cjs","rolldown-binding.wasm","rolldown-binding.debug.wasm"]}
1
+ // napi-rs-artifact-metadata:{"version":2,"rootEntry":"binding.cjs","exports":["LegalCommentsMode","minify","minifySync","Severity","ParseResult","ExportExportNameKind","ExportImportNameKind","ExportLocalNameKind","ImportNameKind","parse","parseSync","rawTransferSupported","ResolverFactory","EnforceExtension","ModuleType","sync","HelperMode","isolatedDeclaration","isolatedDeclarationSync","moduleRunnerTransform","moduleRunnerTransformSync","transform","transformSync","BindingBundleEndEventData","BindingBundleErrorEventData","BindingBundler","BindingCallableBuiltinPlugin","BindingChunkingContext","BindingDecodedMap","BindingDevEngine","BindingLoadPluginContext","BindingMagicString","BindingModuleInfo","BindingNormalizedOptions","BindingOutputAsset","BindingOutputChunk","BindingPluginContext","BindingRenderedChunk","BindingRenderedChunkMeta","BindingRenderedModule","BindingSourceMap","BindingTransformPluginContext","BindingWatcher","BindingWatcherBundler","BindingWatcherChangeData","BindingWatcherEvent","ParallelJsPluginRegistry","TraceSubscriberGuard","TsconfigCache","BindingAttachDebugInfo","BindingBuiltinPluginName","BindingChunkModuleOrderBy","BindingErrorStage","BindingLogLevel","BindingPluginOrder","BindingPropertyReadSideEffects","BindingPropertyWriteSideEffects","BindingRebuildStrategy","collapseSourcemaps","enhancedTransform","enhancedTransformSync","FilterTokenKind","getNativeMemoryStats","initTraceSubscriber","registerPlugins","resetNativeMemoryStats","resolveTsconfig","shutdownAsyncRuntime","startAsyncRuntime"],"managedRootEntries":["browser.js","binding.cjs","rolldown-binding.wasm","rolldown-binding.debug.wasm"]}
2
2
  /* eslint-disable */
3
3
  /* prettier-ignore */
4
4
 
@@ -150,9 +150,16 @@ let __napiInstance
150
150
  let __emnapiContextDestroyed = false
151
151
  let __emnapiContextDestroyPromise
152
152
  let __emnapiWasmEnvCleanupPrepared = false
153
+ let __emnapiWasmEnvCleanupRan = false
154
+ let __emnapiWasmEnvCleanupDrained = false
155
+ let __emnapiWasmEnvCleanupDrainPromise
153
156
  let __wasiDisposed = false
154
157
  let __wasiDisposePromise
155
158
  let __completeWasiDisposal = function() {}
159
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
160
+ // that stopped short of destroying the context. See
161
+ // `__rollbackWasiInitialization`.
162
+ let __retainWasiRollbackForRetry = function() {}
156
163
 
157
164
  function __isThenable(value) {
158
165
  return (
@@ -223,10 +230,168 @@ function __prepareWasmEnvCleanup() {
223
230
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
224
231
  if (typeof prepare === 'function') {
225
232
  prepare()
233
+ __emnapiWasmEnvCleanupRan = true
226
234
  }
227
235
  __emnapiWasmEnvCleanupPrepared = true
228
236
  }
229
237
 
238
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
239
+ // on, so the drain turns below interleave with that dispatch instead of racing
240
+ // ahead of it on a faster queue.
241
+ const __scheduleMacrotask = (function () {
242
+ if (typeof setImmediate === 'function') {
243
+ return function (callback) {
244
+ setImmediate(callback)
245
+ }
246
+ }
247
+ const __MessageChannel = globalThis.MessageChannel
248
+ if (typeof __MessageChannel === 'function') {
249
+ return function (callback) {
250
+ const channel = new __MessageChannel()
251
+ channel.port1.onmessage = function () {
252
+ channel.port1.onmessage = null
253
+ try {
254
+ channel.port1.close()
255
+ } catch {}
256
+ try {
257
+ channel.port2.close()
258
+ } catch {}
259
+ callback()
260
+ }
261
+ channel.port2.postMessage(null)
262
+ }
263
+ }
264
+ return function (callback) {
265
+ setTimeout(callback, 0)
266
+ }
267
+ })()
268
+
269
+ // Turns to wait for while the addon still reports queued settlements. Reaching
270
+ // zero is the only success. A counter still nonzero at this bound rejects the
271
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
272
+ // destroying the context over a still-queued settlement — the wait stays
273
+ // bounded either way.
274
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
275
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
276
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
277
+ // call made on this thread (two), plus a margin.
278
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
279
+
280
+ /**
281
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
282
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
283
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
284
+ * macrotask — two coalescing turns later, even for a call made on this very
285
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
286
+ * which drains the queue with a null env and *discards* whatever is still in it.
287
+ *
288
+ * So destroying without yielding first strands exactly the promises the barrier
289
+ * exists to settle. Yield real event-loop turns until the addon reports the
290
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
291
+ * macrotask run.
292
+ *
293
+ * Returns nothing when there is nothing to wait for, which keeps disposal
294
+ * synchronous in the common case.
295
+ *
296
+ * The "already drained" flag is set only once a wait has actually finished.
297
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
298
+ * that throws is enough — and a disposal that rejects stays retryable, so
299
+ * marking the drain complete up front would make the retry skip it and destroy
300
+ * the context with the barrier's settlements still queued.
301
+ *
302
+ * A wait that runs out of turns with the counter still nonzero rejects with
303
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
304
+ * "finished" is indistinguishable from the stranding above, and destroying
305
+ * would discard the very settlement the wait was for. The rejection leaves the
306
+ * flag unset and disposal retryable.
307
+ */
308
+ function __drainWasmEnvCleanup() {
309
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
310
+ return
311
+ }
312
+ if (__emnapiWasmEnvCleanupDrainPromise) {
313
+ return __emnapiWasmEnvCleanupDrainPromise
314
+ }
315
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
316
+ const observable = typeof pending === 'function'
317
+ if (observable) {
318
+ let queued
319
+ try {
320
+ queued = pending()
321
+ } catch {
322
+ __emnapiWasmEnvCleanupDrained = true
323
+ return
324
+ }
325
+ if (!queued) {
326
+ __emnapiWasmEnvCleanupDrained = true
327
+ return
328
+ }
329
+ }
330
+ const limit = observable
331
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
332
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
333
+ const drainPromise = (async () => {
334
+ let queued = 0
335
+ for (let turn = 0; turn < limit; turn++) {
336
+ await new Promise((resolve) => {
337
+ __scheduleMacrotask(resolve)
338
+ })
339
+ if (!observable) {
340
+ continue
341
+ }
342
+ try {
343
+ queued = pending()
344
+ } catch {
345
+ return
346
+ }
347
+ if (!queued) {
348
+ return
349
+ }
350
+ }
351
+ if (!observable) {
352
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
353
+ // contract — there is nothing to consult, so finishing the turns is
354
+ // finishing the drain.
355
+ return
356
+ }
357
+ // The counter is still nonzero after every turn the bound allows. The wait
358
+ // stays bounded — but claiming success here would be indistinguishable from
359
+ // the stranding this drain exists to prevent: disposal would go on to
360
+ // destroy the context, whose cleanup hook discards the still-queued
361
+ // settlement with a null env, and the promise it was for hangs forever.
362
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
363
+ // unset, dispose() (and the rollback) decline to destroy, and a later
364
+ // dispose() runs the drain again — by which time the queue has usually been
365
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
366
+ // attempt at most another bounded wait and a rejection, never a stranded
367
+ // promise; the process-exit teardown still reclaims the context.
368
+ const drainError = new Error(
369
+ 'the wasm environment still reports ' +
370
+ queued +
371
+ ' queued settlement(s) after ' +
372
+ limit +
373
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
374
+ )
375
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
376
+ throw drainError
377
+ })().then(
378
+ (value) => {
379
+ // Set only when the wait actually finished AND the queue was seen empty
380
+ // (or is unobservable): a drain that timed out with settlements still
381
+ // queued rejects above and must stay repeatable.
382
+ __emnapiWasmEnvCleanupDrained = true
383
+ __emnapiWasmEnvCleanupDrainPromise = undefined
384
+ return value
385
+ },
386
+ (error) => {
387
+ __emnapiWasmEnvCleanupDrainPromise = undefined
388
+ throw error
389
+ },
390
+ )
391
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
392
+ return drainPromise
393
+ }
394
+
230
395
  function __destroyEmnapiContext() {
231
396
  if (__emnapiContextDestroyed || __emnapiContext === undefined) {
232
397
  __emnapiContextDestroyed = true
@@ -304,7 +469,7 @@ function __finishWasiDisposal() {
304
469
  return __completeWasiDisposal()
305
470
  }
306
471
 
307
- function __startWasiDisposal() {
472
+ function __continueWasiDisposal() {
308
473
  const destroyResult = __destroyEmnapiContext()
309
474
  if (__isThenable(destroyResult)) {
310
475
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -312,6 +477,18 @@ function __startWasiDisposal() {
312
477
  return __finishWasiDisposal()
313
478
  }
314
479
 
480
+ function __startWasiDisposal() {
481
+ // Run the pre-teardown barrier, then let the settlements it queued actually
482
+ // reach JavaScript, and only then destroy the environment. Doing these two
483
+ // back to back is what strands them.
484
+ __prepareWasmEnvCleanup()
485
+ const drainResult = __drainWasmEnvCleanup()
486
+ if (__isThenable(drainResult)) {
487
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
488
+ }
489
+ return __continueWasiDisposal()
490
+ }
491
+
315
492
  /**
316
493
  * Disposes this generated WASI binding.
317
494
  *
@@ -383,8 +560,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
383
560
  return cleanupErrors
384
561
  }
385
562
 
386
- function __rollbackWasiInitialization() {
387
- const cleanupErrors = []
563
+ function __destroyContextForWasiRollback(cleanupErrors) {
388
564
  let destroyResult
389
565
  try {
390
566
  destroyResult = __destroyEmnapiContext()
@@ -402,6 +578,83 @@ function __rollbackWasiInitialization() {
402
578
  return __finishWasiInitializationRollback(cleanupErrors)
403
579
  }
404
580
 
581
+ /**
582
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
583
+ * hands it to whatever this flavor has that can still reclaim it.
584
+ */
585
+ function __retainFailedWasiRollback(cleanupErrors) {
586
+ try {
587
+ __retainWasiRollbackForRetry()
588
+ } catch (cleanupError) {
589
+ cleanupErrors.push(cleanupError)
590
+ }
591
+ return cleanupErrors
592
+ }
593
+
594
+ /**
595
+ * Initialization can fail *after* registration has already run, and registration
596
+ * runs with a live environment: a module-init hook can start async work and then
597
+ * return an error, and the promise it created may already have escaped into
598
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
599
+ * path needs the same drain the ordinary disposal does — destroying without
600
+ * yielding discards the queue with a null env and strands the promise.
601
+ *
602
+ * Stays synchronous when nothing is queued, which covers every failure before
603
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
604
+ *
605
+ * A barrier or drain that did *not* finish stops the rollback short of
606
+ * destroying, which is what `dispose()` already does — a rejected drain there
607
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
608
+ * two trades, and not because of what it saves:
609
+ *
610
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
611
+ * threadsafe function's cleanup hook, which drains the queue with a null env
612
+ * and discards it, so a promise that already escaped into JavaScript hangs
613
+ * forever with nothing left that could ever settle it.
614
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
615
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
616
+ * which this module's scope holds either way. What stopping short retains is
617
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
618
+ * - Retry is not theoretical. A rollback that records a cleanup error is
619
+ * already kept in the process-wide registry above, so re-`require()`ing this
620
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
621
+ * means the replay drains again rather than skipping it. Destroying first is
622
+ * what makes that retained record useless.
623
+ *
624
+ * The residual cost is honest: the CJS flavor hands the context to its
625
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
626
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
627
+ * throws while evaluating is permanently errored, so re-importing rethrows
628
+ * without re-running this file — and there the context stays until the realm
629
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
630
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
631
+ */
632
+ function __rollbackWasiInitialization() {
633
+ const cleanupErrors = []
634
+ let drainResult
635
+ let settlementsUnreached = false
636
+ try {
637
+ __prepareWasmEnvCleanup()
638
+ drainResult = __drainWasmEnvCleanup()
639
+ } catch (cleanupError) {
640
+ cleanupErrors.push(cleanupError)
641
+ settlementsUnreached = true
642
+ }
643
+ if (__isThenable(drainResult)) {
644
+ return Promise.resolve(drainResult).then(
645
+ () => __destroyContextForWasiRollback(cleanupErrors),
646
+ (cleanupError) => {
647
+ cleanupErrors.push(cleanupError)
648
+ return __retainFailedWasiRollback(cleanupErrors)
649
+ },
650
+ )
651
+ }
652
+ if (settlementsUnreached) {
653
+ return __retainFailedWasiRollback(cleanupErrors)
654
+ }
655
+ return __destroyContextForWasiRollback(cleanupErrors)
656
+ }
657
+
405
658
  const __wasiRollbackRegistrySymbol = Symbol.for('napi.rs.wasi.rollback.registry.v1')
406
659
  const __wasiRollbackRegistryKey =
407
660
  typeof __filename === 'string' ? __filename : __wasmFilePath
@@ -505,10 +758,18 @@ function __removeWasiExitListener() {
505
758
 
506
759
  function __disposeWasiBindingAtExit() {
507
760
  __wasiExitListenerRegistered = false
761
+ // An 'exit' handler cannot yield, so it cannot wait for queued promise
762
+ // settlements the way __startWasiDisposal does — the process is leaving and
763
+ // those promises have no observer left anyway. Run the synchronous teardown
764
+ // directly. Every step is idempotent, which also makes this the synchronous
765
+ // finish for a disposal that is still waiting for its drain.
508
766
  try {
509
- const result = __disposeWasiBinding()
510
- if (__isThenable(result)) {
511
- void Promise.resolve(result).catch(() => {})
767
+ __destroyEmnapiContext()
768
+ } catch {}
769
+ try {
770
+ const workerResult = __terminateWasiWorkers()
771
+ if (__isThenable(workerResult)) {
772
+ void Promise.resolve(workerResult).catch(() => {})
512
773
  }
513
774
  } catch {}
514
775
  }
@@ -524,6 +785,13 @@ function __registerWasiExitListener() {
524
785
  }
525
786
 
526
787
  __completeWasiDisposal = __removeWasiExitListener
788
+ // A rollback that could not reach the queued settlements keeps the context so
789
+ // the registry replay above can retry it. Nothing forces that replay to happen,
790
+ // so hand the context to the same synchronous teardown a successful load uses:
791
+ // a process that exits without ever retrying still runs the cleanup hooks. The
792
+ // handler cannot yield, so it does not settle anything — but by then the process
793
+ // is leaving and those promises have no observer left anyway.
794
+ __retainWasiRollbackForRetry = __registerWasiExitListener
527
795
 
528
796
  function __captureEmnapiAutoDestroyListener() {
529
797
  if (
@@ -715,8 +983,10 @@ module.exports.collapseSourcemaps = __napiModule.exports.collapseSourcemaps
715
983
  module.exports.enhancedTransform = __napiModule.exports.enhancedTransform
716
984
  module.exports.enhancedTransformSync = __napiModule.exports.enhancedTransformSync
717
985
  module.exports.FilterTokenKind = __napiModule.exports.FilterTokenKind
986
+ module.exports.getNativeMemoryStats = __napiModule.exports.getNativeMemoryStats
718
987
  module.exports.initTraceSubscriber = __napiModule.exports.initTraceSubscriber
719
988
  module.exports.registerPlugins = __napiModule.exports.registerPlugins
989
+ module.exports.resetNativeMemoryStats = __napiModule.exports.resetNativeMemoryStats
720
990
  module.exports.resolveTsconfig = __napiModule.exports.resolveTsconfig
721
991
  module.exports.shutdownAsyncRuntime = __napiModule.exports.shutdownAsyncRuntime
722
992
  module.exports.startAsyncRuntime = __napiModule.exports.startAsyncRuntime
@@ -169,6 +169,38 @@ export interface MangleOptionsKeepNames {
169
169
  class: boolean
170
170
  }
171
171
 
172
+ export interface ManglePropertiesOptions {
173
+ /**
174
+ * JavaScript `RegExp` selecting property names to mangle. The source and flags are compiled
175
+ * with Rust's regex engine. Flags `i`, `m`, `s`, and `u` are supported.
176
+ */
177
+ include: RegExp
178
+ /** JavaScript `RegExp` excluding property names selected by `include`. */
179
+ exclude?: RegExp
180
+ /** Exact names that are neither mangled nor emitted as automatic output names. */
181
+ reserved?: Array<string>
182
+ /**
183
+ * Mangle quoted property occurrences in addition to unquoted occurrences.
184
+ *
185
+ * @default false
186
+ */
187
+ quoted?: boolean
188
+ /**
189
+ * Generate readable `_$name$_`-style output names.
190
+ *
191
+ * @default false
192
+ */
193
+ debug?: boolean
194
+ /**
195
+ * Stable mappings from original names to output names. `false` reserves an original name.
196
+ * Entries that do not match `include`, or that match `exclude`, remain inert but are
197
+ * preserved in the returned `mangleCache`. String targets must be `IdentifierName` values
198
+ * other than `__proto__`, `constructor`, or `prototype`. The original name `__proto__` is
199
+ * always reserved and cannot be used as a cache key.
200
+ */
201
+ cache?: Record<string, string | false>
202
+ }
203
+
172
204
  /**
173
205
  * Minify asynchronously.
174
206
  *
@@ -181,6 +213,12 @@ export interface MinifyOptions {
181
213
  module?: boolean
182
214
  compress?: boolean | CompressOptions
183
215
  mangle?: boolean | MangleOptions
216
+ /**
217
+ * Mangle matching property names independently of identifier mangling. Properties owned by
218
+ * unminified code, imported module namespaces, globals, or host APIs must be excluded or
219
+ * reserved.
220
+ */
221
+ mangleProps?: ManglePropertiesOptions
184
222
  codegen?: boolean | CodegenOptions
185
223
  sourcemap?: boolean
186
224
  }
@@ -194,6 +232,11 @@ export interface MinifyResult {
194
232
  * Only populated when `codegen.legalComments` is `"linked"` or `"external"`.
195
233
  */
196
234
  legalComments: Array<string>
235
+ /**
236
+ * Updated property-name cache sorted by original name. Present when `mangleProps` ran on a
237
+ * parse without errors.
238
+ */
239
+ mangleCache?: Record<string, string | false>
197
240
  }
198
241
 
199
242
  /** Minify synchronously. */
@@ -1969,6 +2012,7 @@ export interface BindingChecksOptions {
1969
2012
  ineffectiveDynamicImport?: boolean
1970
2013
  largeBarrelModules?: boolean
1971
2014
  sourcemapBroken?: boolean
2015
+ namespaceConflict?: boolean
1972
2016
  }
1973
2017
 
1974
2018
  export interface BindingChunkImportMap {
@@ -2564,6 +2608,22 @@ export interface BindingModuleSideEffectsRule {
2564
2608
  external?: boolean
2565
2609
  }
2566
2610
 
2611
+ /**
2612
+ * Counters of the Rust-side tracking allocator. V8 never allocates through
2613
+ * the Rust global allocator, so these numbers exclude the JS heap and GC
2614
+ * noise completely, unlike `process.memoryUsage()`.
2615
+ */
2616
+ export interface BindingNativeMemoryStats {
2617
+ /** Bytes currently allocated and not yet freed, since process start. */
2618
+ liveBytes: number
2619
+ /** Highest `live_bytes` seen since process start or the last reset. */
2620
+ peakBytes: number
2621
+ /** Successful `alloc` calls since the last reset. */
2622
+ allocCount: number
2623
+ /** Successful `realloc` calls since the last reset. */
2624
+ reallocCount: number
2625
+ }
2626
+
2567
2627
  export interface BindingOptimization {
2568
2628
  inlineConst?: boolean | BindingInlineConstConfig
2569
2629
  pifeForModuleWrappers?: boolean
@@ -3061,6 +3121,13 @@ export type FilterTokenKind = 'Id'|
3061
3121
  'QueryKey'|
3062
3122
  'QueryValue';
3063
3123
 
3124
+ /**
3125
+ * Returns the Rust-side allocator counters, or `None` when this binding was
3126
+ * built without the `tracking_allocator` cargo feature (the default —
3127
+ * tracking costs a few atomic operations per allocation).
3128
+ */
3129
+ export declare function getNativeMemoryStats(): BindingNativeMemoryStats | null
3130
+
3064
3131
  export declare function initTraceSubscriber(): TraceSubscriberGuard | null
3065
3132
 
3066
3133
  export interface JsChangedOutputs {
@@ -3123,6 +3190,13 @@ export interface PreRenderedChunk {
3123
3190
 
3124
3191
  export declare function registerPlugins(id: number, plugins: Array<BindingPluginWithIndex>): void
3125
3192
 
3193
+ /**
3194
+ * Starts a new measuring window: the peak restarts from the current live
3195
+ * bytes and the counts restart from zero. No-op when the binding was built
3196
+ * without the `tracking_allocator` cargo feature.
3197
+ */
3198
+ export declare function resetNativeMemoryStats(): void
3199
+
3126
3200
  export declare function resolveTsconfig(filename: string, cache: TsconfigCache | undefined | null, yarnPnp: boolean): BindingTsconfigResult | null
3127
3201
 
3128
3202
  /**
Binary file