@oxc-minify/binding-wasm32-wasi 0.143.0 → 0.145.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.
@@ -2,7 +2,7 @@ import {
2
2
  emnapiAsyncWorkPlugin as __emnapiAsyncWorkPlugin,
3
3
  emnapiTSFNPlugin as __emnapiTSFNPlugin,
4
4
  createOnMessage as __wasmCreateOnMessageForFsProxy,
5
- instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync,
5
+ instantiateNapiModule as __emnapiInstantiateNapiModule,
6
6
  WASI as __WASI,
7
7
  } from '@napi-rs/wasm-runtime'
8
8
  import { createContext as __emnapiCreateContext } from '@emnapi/runtime'
@@ -32,6 +32,11 @@ const __sharedMemory = new WebAssembly.Memory({
32
32
  maximum: 65536,
33
33
  shared: true,
34
34
  })
35
+ const __asyncWorkPoolSize = 4
36
+ const __workerPoolSize = Math.max(
37
+ 2,
38
+ globalThis.navigator?.hardwareConcurrency ?? 4,
39
+ )
35
40
 
36
41
  let __emnapiContext
37
42
 
@@ -41,9 +46,16 @@ let __napiInstance
41
46
  let __emnapiContextDestroyed = false
42
47
  let __emnapiContextDestroyPromise
43
48
  let __emnapiWasmEnvCleanupPrepared = false
49
+ let __emnapiWasmEnvCleanupRan = false
50
+ let __emnapiWasmEnvCleanupDrained = false
51
+ let __emnapiWasmEnvCleanupDrainPromise
44
52
  let __wasiDisposed = false
45
53
  let __wasiDisposePromise
46
54
  let __completeWasiDisposal = function() {}
55
+ // Overridden by loader flavors that have a last-resort reclaim for a rollback
56
+ // that stopped short of destroying the context. See
57
+ // `__rollbackWasiInitialization`.
58
+ let __retainWasiRollbackForRetry = function() {}
47
59
 
