@emnapi/runtime 2.0.0-beta.3 → 2.0.0-beta.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/dist/emnapi.d.ts CHANGED
@@ -288,9 +288,13 @@ export declare interface CallHandlerConfig {
288
288
  export declare type CleanupHookCallbackFunction = number | ((arg: number) => void);
289
289
 
290
290
  export declare class Context {
291
+ private _isAborted;
291
292
  private _isStopping;
292
293
  private _canCallIntoJs;
293
294
  private _suppressDestroy;
295
+ private _beforeExitListener?;
296
+ private readonly _pendingTasks;
297
+ private _activeTaskDepth;
294
298
  private envStore;
295
299
  refStore: Map<number, Reference>;
296
300
  private readonly refCounter?;
@@ -298,6 +302,7 @@ export declare class Context {
298
302
  readonly features: Features;
299
303
  readonly isolate: Isolate;
300
304
  constructor(options?: ContextOptions);
305
+ private _removeBeforeExitListener;
301
306
  getIsolate(): Isolate;
302
307
  suppressDestroy(): void;
303
308
  getRuntimeVersions(): {
@@ -337,11 +342,20 @@ export declare class Context {
337
342
  setCanCallIntoJs(value: boolean): void;
338
343
  setStopping(value: boolean): void;
339
344
  canCallIntoJs(): boolean;
345
+ isAborted(): boolean;
346
+ registerPendingTask(task: () => void): () => void;
347
+ scheduleImmediate(callback: () => void): void;
348
+ scheduleMicrotask(callback: () => void): void;
349
+ hasPendingWork(): boolean;
350
+ flush(): void;
351
+ drain(): Promise<void>;
352
+ abort(): void;
340
353
  getDylinkMetadata(binary: WebAssembly.Module | Uint8Array): DylinkMetadata;
341
354
  destroy(): void;
342
355
  }
343
356
 
344
357
  export declare interface ContextOptions extends IsolateOptions {
358
+ autoDestroy?: boolean;
345
359
  }
346
360
 
347
361
  export declare class CountIdAllocator extends Disposable_2 implements IdAllocator {
@@ -462,6 +476,7 @@ export declare class Finalizer {
462
476
  private _finalizeCallback;
463
477
  private _finalizeData;
464
478
  private _finalizeHint;
479
+ private _ctx;
465
480
  private _makeDynCall_vppp;
466
481
  constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p);
467
482
  copy(): Finalizer;
package/dist/emnapi.js CHANGED
@@ -144,6 +144,24 @@ function detectFeatures(features) {
144
144
  function isReferenceType(v) {
145
145
  return (typeof v === 'object' && v !== null) || typeof v === 'function';
146
146
  }
147
+ function isWebAssemblyModule(value) {
148
+ if (typeof value !== 'object' || value === null || typeof WebAssembly !== 'object' || WebAssembly === null) {
149
+ return false;
150
+ }
151
+ if (typeof WebAssembly.Module === 'function') {
152
+ if (typeof WebAssembly.Module.imports === 'function') {
153
+ try {
154
+ WebAssembly.Module.imports(value);
155
+ return true;
156
+ }
157
+ catch (_) {
158
+ return false;
159
+ }
160
+ }
161
+ return value instanceof WebAssembly.Module;
162
+ }
163
+ return false;
164
+ }
147
165
  function getDylinkMetadata(binary) {
148
166
  let offset = 0;
149
167
  let end = 0;
@@ -179,7 +197,7 @@ function getDylinkMetadata(binary) {
179
197
  if (condition)
180
198
  throw new Error(message);
181
199
  }
182
- if (binary instanceof WebAssembly.Module) {
200
+ if (isWebAssemblyModule(binary)) {
183
201
  const dylinkSection = WebAssembly.Module.customSections(binary, 'dylink.0');
184
202
  failIf(dylinkSection.length === 0, 'need dylink section');
185
203
  binary = new Uint8Array(dylinkSection[0]);
@@ -260,7 +278,7 @@ function getDylinkMetadata(binary) {
260
278
  failIf(offset !== end);
261
279
  return customSection;
262
280
  }
263
- const version = "2.0.0-beta.3";
281
+ const version = "2.0.0-beta.5";
264
282
  const NODE_API_SUPPORTED_VERSION_MIN = 1;
265
283
  const NODE_API_SUPPORTED_VERSION_MAX = 10;
266
284
  const NAPI_VERSION_EXPERIMENTAL = 2147483647;
@@ -328,11 +346,13 @@ class Finalizer {
328
346
  this._finalizeCallback = _finalizeCallback;
329
347
  this._finalizeData = _finalizeData;
330
348
  this._finalizeHint = _finalizeHint;
349
+ this._ctx = envObject.ctx;
331
350
  this._makeDynCall_vppp = envObject.bridge.makeDynCall_vppp;
332
351
  }
333
352
  copy() {
334
353
  const newFina = Object.create(Finalizer.prototype);
335
354
  newFina.envObject = this.envObject;
355
+ newFina._ctx = this._ctx;
336
356
  newFina._makeDynCall_vppp = this._makeDynCall_vppp;
337
357
  newFina._finalizeCallback = this._finalizeCallback;
338
358
  newFina._finalizeData = this._finalizeData;
@@ -344,6 +364,7 @@ class Finalizer {
344
364
  target._finalizeData = this._finalizeData;
345
365
  target._finalizeHint = this._finalizeHint;
346
366
  target.envObject = this.envObject;
367
+ target._ctx = this._ctx;
347
368
  target._makeDynCall_vppp = this._makeDynCall_vppp;
348
369
  this._finalizeCallback = 0;
349
370
  this._finalizeData = 0;
@@ -368,6 +389,8 @@ class Finalizer {
368
389
  this.resetFinalizer();
369
390
  if (!finalize_callback)
370
391
  return;
392
+ if (this._ctx?.isAborted())
393
+ return;
371
394
  const fini = Number(finalize_callback);
372
395
  if (!this.envObject) {
373
396
  this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint);
@@ -378,6 +401,7 @@ class Finalizer {
378
401
  }
379
402
  dispose() {
380
403
  this.envObject = undefined;
404
+ this._ctx = undefined;
381
405
  this._makeDynCall_vppp = undefined;
382
406
  }
383
407
  }
@@ -803,9 +827,15 @@ class Env extends Disposable {
803
827
  return error_code;
804
828
  }
805
829
  callIntoModule(fn, handleException = handleThrow) {
830
+ if (this.ctx.isAborted()) {
831
+ throw new Error('Context has been aborted');
832
+ }
806
833
  const openHandleScopesBefore = this.openHandleScopes;
807
834
  this.clearLastError();
808
835
  const r = fn(this);
836
+ if (this.ctx.isAborted()) {
837
+ return r;
838
+ }
809
839
  if (openHandleScopesBefore !== this.openHandleScopes) {
810
840
  this.bridge.abort('open_handle_scopes != open_handle_scopes_before');
811
841
  }
@@ -817,6 +847,8 @@ class Env extends Disposable {
817
847
  return r;
818
848
  }
819
849
  invokeFinalizerFromGC(finalizer) {
850
+ if (this.ctx.isAborted())
851
+ return;
820
852
  if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) {
821
853
  this.enqueueFinalizer(finalizer);
822
854
  }
@@ -848,10 +880,16 @@ class Env extends Disposable {
848
880
  this.pendingFinalizers.delete(finalizer);
849
881
  }
850
882
  deleteMe() {
883
+ if (this.ctx.isAborted())
884
+ return;
851
885
  RefTracker.finalizeAll(this.finalizing_reflist);
886
+ if (this.ctx.isAborted())
887
+ return;
852
888
  RefTracker.finalizeAll(this.reflist);
853
889
  this.lastException.reset();
854
890
  this.store.dealloc(this.id);
891
+ if (this.ctx.isAborted())
892
+ return;
855
893
  this.bridge.deleteEnv(this.address);
856
894
  }
857
895
  dispose() {
@@ -894,8 +932,12 @@ class NodeEnv extends Env {
894
932
  this.bridge = bridge;
895
933
  }
896
934
  deleteMe() {
935
+ if (this.ctx.isAborted())
936
+ return;
897
937
  this.destructing = true;
898
938
  this.drainFinalizerQueue();
939
+ if (this.ctx.isAborted())
940
+ return;
899
941
  super.deleteMe();
900
942
  }
901
943
  canCallIntoJs() {
@@ -958,10 +1000,21 @@ class NodeEnv extends Env {
958
1000
  }
959
1001
  }
960
1002
  enqueueFinalizer(finalizer) {
1003
+ if (this.ctx.isAborted())
1004
+ return;
961
1005
  super.enqueueFinalizer(finalizer);
962
1006
  if (!this.finalizationScheduled && !this.destructing) {
1007
+ let done = false;
1008
+ let cancelPending;
963
1009
  const drain = () => {
1010
+ if (done)
1011
+ return;
1012
+ done = true;
1013
+ cancelPending?.();
1014
+ cancelPending = undefined;
964
1015
  this.finalizationScheduled = false;
1016
+ if (this.ctx.isAborted())
1017
+ return;
965
1018
  this.unref();
966
1019
  this.drainFinalizerQueue();
967
1020
  };
@@ -976,13 +1029,18 @@ class NodeEnv extends Env {
976
1029
  Promise.resolve().then(drain);
977
1030
  }
978
1031
  }
1032
+ cancelPending = this.ctx.registerPendingTask(drain);
979
1033
  this.finalizationScheduled = true;
980
1034
  this.ref();
981
1035
  }
982
1036
  }
983
1037
  drainFinalizerQueue() {
1038
+ if (this.ctx.isAborted())
1039
+ return;
984
1040
  for (const refTracker of this.pendingFinalizers) {
985
1041
  this.pendingFinalizers.delete(refTracker);
1042
+ if (this.ctx.isAborted())
1043
+ return;
986
1044
  refTracker.finalize();
987
1045
  }
988
1046
  }
@@ -2362,12 +2420,16 @@ class CleanupQueue {
2362
2420
  const hooks = this._cleanupHooks.slice();
2363
2421
  for (let i = hooks.length - 1; i >= 0; --i) {
2364
2422
  const cb = hooks[i];
2423
+ if (cb.envObject.ctx.isAborted())
2424
+ return;
2365
2425
  if (typeof cb.fn === 'number') {
2366
2426
  cb.envObject.bridge.makeDynCall_vp(cb.fn)(cb.arg);
2367
2427
  }
2368
2428
  else {
2369
2429
  cb.fn(cb.arg);
2370
2430
  }
2431
+ if (cb.envObject.ctx.isAborted())
2432
+ return;
2371
2433
  const lastIndex = this._cleanupHooks.length - 1;
2372
2434
  if (this._cleanupHooks[lastIndex] === cb) {
2373
2435
  this._cleanupHooks.pop();
@@ -2443,24 +2505,53 @@ class NodejsWaitingRequestCounter {
2443
2505
  }
2444
2506
  this.count--;
2445
2507
  }
2508
+ abort() {
2509
+ this.count = 0;
2510
+ if (this.refHandle.unref) {
2511
+ this.refHandle.unref();
2512
+ }
2513
+ try {
2514
+ this.refHandle.close?.();
2515
+ }
2516
+ catch (_) { }
2517
+ }
2446
2518
  }
2447
2519
  class Context {
2448
2520
  constructor(options) {
2521
+ this._isAborted = false;
2449
2522
  this._isStopping = false;
2450
2523
  this._canCallIntoJs = true;
2451
2524
  this._suppressDestroy = false;
2525
+ this._pendingTasks = new Set();
2526
+ this._activeTaskDepth = 0;
2452
2527
  this.envStore = new ArrayStore();
2453
2528
  this.refStore = new Map();
2454
2529
  this.isolate = new Isolate(options);
2455
2530
  this.features = this.isolate.features;
2456
2531
  this.cleanupQueue = new CleanupQueue();
2457
- if (typeof process === 'object' && process !== null && typeof process.once === 'function' && this.features.MessageChannel) {
2458
- this.refCounter = new NodejsWaitingRequestCounter(this.features.MessageChannel);
2459
- process.once('beforeExit', () => {
2460
- if (!this._suppressDestroy) {
2461
- this.destroy();
2462
- }
2463
- });
2532
+ if (typeof process === 'object' && process !== null && typeof process.once === 'function') {
2533
+ if (this.features.MessageChannel) {
2534
+ this.refCounter = new NodejsWaitingRequestCounter(this.features.MessageChannel);
2535
+ }
2536
+ if (options?.autoDestroy !== false) {
2537
+ const onBeforeExit = () => {
2538
+ this._beforeExitListener = undefined;
2539
+ if (!this._suppressDestroy) {
2540
+ this.destroy();
2541
+ }
2542
+ };
2543
+ this._beforeExitListener = onBeforeExit;
2544
+ process.once('beforeExit', onBeforeExit);
2545
+ }
2546
+ }
2547
+ }
2548
+ _removeBeforeExitListener() {
2549
+ const listener = this._beforeExitListener;
2550
+ if (listener !== undefined) {
2551
+ this._beforeExitListener = undefined;
2552
+ if (typeof process === 'object' && process !== null && typeof process.removeListener === 'function') {
2553
+ process.removeListener('beforeExit', listener);
2554
+ }
2464
2555
  }
2465
2556
  }
2466
2557
  getIsolate() {
@@ -2468,6 +2559,7 @@ class Context {
2468
2559
  }
2469
2560
  suppressDestroy() {
2470
2561
  this._suppressDestroy = true;
2562
+ this._removeBeforeExitListener();
2471
2563
  }
2472
2564
  getRuntimeVersions() {
2473
2565
  return {
@@ -2591,20 +2683,28 @@ class Context {
2591
2683
  return this.isolate.isExternal(value);
2592
2684
  }
2593
2685
  addCleanupHook(envObject, fn, arg) {
2686
+ if (this._isAborted)
2687
+ return;
2594
2688
  this.cleanupQueue.add(envObject, fn, arg);
2595
2689
  }
2596
2690
  removeCleanupHook(envObject, fn, arg) {
2597
2691
  this.cleanupQueue.remove(envObject, fn, arg);
2598
2692
  }
2599
2693
  runCleanup() {
2600
- while (!this.cleanupQueue.empty()) {
2694
+ if (this._isAborted)
2695
+ return;
2696
+ while (!this._isAborted && !this.cleanupQueue.empty()) {
2601
2697
  this.cleanupQueue.drain();
2602
2698
  }
2603
2699
  }
2604
2700
  increaseWaitingRequestCounter() {
2701
+ if (this._isAborted)
2702
+ return;
2605
2703
  this.refCounter?.increase();
2606
2704
  }
2607
2705
  decreaseWaitingRequestCounter() {
2706
+ if (this._isAborted)
2707
+ return;
2608
2708
  this.refCounter?.decrease();
2609
2709
  }
2610
2710
  setCanCallIntoJs(value) {
@@ -2614,15 +2714,121 @@ class Context {
2614
2714
  this._isStopping = value;
2615
2715
  }
2616
2716
  canCallIntoJs() {
2617
- return this._canCallIntoJs && !this._isStopping;
2717
+ return this._canCallIntoJs && !this._isStopping && !this._isAborted;
2718
+ }
2719
+ isAborted() {
2720
+ return this._isAborted;
2721
+ }
2722
+ registerPendingTask(task) {
2723
+ if (this._isAborted) {
2724
+ return () => { };
2725
+ }
2726
+ this._pendingTasks.add(task);
2727
+ return () => {
2728
+ this._pendingTasks.delete(task);
2729
+ };
2730
+ }
2731
+ scheduleImmediate(callback) {
2732
+ if (this._isAborted)
2733
+ return;
2734
+ let done = false;
2735
+ const run = () => {
2736
+ if (done)
2737
+ return;
2738
+ done = true;
2739
+ cancel();
2740
+ if (this._isAborted)
2741
+ return;
2742
+ this._activeTaskDepth++;
2743
+ try {
2744
+ callback();
2745
+ }
2746
+ finally {
2747
+ this._activeTaskDepth--;
2748
+ }
2749
+ };
2750
+ const cancel = this.registerPendingTask(run);
2751
+ try {
2752
+ this.features.setImmediate(run);
2753
+ }
2754
+ catch (err) {
2755
+ done = true;
2756
+ cancel();
2757
+ throw err;
2758
+ }
2759
+ }
2760
+ scheduleMicrotask(callback) {
2761
+ if (this._isAborted)
2762
+ return;
2763
+ let done = false;
2764
+ const run = () => {
2765
+ if (done)
2766
+ return;
2767
+ done = true;
2768
+ cancel();
2769
+ if (this._isAborted)
2770
+ return;
2771
+ this._activeTaskDepth++;
2772
+ try {
2773
+ callback();
2774
+ }
2775
+ finally {
2776
+ this._activeTaskDepth--;
2777
+ }
2778
+ };
2779
+ const cancel = this.registerPendingTask(run);
2780
+ Promise.resolve().then(run);
2781
+ }
2782
+ hasPendingWork() {
2783
+ return !this._isAborted && this._pendingTasks.size > 0;
2784
+ }
2785
+ flush() {
2786
+ if (this._activeTaskDepth > 0)
2787
+ return;
2788
+ this._activeTaskDepth++;
2789
+ try {
2790
+ while (!this._isAborted && this._pendingTasks.size > 0) {
2791
+ const task = this._pendingTasks.values().next().value;
2792
+ this._pendingTasks.delete(task);
2793
+ task();
2794
+ }
2795
+ }
2796
+ finally {
2797
+ this._activeTaskDepth--;
2798
+ }
2799
+ }
2800
+ async drain() {
2801
+ while (!this._isAborted) {
2802
+ this.flush();
2803
+ if (this._isAborted)
2804
+ return;
2805
+ await Promise.resolve();
2806
+ if (this._isAborted || this._pendingTasks.size === 0)
2807
+ return;
2808
+ }
2809
+ }
2810
+ abort() {
2811
+ if (this._isAborted)
2812
+ return;
2813
+ this._isAborted = true;
2814
+ this._isStopping = true;
2815
+ this._canCallIntoJs = false;
2816
+ this._suppressDestroy = true;
2817
+ this._removeBeforeExitListener();
2818
+ this.refCounter?.abort();
2819
+ this.cleanupQueue.dispose();
2820
+ this._pendingTasks.clear();
2618
2821
  }
2619
2822
  getDylinkMetadata(binary) {
2620
2823
  return getDylinkMetadata(binary);
2621
2824
  }
2622
2825
  destroy() {
2826
+ if (this._isAborted)
2827
+ return;
2623
2828
  this.setStopping(true);
2624
2829
  this.setCanCallIntoJs(false);
2625
2830
  this.runCleanup();
2831
+ this._removeBeforeExitListener();
2626
2832
  }
2627
2833
  }
2628
2834
  let defaultContext;