48
60
  function __isThenable(value) {
49
61
  return (
@@ -114,10 +126,168 @@ function __prepareWasmEnvCleanup() {
114
126
  const prepare = __napiInstance?.exports?.napi_prepare_wasm_env_cleanup
115
127
  if (typeof prepare === 'function') {
116
128
  prepare()
129
+ __emnapiWasmEnvCleanupRan = true
117
130
  }
118
131
  __emnapiWasmEnvCleanupPrepared = true
119
132
  }
120
133
 
134
+ // Mirror the primitive @emnapi/core schedules its threadsafe-function dispatch
135
+ // on, so the drain turns below interleave with that dispatch instead of racing
136
+ // ahead of it on a faster queue.
137
+ const __scheduleMacrotask = (function () {
138
+ if (typeof setImmediate === 'function') {
139
+ return function (callback) {
140
+ setImmediate(callback)
141
+ }
142
+ }
143
+ const __MessageChannel = globalThis.MessageChannel
144
+ if (typeof __MessageChannel === 'function') {
145
+ return function (callback) {
146
+ const channel = new __MessageChannel()
147
+ channel.port1.onmessage = function () {
148
+ channel.port1.onmessage = null
149
+ try {
150
+ channel.port1.close()
151
+ } catch {}
152
+ try {
153
+ channel.port2.close()
154
+ } catch {}
155
+ callback()
156
+ }
157
+ channel.port2.postMessage(null)
158
+ }
159
+ }
160
+ return function (callback) {
161
+ setTimeout(callback, 0)
162
+ }
163
+ })()
164
+
165
+ // Turns to wait for while the addon still reports queued settlements. Reaching
166
+ // zero is the only success. A counter still nonzero at this bound rejects the
167
+ // disposal as retryable (`ERR_NAPI_WASI_CLEANUP_PENDING`) rather than
168
+ // destroying the context over a still-queued settlement — the wait stays
169
+ // bounded either way.
170
+ const __WASM_ENV_CLEANUP_DRAIN_TURNS = 128
171
+ // Without `napi_wasm_env_cleanup_pending` the queue is not observable. Fall
172
+ // back to the number of turns @emnapi/core needs to coalesce and dispatch a
173
+ // call made on this thread (two), plus a margin.
174
+ const __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS = 4
175
+
176
+ /**
177
+ * `napi_prepare_wasm_env_cleanup` only *queues* the promise settlements of the
178
+ * tasks it cancelled: `napi_call_threadsafe_function` appends to the
179
+ * threadsafe-function queue, and @emnapi/core dispatches that queue from a
180
+ * macrotask — two coalescing turns later, even for a call made on this very
181
+ * thread. `Context.destroy()` then runs the threadsafe function's cleanup hook,
182
+ * which drains the queue with a null env and *discards* whatever is still in it.
183
+ *
184
+ * So destroying without yielding first strands exactly the promises the barrier
185
+ * exists to settle. Yield real event-loop turns until the addon reports the
186
+ * queue empty; microtask checkpoints cannot help, no number of them lets a
187
+ * macrotask run.
188
+ *
189
+ * Returns nothing when there is nothing to wait for, which keeps disposal
190
+ * synchronous in the common case.
191
+ *
192
+ * The "already drained" flag is set only once a wait has actually finished.
193
+ * Scheduling a macrotask can fail — a host-provided or patched `setImmediate`
194
+ * that throws is enough — and a disposal that rejects stays retryable, so
195
+ * marking the drain complete up front would make the retry skip it and destroy
196
+ * the context with the barrier's settlements still queued.
197
+ *
198
+ * A wait that runs out of turns with the counter still nonzero rejects with
199
+ * `ERR_NAPI_WASI_CLEANUP_PENDING` for the same reason: at that point
200
+ * "finished" is indistinguishable from the stranding above, and destroying
201
+ * would discard the very settlement the wait was for. The rejection leaves the
202
+ * flag unset and disposal retryable.
203
+ */
204
+ function __drainWasmEnvCleanup() {
205
+ if (__emnapiWasmEnvCleanupDrained || !__emnapiWasmEnvCleanupRan) {
206
+ return
207
+ }
208
+ if (__emnapiWasmEnvCleanupDrainPromise) {
209
+ return __emnapiWasmEnvCleanupDrainPromise
210
+ }
211
+ const pending = __napiInstance?.exports?.napi_wasm_env_cleanup_pending
212
+ const observable = typeof pending === 'function'
213
+ if (observable) {
214
+ let queued
215
+ try {
216
+ queued = pending()
217
+ } catch {
218
+ __emnapiWasmEnvCleanupDrained = true
219
+ return
220
+ }
221
+ if (!queued) {
222
+ __emnapiWasmEnvCleanupDrained = true
223
+ return
224
+ }
225
+ }
226
+ const limit = observable
227
+ ? __WASM_ENV_CLEANUP_DRAIN_TURNS
228
+ : __WASM_ENV_CLEANUP_BLIND_DRAIN_TURNS
229
+ const drainPromise = (async () => {
230
+ let queued = 0
231
+ for (let turn = 0; turn < limit; turn++) {
232
+ await new Promise((resolve) => {
233
+ __scheduleMacrotask(resolve)
234
+ })
235
+ if (!observable) {
236
+ continue
237
+ }
238
+ try {
239
+ queued = pending()
240
+ } catch {
241
+ return
242
+ }
243
+ if (!queued) {
244
+ return
245
+ }
246
+ }
247
+ if (!observable) {
248
+ // Blind wait: without `napi_wasm_env_cleanup_pending` the bound IS the
249
+ // contract — there is nothing to consult, so finishing the turns is
250
+ // finishing the drain.
251
+ return
252
+ }
253
+ // The counter is still nonzero after every turn the bound allows. The wait
254
+ // stays bounded — but claiming success here would be indistinguishable from
255
+ // the stranding this drain exists to prevent: disposal would go on to
256
+ // destroy the context, whose cleanup hook discards the still-queued
257
+ // settlement with a null env, and the promise it was for hangs forever.
258
+ // Reject instead, as a retryable cleanup failure: the drained flag stays
259
+ // unset, dispose() (and the rollback) decline to destroy, and a later
260
+ // dispose() runs the drain again — by which time the queue has usually been
261
+ // delivered. A counter that is somehow stuck nonzero therefore costs each
262
+ // attempt at most another bounded wait and a rejection, never a stranded
263
+ // promise; the process-exit teardown still reclaims the context.
264
+ const drainError = new Error(
265
+ 'the wasm environment still reports ' +
266
+ queued +
267
+ ' queued settlement(s) after ' +
268
+ limit +
269
+ ' event-loop turns; the context was not destroyed - retry dispose() to wait for the queue again',
270
+ )
271
+ drainError.code = 'ERR_NAPI_WASI_CLEANUP_PENDING'
272
+ throw drainError
273
+ })().then(
274
+ (value) => {
275
+ // Set only when the wait actually finished AND the queue was seen empty
276
+ // (or is unobservable): a drain that timed out with settlements still
277
+ // queued rejects above and must stay repeatable.
278
+ __emnapiWasmEnvCleanupDrained = true
279
+ __emnapiWasmEnvCleanupDrainPromise = undefined
280
+ return value
281
+ },
282
+ (error) => {
283
+ __emnapiWasmEnvCleanupDrainPromise = undefined
284
+ throw error
285
+ },
286
+ )
287
+ __emnapiWasmEnvCleanupDrainPromise = drainPromise
288
+ return drainPromise
289
+ }
290
+
121
291
  function __destroyEmnapiContext() {
122
292
  if (__emnapiContextDestroyed || __emnapiContext === undefined) {
123
293
  __emnapiContextDestroyed = true
@@ -195,7 +365,7 @@ function __finishWasiDisposal() {
195
365
  return __completeWasiDisposal()
196
366
  }
197
367
 
198
- function __startWasiDisposal() {
368
+ function __continueWasiDisposal() {
199
369
  const destroyResult = __destroyEmnapiContext()
200
370
  if (__isThenable(destroyResult)) {
201
371
  return Promise.resolve(destroyResult).then(__finishWasiDisposal)
@@ -203,6 +373,18 @@ function __startWasiDisposal() {
203
373
  return __finishWasiDisposal()
204
374
  }
205
375
 
376
+ function __startWasiDisposal() {
377
+ // Run the pre-teardown barrier, then let the settlements it queued actually
378
+ // reach JavaScript, and only then destroy the environment. Doing these two
379
+ // back to back is what strands them.
380
+ __prepareWasmEnvCleanup()
381
+ const drainResult = __drainWasmEnvCleanup()
382
+ if (__isThenable(drainResult)) {
383
+ return Promise.resolve(drainResult).then(__continueWasiDisposal)
384
+ }
385
+ return __continueWasiDisposal()
386
+ }
387
+
206
388
  /**
207
389
  * Disposes this generated WASI binding.
208
390
  *
@@ -274,8 +456,7 @@ function __finishWasiInitializationRollback(cleanupErrors) {
274
456
  return cleanupErrors
275
457
  }
276
458
 
277
- function __rollbackWasiInitialization() {
278
- const cleanupErrors = []
459
+ function __destroyContextForWasiRollback(cleanupErrors) {
279
460
  let destroyResult
280
461
  try {
281
462
  destroyResult = __destroyEmnapiContext()
@@ -293,6 +474,83 @@ function __rollbackWasiInitialization() {
293
474
  return __finishWasiInitializationRollback(cleanupErrors)
294
475
  }
295
476
 
477
+ /**
478
+ * Leaves a rollback that could not reach the queued settlements undestroyed, and
479
+ * hands it to whatever this flavor has that can still reclaim it.
480
+ */
481
+ function __retainFailedWasiRollback(cleanupErrors) {
482
+ try {
483
+ __retainWasiRollbackForRetry()
484
+ } catch (cleanupError) {
485
+ cleanupErrors.push(cleanupError)
486
+ }
487
+ return cleanupErrors
488
+ }
489
+
490
+ /**
491
+ * Initialization can fail *after* registration has already run, and registration
492
+ * runs with a live environment: a module-init hook can start async work and then
493
+ * return an error, and the promise it created may already have escaped into
494
+ * JavaScript. The barrier cancels that work and *queues* the settlement, so this
495
+ * path needs the same drain the ordinary disposal does — destroying without
496
+ * yielding discards the queue with a null env and strands the promise.
497
+ *
498
+ * Stays synchronous when nothing is queued, which covers every failure before
499
+ * `beforeInit`: there is no instance to run the barrier on, so nothing to drain.
500
+ *
501
+ * A barrier or drain that did *not* finish stops the rollback short of
502
+ * destroying, which is what `dispose()` already does — a rejected drain there
503
+ * never reaches `__continueWasiDisposal`. Destroying anyway is the worse of the
504
+ * two trades, and not because of what it saves:
505
+ *
506
+ * - It cannot deliver the settlements. `Context.destroy()` runs the
507
+ * threadsafe function's cleanup hook, which drains the queue with a null env
508
+ * and discards it, so a promise that already escaped into JavaScript hangs
509
+ * forever with nothing left that could ever settle it.
510
+ * - It saves less than it looks. `Context.destroy()` stops JavaScript calls
511
+ * and runs cleanup hooks; it does not free the wasm instance or its Memory,
512
+ * which this module's scope holds either way. What stopping short retains is
513
+ * the emnapi context's bookkeeping and its un-run cleanup hooks.
514
+ * - Retry is not theoretical. A rollback that records a cleanup error is
515
+ * already kept in the process-wide registry above, so re-`require()`ing this
516
+ * file replays it instead of re-instantiating — and the `6e15de6f` flag fix
517
+ * means the replay drains again rather than skipping it. Destroying first is
518
+ * what makes that retained record useless.
519
+ *
520
+ * The residual cost is honest: the CJS flavor hands the context to its
521
+ * `process.on('exit')` teardown, so a process that never retries still reclaims
522
+ * it on the way out. The ESM browser flavor has no equivalent — a module that
523
+ * throws while evaluating is permanently errored, so re-importing rethrows
524
+ * without re-running this file — and there the context stays until the realm
525
+ * goes away. That is the deliberate choice: a hung promise is a silent liveness
526
+ * bug with no upper bound, while the retained bookkeeping is bounded by the page.
527
+ */
528
+ function __rollbackWasiInitialization() {
529
+ const cleanupErrors = []
530
+ let drainResult
531
+ let settlementsUnreached = false
532
+ try {
533
+ __prepareWasmEnvCleanup()
534
+ drainResult = __drainWasmEnvCleanup()
535
+ } catch (cleanupError) {
536
+ cleanupErrors.push(cleanupError)
537
+ settlementsUnreached = true
538
+ }
539
+ if (__isThenable(drainResult)) {
540
+ return Promise.resolve(drainResult).then(
541
+ () => __destroyContextForWasiRollback(cleanupErrors),
542
+ (cleanupError) => {
543
+ cleanupErrors.push(cleanupError)
544
+ return __retainFailedWasiRollback(cleanupErrors)
545
+ },
546
+ )
547
+ }
548
+ if (settlementsUnreached) {
549
+ return __retainFailedWasiRollback(cleanupErrors)
550
+ }
551
+ return __destroyContextForWasiRollback(cleanupErrors)
552
+ }
553
+
296
554
  let __wasiModule
297
555
  let __napiModule
298
556
 
@@ -304,9 +562,10 @@ try {
304
562
  instance: __napiInstance,
305
563
  module: __wasiModule,
306
564
  napiModule: __napiModule,
307
- } = __emnapiInstantiateNapiModuleSync(__wasmFile, {
565
+ } = await __emnapiInstantiateNapiModule(__wasmFile, {
308
566
  context: __emnapiContext,
309
- asyncWorkPoolSize: 4,
567
+ asyncWorkPoolSize: __asyncWorkPoolSize,
568
+ reuseWorker: false,
310
569
  plugins: [__emnapiAsyncWorkPlugin, __emnapiTSFNPlugin],
311
570
  wasi: __wasi,
312
571
  onCreateWorker() {
package/minify.wasi.cjs CHANGED
@@ -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 (
package/minify.wasi.d.cts CHANGED
@@ -167,6 +167,38 @@ export interface MangleOptionsKeepNames {
167
167
  class: boolean
168
168
  }
169
169
 
170
+ export interface ManglePropertiesOptions {
171
+ /**
172
+ * JavaScript `RegExp` selecting property names to mangle. The source and flags are compiled
173
+ * with Rust's regex engine. Flags `i`, `m`, `s`, and `u` are supported.
174
+ */
175
+ include: RegExp
176
+ /** JavaScript `RegExp` excluding property names selected by `include`. */
177
+ exclude?: RegExp
178
+ /** Exact names that are neither mangled nor emitted as automatic output names. */
179
+ reserved?: Array<string>
180
+ /**
181
+ * Mangle quoted property occurrences in addition to unquoted occurrences.
182
+ *
183
+ * @default false
184
+ */
185
+ quoted?: boolean
186
+ /**
187
+ * Generate readable `_$name$_`-style output names.
188
+ *
189
+ * @default false
190
+ */
191
+ debug?: boolean
192
+ /**
193
+ * Stable mappings from original names to output names. `false` reserves an original name.
194
+ * Entries that do not match `include`, or that match `exclude`, remain inert but are
195
+ * preserved in the returned `mangleCache`. String targets must be `IdentifierName` values
196
+ * other than `__proto__`, `constructor`, or `prototype`. The original name `__proto__` is
197
+ * always reserved and cannot be used as a cache key.
198
+ */
199
+ cache?: Record<string, string | false>
200
+ }
201
+
170
202
  /**
171
203
  * Minify asynchronously.
172
204
  *
@@ -179,6 +211,12 @@ export interface MinifyOptions {
179
211
  module?: boolean
180
212
  compress?: boolean | CompressOptions
181
213
  mangle?: boolean | MangleOptions
214
+ /**
215
+ * Mangle matching property names independently of identifier mangling. Properties owned by
216
+ * unminified code, imported module namespaces, globals, or host APIs must be excluded or
217
+ * reserved.
218
+ */
219
+ mangleProps?: ManglePropertiesOptions
182
220
  codegen?: boolean | CodegenOptions
183
221
  sourcemap?: boolean
184
222
  }
@@ -192,6 +230,11 @@ export interface MinifyResult {
192
230
  * Only populated when `codegen.legalComments` is `"linked"` or `"external"`.
193
231
  */
194
232
  legalComments: Array<string>
233
+ /**
234
+ * Updated property-name cache sorted by original name. Present when `mangleProps` ran on a
235
+ * parse without errors.
236
+ */
237
+ mangleCache?: Record<string, string | false>
195
238
  }
196
239
 
197
240
  /** Minify synchronously. */
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oxc-minify/binding-wasm32-wasi",
3
- "version": "0.143.0",
3
+ "version": "0.145.0",
4
4
  "main": "minify.wasi.cjs",
5
5
  "files": [
6
6
  "minify.wasm32-wasi.wasm",
@@ -40,7 +40,7 @@
40
40
  "browser": "minify.wasi-browser.js",
41
41
  "type": "module",
42
42
  "dependencies": {
43
- "@napi-rs/wasm-runtime": "~1.2.2",
43
+ "@napi-rs/wasm-runtime": "~1.2.3",
44
44
  "@emnapi/core": "2.0.0-alpha.3",
45
45
  "@emnapi/runtime": "2.0.0-alpha.3"
46
46
  }