@emnapi/runtime 1.11.0 → 2.0.0-alpha.2

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.js CHANGED
@@ -1,68 +1,11 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.emnapi = {}));
5
- })(this, (function (exports) {
6
- /******************************************************************************
7
- Copyright (c) Microsoft Corporation.
8
-
9
- Permission to use, copy, modify, and/or distribute this software for any
10
- purpose with or without fee is hereby granted.
11
-
12
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
14
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
15
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
16
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
17
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
18
- PERFORMANCE OF THIS SOFTWARE.
19
- ***************************************************************************** */
20
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
21
-
22
- var extendStatics = function(d, b) {
23
- extendStatics = Object.setPrototypeOf ||
24
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
26
- return extendStatics(d, b);
27
- };
28
-
29
- function __extends(d, b) {
30
- if (typeof b !== "function" && b !== null)
31
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
32
- extendStatics(d, b);
33
- function __() { this.constructor = d; }
34
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
35
- }
36
-
37
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
38
- var e = new Error(message);
39
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
40
- };
41
-
42
- var externalValue = new WeakMap();
43
- /** @public */
44
- function isExternal(object) {
45
- return externalValue.has(object);
46
- }
47
- /** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare
48
- var External = (function () {
49
- function External(value) {
50
- Object.setPrototypeOf(this, null);
51
- externalValue.set(this, value);
52
- }
53
- External.prototype = null;
54
- return External;
55
- })();
56
- /** @public */
57
- function getExternalValue(external) {
58
- if (!isExternal(external)) {
59
- throw new TypeError('not external');
60
- }
61
- return externalValue.get(external);
62
- }
63
-
64
- var supportNewFunction = /*#__PURE__*/ (function () {
65
- var f;
1
+ //#region src/util.ts
2
+ function detectFinalizer() {
3
+ return (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined');
4
+ }
5
+ const supportFinalizer = detectFinalizer();
6
+ function detectFeatures(features) {
7
+ const supportNewFunction = (function () {
8
+ let f;
66
9
  try {
67
10
  f = new Function();
68
11
  }
@@ -71,73 +14,17 @@
71
14
  }
72
15
  return typeof f === 'function';
73
16
  })();
74
- var _global = /*#__PURE__*/ (function () {
75
- if (typeof globalThis !== 'undefined')
76
- return globalThis;
77
- var g = (function () { return this; })();
78
- if (!g && supportNewFunction) {
79
- try {
80
- g = new Function('return this')();
81
- }
82
- catch (_) { }
83
- }
84
- if (!g) {
85
- if (typeof __webpack_public_path__ === 'undefined') {
86
- if (typeof global !== 'undefined')
87
- return global;
88
- }
89
- if (typeof window !== 'undefined')
90
- return window;
91
- if (typeof self !== 'undefined')
92
- return self;
93
- }
94
- return g;
95
- })();
96
- var TryCatch = /*#__PURE__*/ (function () {
97
- function TryCatch() {
98
- this._exception = undefined;
99
- this._caught = false;
100
- }
101
- TryCatch.prototype.isEmpty = function () {
102
- return !this._caught;
103
- };
104
- TryCatch.prototype.hasCaught = function () {
105
- return this._caught;
106
- };
107
- TryCatch.prototype.exception = function () {
108
- return this._exception;
109
- };
110
- TryCatch.prototype.setError = function (err) {
111
- this._caught = true;
112
- this._exception = err;
113
- };
114
- TryCatch.prototype.reset = function () {
115
- this._caught = false;
116
- this._exception = undefined;
117
- };
118
- TryCatch.prototype.extractException = function () {
119
- var e = this._exception;
120
- this.reset();
121
- return e;
122
- };
123
- return TryCatch;
124
- }());
125
- var canSetFunctionName = /*#__PURE__*/ (function () {
126
- var _a;
17
+ const canSetFunctionName = (function () {
127
18
  try {
128
- return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable);
19
+ return Boolean(Object.getOwnPropertyDescriptor(Function.prototype, 'name')?.configurable);
129
20
  }
130
21
  catch (_) {
131
22
  return false;
132
23
  }
133
24
  })();
134
- var supportReflect = typeof Reflect === 'object';
135
- var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined');
136
- var supportWeakSymbol = /*#__PURE__*/ (function () {
25
+ const weakSymbol = (function () {
137
26
  try {
138
- // eslint-disable-next-line symbol-description
139
- var sym = Symbol();
140
- // eslint-disable-next-line no-new
27
+ const sym = Symbol();
141
28
  new WeakRef(sym);
142
29
  new WeakMap().set(sym, undefined);
143
30
  }
@@ -146,12 +33,8 @@
146
33
  }
147
34
  return true;
148
35
  })();
149
- var supportBigInt = typeof BigInt !== 'undefined';
150
- function isReferenceType(v) {
151
- return (typeof v === 'object' && v !== null) || typeof v === 'function';
152
- }
153
- var _require = /*#__PURE__*/ (function () {
154
- var nativeRequire;
36
+ const _require = (function () {
37
+ let nativeRequire;
155
38
  if (typeof __webpack_public_path__ !== 'undefined') {
156
39
  nativeRequire = (function () {
157
40
  return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined;
@@ -164,1347 +47,2179 @@
164
47
  }
165
48
  return nativeRequire;
166
49
  })();
167
- var _MessageChannel = typeof MessageChannel === 'function'
168
- ? MessageChannel
169
- : /*#__PURE__*/ (function () {
170
- try {
171
- return _require('worker_threads').MessageChannel;
172
- }
173
- catch (_) { }
174
- return undefined;
175
- })();
176
- var _setImmediate = typeof setImmediate === 'function'
177
- ? setImmediate
178
- : function (callback) {
179
- if (typeof callback !== 'function') {
180
- throw new TypeError('The "callback" argument must be of type function');
181
- }
182
- if (_MessageChannel) {
183
- var channel_1 = new _MessageChannel();
184
- channel_1.port1.onmessage = function () {
185
- channel_1.port1.onmessage = null;
186
- channel_1 = undefined;
187
- callback();
188
- };
189
- channel_1.port2.postMessage(null);
190
- }
191
- else {
192
- setTimeout(callback, 0);
193
- }
194
- };
195
- var _Buffer = typeof Buffer === 'function'
196
- ? Buffer
197
- : /*#__PURE__*/ (function () {
50
+ function defaultGetGlobalThis() {
51
+ if (typeof globalThis !== 'undefined')
52
+ return globalThis;
53
+ let g = (function () { return this; })();
54
+ if (!g && supportNewFunction) {
198
55
  try {
199
- return _require('buffer').Buffer;
56
+ g = new Function('return this')();
200
57
  }
201
58
  catch (_) { }
202
- return undefined;
203
- })();
204
- var version = "1.11.0";
205
- var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */;
206
- var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */;
207
- var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */;
208
- var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */;
209
-
210
- var Handle = /*#__PURE__*/ (function () {
211
- function Handle(id, value) {
212
- this.id = id;
213
- this.value = value;
214
59
  }
215
- Handle.prototype.data = function () {
216
- return getExternalValue(this.value);
217
- };
218
- Handle.prototype.isNumber = function () {
219
- return typeof this.value === 'number';
220
- };
221
- Handle.prototype.isBigInt = function () {
222
- return typeof this.value === 'bigint';
223
- };
224
- Handle.prototype.isString = function () {
225
- return typeof this.value === 'string';
226
- };
227
- Handle.prototype.isFunction = function () {
228
- return typeof this.value === 'function';
229
- };
230
- Handle.prototype.isExternal = function () {
231
- return isExternal(this.value);
232
- };
233
- Handle.prototype.isObject = function () {
234
- return typeof this.value === 'object' && this.value !== null;
235
- };
236
- Handle.prototype.isArray = function () {
237
- return Array.isArray(this.value);
238
- };
239
- Handle.prototype.isArrayBuffer = function () {
240
- return (this.value instanceof ArrayBuffer);
241
- };
242
- Handle.prototype.isTypedArray = function () {
243
- return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView);
244
- };
245
- Handle.prototype.isBuffer = function (BufferConstructor) {
246
- if (ArrayBuffer.isView(this.value))
247
- return true;
248
- BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer);
249
- return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value);
250
- };
251
- Handle.prototype.isDataView = function () {
252
- return (this.value instanceof DataView);
253
- };
254
- Handle.prototype.isDate = function () {
255
- return (this.value instanceof Date);
256
- };
257
- Handle.prototype.isPromise = function () {
258
- return (this.value instanceof Promise);
259
- };
260
- Handle.prototype.isBoolean = function () {
261
- return typeof this.value === 'boolean';
262
- };
263
- Handle.prototype.isUndefined = function () {
264
- return this.value === undefined;
265
- };
266
- Handle.prototype.isSymbol = function () {
267
- return typeof this.value === 'symbol';
268
- };
269
- Handle.prototype.isNull = function () {
270
- return this.value === null;
271
- };
272
- Handle.prototype.dispose = function () {
273
- this.value = undefined;
274
- };
275
- return Handle;
276
- }());
277
- var ConstHandle = /*#__PURE__*/ (function (_super) {
278
- __extends(ConstHandle, _super);
279
- function ConstHandle(id, value) {
280
- return _super.call(this, id, value) || this;
281
- }
282
- ConstHandle.prototype.dispose = function () { };
283
- return ConstHandle;
284
- }(Handle));
285
- var HandleStore = /*#__PURE__*/ (function () {
286
- function HandleStore() {
287
- this._values = [
288
- undefined,
289
- HandleStore.UNDEFINED,
290
- HandleStore.NULL,
291
- HandleStore.FALSE,
292
- HandleStore.TRUE,
293
- HandleStore.GLOBAL
294
- ];
295
- this._next = HandleStore.MIN_ID;
296
- }
297
- HandleStore.prototype.push = function (value) {
298
- var h;
299
- var next = this._next;
300
- var values = this._values;
301
- if (next < values.length) {
302
- h = values[next];
303
- h.value = value;
304
- }
305
- else {
306
- h = new Handle(next, value);
307
- values[next] = h;
308
- }
309
- this._next++;
310
- return h;
311
- };
312
- HandleStore.prototype.erase = function (start, end) {
313
- this._next = start;
314
- var values = this._values;
315
- for (var i = start; i < end; ++i) {
316
- values[i].dispose();
60
+ if (!g) {
61
+ if (typeof __webpack_public_path__ === 'undefined') {
62
+ if (typeof global !== 'undefined')
63
+ return global;
317
64
  }
318
- };
319
- HandleStore.prototype.get = function (id) {
320
- return this._values[id];
321
- };
322
- HandleStore.prototype.swap = function (a, b) {
323
- var values = this._values;
324
- var h = values[a];
325
- values[a] = values[b];
326
- values[a].id = Number(a);
327
- values[b] = h;
328
- h.id = Number(b);
329
- };
330
- HandleStore.prototype.dispose = function () {
331
- this._values.length = HandleStore.MIN_ID;
332
- this._next = HandleStore.MIN_ID;
333
- };
334
- HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined);
335
- HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null);
336
- HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false);
337
- HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true);
338
- HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global);
339
- HandleStore.MIN_ID = 6;
340
- return HandleStore;
341
- }());
342
-
343
- var HandleScope = /*#__PURE__*/ (function () {
344
- function HandleScope(handleStore, id, parentScope, start, end) {
345
- if (end === void 0) { end = start; }
346
- this.handleStore = handleStore;
347
- this.id = id;
348
- this.parent = parentScope;
349
- this.child = null;
350
- if (parentScope !== null)
351
- parentScope.child = this;
352
- this.start = start;
353
- this.end = end;
354
- this._escapeCalled = false;
355
- this.callbackInfo = {
356
- thiz: undefined,
357
- data: 0,
358
- args: undefined,
359
- fn: undefined
360
- };
65
+ if (typeof window !== 'undefined')
66
+ return window;
67
+ if (typeof self !== 'undefined')
68
+ return self;
361
69
  }
362
- HandleScope.prototype.add = function (value) {
363
- var h = this.handleStore.push(value);
364
- this.end++;
365
- return h;
366
- };
367
- HandleScope.prototype.addExternal = function (data) {
368
- return this.add(new External(data));
369
- };
370
- HandleScope.prototype.dispose = function () {
371
- if (this._escapeCalled)
372
- this._escapeCalled = false;
373
- if (this.start === this.end)
374
- return;
375
- this.handleStore.erase(this.start, this.end);
376
- };
377
- HandleScope.prototype.escape = function (handle) {
378
- if (this._escapeCalled)
379
- return null;
380
- this._escapeCalled = true;
381
- if (handle < this.start || handle >= this.end) {
382
- return null;
383
- }
384
- this.handleStore.swap(handle, this.start);
385
- var h = this.handleStore.get(this.start);
386
- this.start++;
387
- this.parent.end++;
388
- return h;
389
- };
390
- HandleScope.prototype.escapeCalled = function () {
391
- return this._escapeCalled;
392
- };
393
- return HandleScope;
394
- }());
395
-
396
- var ScopeStore = /*#__PURE__*/ (function () {
397
- function ScopeStore() {
398
- this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID);
399
- this.currentScope = this._rootScope;
400
- this._values = [undefined];
401
- }
402
- ScopeStore.prototype.get = function (id) {
403
- return this._values[id];
404
- };
405
- ScopeStore.prototype.openScope = function (handleStore) {
406
- var currentScope = this.currentScope;
407
- var scope = currentScope.child;
408
- if (scope !== null) {
409
- scope.start = scope.end = currentScope.end;
410
- }
411
- else {
412
- var id = currentScope.id + 1;
413
- scope = new HandleScope(handleStore, id, currentScope, currentScope.end);
414
- this._values[id] = scope;
415
- }
416
- this.currentScope = scope;
417
- return scope;
418
- };
419
- ScopeStore.prototype.closeScope = function () {
420
- var scope = this.currentScope;
421
- this.currentScope = scope.parent;
422
- scope.dispose();
423
- };
424
- ScopeStore.prototype.dispose = function () {
425
- this.currentScope = this._rootScope;
426
- this._values.length = 1;
427
- };
428
- return ScopeStore;
429
- }());
430
-
431
- var RefTracker = /*#__PURE__*/ (function () {
432
- function RefTracker() {
433
- this._next = null;
434
- this._prev = null;
435
- }
436
- /** @virtual */
437
- RefTracker.prototype.dispose = function () { };
438
- /** @virtual */
439
- RefTracker.prototype.finalize = function () { };
440
- RefTracker.prototype.link = function (list) {
441
- this._prev = list;
442
- this._next = list._next;
443
- if (this._next !== null) {
444
- this._next._prev = this;
445
- }
446
- list._next = this;
447
- };
448
- RefTracker.prototype.unlink = function () {
449
- if (this._prev !== null) {
450
- this._prev._next = this._next;
451
- }
452
- if (this._next !== null) {
453
- this._next._prev = this._prev;
454
- }
455
- this._prev = null;
456
- this._next = null;
457
- };
458
- RefTracker.finalizeAll = function (list) {
459
- while (list._next !== null) {
460
- list._next.finalize();
461
- }
462
- };
463
- return RefTracker;
464
- }());
465
-
466
- var Finalizer = /*#__PURE__*/ (function () {
467
- function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) {
468
- if (_finalizeCallback === void 0) { _finalizeCallback = 0; }
469
- if (_finalizeData === void 0) { _finalizeData = 0; }
470
- if (_finalizeHint === void 0) { _finalizeHint = 0; }
471
- this.envObject = envObject;
472
- this._finalizeCallback = _finalizeCallback;
473
- this._finalizeData = _finalizeData;
474
- this._finalizeHint = _finalizeHint;
475
- this._makeDynCall_vppp = envObject.makeDynCall_vppp;
476
- }
477
- Finalizer.prototype.callback = function () { return this._finalizeCallback; };
478
- Finalizer.prototype.data = function () { return this._finalizeData; };
479
- Finalizer.prototype.hint = function () { return this._finalizeHint; };
480
- Finalizer.prototype.resetEnv = function () {
481
- this.envObject = undefined;
482
- };
483
- Finalizer.prototype.resetFinalizer = function () {
484
- this._finalizeCallback = 0;
485
- this._finalizeData = 0;
486
- this._finalizeHint = 0;
487
- };
488
- Finalizer.prototype.callFinalizer = function () {
489
- var finalize_callback = this._finalizeCallback;
490
- var finalize_data = this._finalizeData;
491
- var finalize_hint = this._finalizeHint;
492
- this.resetFinalizer();
493
- if (!finalize_callback)
494
- return;
495
- var fini = Number(finalize_callback);
496
- if (!this.envObject) {
497
- this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint);
498
- }
499
- else {
500
- this.envObject.callFinalizer(fini, finalize_data, finalize_hint);
501
- }
502
- };
503
- Finalizer.prototype.dispose = function () {
504
- this.envObject = undefined;
505
- this._makeDynCall_vppp = undefined;
506
- };
507
- return Finalizer;
508
- }());
509
-
510
- var TrackedFinalizer = /*#__PURE__*/ (function (_super) {
511
- __extends(TrackedFinalizer, _super);
512
- function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) {
513
- var _this = _super.call(this) || this;
514
- _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint);
515
- return _this;
516
- }
517
- TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) {
518
- var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint);
519
- finalizer.link(envObject.finalizing_reflist);
520
- return finalizer;
521
- };
522
- TrackedFinalizer.prototype.data = function () {
523
- return this._finalizer.data();
524
- };
525
- TrackedFinalizer.prototype.dispose = function () {
526
- if (!this._finalizer)
527
- return;
528
- this.unlink();
529
- this._finalizer.envObject.dequeueFinalizer(this);
530
- this._finalizer.dispose();
531
- this._finalizer = undefined;
532
- _super.prototype.dispose.call(this);
533
- };
534
- TrackedFinalizer.prototype.finalize = function () {
535
- this.unlink();
536
- var error;
537
- var caught = false;
538
- try {
539
- this._finalizer.callFinalizer();
540
- }
541
- catch (err) {
542
- caught = true;
543
- error = err;
544
- }
545
- this.dispose();
546
- if (caught) {
547
- throw error;
548
- }
549
- };
550
- return TrackedFinalizer;
551
- }(RefTracker));
552
-
553
- function throwNodeApiVersionError(moduleName, moduleApiVersion) {
554
- var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons.");
555
- throw new Error(errorMessage);
70
+ throw new Error('Unable to get globalThis');
556
71
  }
557
- function handleThrow(envObject, value) {
558
- if (envObject.terminatedOrTerminating()) {
559
- return;
560
- }
561
- throw value;
562
- }
563
- var Env = /*#__PURE__*/ (function () {
564
- function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) {
565
- this.ctx = ctx;
566
- this.moduleApiVersion = moduleApiVersion;
567
- this.makeDynCall_vppp = makeDynCall_vppp;
568
- this.makeDynCall_vp = makeDynCall_vp;
569
- this.abort = abort;
570
- this.openHandleScopes = 0;
571
- this.instanceData = null;
572
- this.tryCatch = new TryCatch();
573
- this.refs = 1;
574
- this.reflist = new RefTracker();
575
- this.finalizing_reflist = new RefTracker();
576
- this.pendingFinalizers = [];
577
- this.lastError = {
578
- errorCode: 0 /* napi_status.napi_ok */,
579
- engineErrorCode: 0,
580
- engineReserved: 0
581
- };
582
- this.inGcFinalizer = false;
583
- this._bindingMap = new WeakMap();
584
- this.id = 0;
585
- }
586
- /** @virtual */
587
- Env.prototype.canCallIntoJs = function () {
588
- return true;
589
- };
590
- Env.prototype.terminatedOrTerminating = function () {
591
- return !this.canCallIntoJs();
592
- };
593
- Env.prototype.ref = function () {
594
- this.refs++;
595
- };
596
- Env.prototype.unref = function () {
597
- this.refs--;
598
- if (this.refs === 0) {
599
- this.dispose();
600
- }
601
- };
602
- Env.prototype.ensureHandle = function (value) {
603
- return this.ctx.ensureHandle(value);
604
- };
605
- Env.prototype.ensureHandleId = function (value) {
606
- return this.ensureHandle(value).id;
607
- };
608
- Env.prototype.clearLastError = function () {
609
- var lastError = this.lastError;
610
- if (lastError.errorCode !== 0 /* napi_status.napi_ok */)
611
- lastError.errorCode = 0 /* napi_status.napi_ok */;
612
- if (lastError.engineErrorCode !== 0)
613
- lastError.engineErrorCode = 0;
614
- if (lastError.engineReserved !== 0)
615
- lastError.engineReserved = 0;
616
- return 0 /* napi_status.napi_ok */;
617
- };
618
- Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) {
619
- if (engine_error_code === void 0) { engine_error_code = 0; }
620
- if (engine_reserved === void 0) { engine_reserved = 0; }
621
- var lastError = this.lastError;
622
- if (lastError.errorCode !== error_code)
623
- lastError.errorCode = error_code;
624
- if (lastError.engineErrorCode !== engine_error_code)
625
- lastError.engineErrorCode = engine_error_code;
626
- if (lastError.engineReserved !== engine_reserved)
627
- lastError.engineReserved = engine_reserved;
628
- return error_code;
629
- };
630
- Env.prototype.getReturnStatus = function () {
631
- return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */);
632
- };
633
- Env.prototype.callIntoModule = function (fn, handleException) {
634
- if (handleException === void 0) { handleException = handleThrow; }
635
- var openHandleScopesBefore = this.openHandleScopes;
636
- this.clearLastError();
637
- var r = fn(this);
638
- if (openHandleScopesBefore !== this.openHandleScopes) {
639
- this.abort('open_handle_scopes != open_handle_scopes_before');
640
- }
641
- if (this.tryCatch.hasCaught()) {
642
- var err = this.tryCatch.extractException();
643
- handleException(this, err);
644
- }
645
- return r;
646
- };
647
- Env.prototype.invokeFinalizerFromGC = function (finalizer) {
648
- if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) {
649
- this.enqueueFinalizer(finalizer);
650
- }
651
- else {
652
- var saved = this.inGcFinalizer;
653
- this.inGcFinalizer = true;
72
+ function defaultWithResolvers() {
73
+ let ok;
74
+ let err;
75
+ const promise = new this((resolve, reject) => {
76
+ ok = resolve;
77
+ err = reject;
78
+ });
79
+ return { promise, resolve: ok, reject: err };
80
+ }
81
+ const getGlobalThis = features && 'getGlobalThis' in features
82
+ ? (features.getGlobalThis ?? defaultGetGlobalThis)
83
+ : defaultGetGlobalThis;
84
+ const withResolvers = (features && 'withResolvers' in features)
85
+ ? (features.withResolvers ?? defaultWithResolvers)
86
+ : typeof Promise.withResolvers === 'function'
87
+ ? Promise.withResolvers
88
+ : defaultWithResolvers;
89
+ const getBuiltinModule = getGlobalThis?.().process?.getBuiltinModule ?? _require;
90
+ const ret = {
91
+ makeDynamicFunction: (supportNewFunction
92
+ ? (...args) => (new Function(...args))
93
+ : undefined),
94
+ setFunctionName: (canSetFunctionName
95
+ ? (f, name) => { Object.defineProperty(f, 'name', { value: name }); }
96
+ : undefined),
97
+ Reflect: typeof Reflect === 'object' ? Reflect : undefined,
98
+ finalizer: detectFinalizer(),
99
+ weakSymbol,
100
+ BigInt: typeof BigInt !== 'undefined' ? BigInt : undefined,
101
+ MessageChannel: typeof MessageChannel === 'function'
102
+ ? MessageChannel
103
+ : (function () {
654
104
  try {
655
- finalizer.finalize();
105
+ return getBuiltinModule('worker_threads').MessageChannel;
656
106
  }
657
- finally {
658
- this.inGcFinalizer = saved;
107
+ catch (_) { }
108
+ return undefined;
109
+ })(),
110
+ setImmediate: typeof setImmediate === 'function'
111
+ ? setImmediate
112
+ : function (callback) {
113
+ if (typeof callback !== 'function') {
114
+ throw new TypeError('The "callback" argument must be of type function');
659
115
  }
660
- }
661
- };
662
- Env.prototype.checkGCAccess = function () {
663
- if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) {
664
- this.abort('Finalizer is calling a function that may affect GC state.\n' +
665
- 'The finalizers are run directly from GC and must not affect GC ' +
666
- 'state.\n' +
667
- 'Use `node_api_post_finalizer` from inside of the finalizer to work ' +
668
- 'around this issue.\n' +
669
- 'It schedules the call as a new task in the event loop.');
670
- }
671
- };
672
- /** @virtual */
673
- Env.prototype.enqueueFinalizer = function (finalizer) {
674
- if (this.pendingFinalizers.indexOf(finalizer) === -1) {
675
- this.pendingFinalizers.push(finalizer);
676
- }
677
- };
678
- /** @virtual */
679
- Env.prototype.dequeueFinalizer = function (finalizer) {
680
- var index = this.pendingFinalizers.indexOf(finalizer);
681
- if (index !== -1) {
682
- this.pendingFinalizers.splice(index, 1);
683
- }
684
- };
685
- /** @virtual */
686
- Env.prototype.deleteMe = function () {
687
- RefTracker.finalizeAll(this.finalizing_reflist);
688
- RefTracker.finalizeAll(this.reflist);
689
- this.tryCatch.extractException();
690
- this.ctx.envStore.remove(this.id);
691
- };
692
- Env.prototype.dispose = function () {
693
- if (this.id === 0)
694
- return;
695
- this.deleteMe();
696
- this.finalizing_reflist.dispose();
697
- this.reflist.dispose();
698
- this.id = 0;
699
- };
700
- Env.prototype.initObjectBinding = function (value) {
701
- var binding = {
702
- wrapped: 0,
703
- tag: null
704
- };
705
- this._bindingMap.set(value, binding);
706
- return binding;
707
- };
708
- Env.prototype.getObjectBinding = function (value) {
709
- if (this._bindingMap.has(value)) {
710
- return this._bindingMap.get(value);
711
- }
712
- return this.initObjectBinding(value);
713
- };
714
- Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) {
715
- if (this.instanceData) {
716
- this.instanceData.dispose();
717
- }
718
- this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint);
719
- };
720
- Env.prototype.getInstanceData = function () {
721
- return this.instanceData ? this.instanceData.data() : 0;
722
- };
723
- return Env;
724
- }());
725
- var NodeEnv = /*#__PURE__*/ (function (_super) {
726
- __extends(NodeEnv, _super);
727
- function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) {
728
- var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this;
729
- _this.filename = filename;
730
- _this.nodeBinding = nodeBinding;
731
- _this.destructing = false;
732
- _this.finalizationScheduled = false;
733
- return _this;
734
- }
735
- NodeEnv.prototype.deleteMe = function () {
736
- this.destructing = true;
737
- this.drainFinalizerQueue();
738
- _super.prototype.deleteMe.call(this);
739
- };
740
- NodeEnv.prototype.canCallIntoJs = function () {
741
- return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs();
742
- };
743
- NodeEnv.prototype.triggerFatalException = function (err) {
744
- if (this.nodeBinding) {
745
- this.nodeBinding.napi.fatalException(err);
746
- }
747
- else {
748
- if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') {
749
- var handled = process._fatalException(err);
750
- if (!handled) {
751
- console.error(err);
752
- process.exit(1);
753
- }
116
+ if (ret.MessageChannel) {
117
+ let channel = new ret.MessageChannel();
118
+ channel.port1.onmessage = function () {
119
+ channel.port1.onmessage = null;
120
+ channel = undefined;
121
+ callback();
122
+ };
123
+ channel.port2.postMessage(null);
754
124
  }
755
125
  else {
756
- throw err;
126
+ setTimeout(callback, 0);
757
127
  }
758
- }
759
- };
760
- NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) {
761
- return this.callIntoModule(fn, function (envObject, err) {
762
- if (envObject.terminatedOrTerminating()) {
763
- return;
128
+ },
129
+ Buffer: typeof Buffer === 'function'
130
+ ? Buffer
131
+ : (function () {
132
+ try {
133
+ return getBuiltinModule('buffer').Buffer;
764
134
  }
765
- var hasProcess = typeof process === 'object' && process !== null;
766
- var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false;
767
- if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) {
768
- var warn = hasProcess && typeof process.emitWarning === 'function'
769
- ? process.emitWarning
770
- : function (warning, type, code) {
771
- if (warning instanceof Error) {
772
- console.warn(warning.toString());
773
- }
774
- else {
775
- var prefix = code ? "[".concat(code, "] ") : '';
776
- // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
777
- console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning));
778
- }
779
- };
780
- warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168');
781
- return;
135
+ catch (_) { }
136
+ return undefined;
137
+ })(),
138
+ ...features,
139
+ getGlobalThis,
140
+ withResolvers
141
+ };
142
+ return ret;
143
+ }
144
+ function isReferenceType(v) {
145
+ return (typeof v === 'object' && v !== null) || typeof v === 'function';
146
+ }
147
+ function getDylinkMetadata(binary) {
148
+ let offset = 0;
149
+ let end = 0;
150
+ const decoder = new TextDecoder();
151
+ function getU8() {
152
+ return binary[offset++];
153
+ }
154
+ function getLEB() {
155
+ let ret = 0;
156
+ let mul = 1;
157
+ while (1) {
158
+ let byte = binary[offset++];
159
+ ret += ((byte & 0x7f) * mul);
160
+ mul *= 0x80;
161
+ if (!(byte & 0x80))
162
+ break;
163
+ }
164
+ return ret;
165
+ }
166
+ function getString() {
167
+ let len = getLEB();
168
+ offset += len;
169
+ return decoder.decode(binary.subarray(offset - len, offset));
170
+ }
171
+ function getStringList() {
172
+ let count = getLEB();
173
+ let rtn = [];
174
+ while (count--)
175
+ rtn.push(getString());
176
+ return rtn;
177
+ }
178
+ function failIf(condition, message) {
179
+ if (condition)
180
+ throw new Error(message);
181
+ }
182
+ if (binary instanceof WebAssembly.Module) {
183
+ const dylinkSection = WebAssembly.Module.customSections(binary, 'dylink.0');
184
+ failIf(dylinkSection.length === 0, 'need dylink section');
185
+ binary = new Uint8Array(dylinkSection[0]);
186
+ end = binary.length;
187
+ }
188
+ else {
189
+ var int32View = new Uint32Array(new Uint8Array(binary.subarray(0, 24)).buffer);
190
+ var magicNumberFound = int32View[0] === 0x6d736100 || int32View[0] === 0x0061736d;
191
+ failIf(!magicNumberFound, 'need to see wasm magic number');
192
+ failIf(binary[8] !== 0, 'need the dylink section to be first');
193
+ offset = 9;
194
+ var section_size = getLEB();
195
+ end = offset + section_size;
196
+ var name = getString();
197
+ failIf(name !== 'dylink.0');
198
+ }
199
+ var customSection = {
200
+ neededDynlibs: [],
201
+ tlsExports: new Set(),
202
+ weakImports: new Set(),
203
+ runtimePaths: [],
204
+ memorySize: 0,
205
+ memoryAlign: 0,
206
+ tableSize: 0,
207
+ tableAlign: 0
208
+ };
209
+ var WASM_DYLINK_MEM_INFO = 0x1;
210
+ var WASM_DYLINK_NEEDED = 0x2;
211
+ var WASM_DYLINK_EXPORT_INFO = 0x3;
212
+ var WASM_DYLINK_IMPORT_INFO = 0x4;
213
+ var WASM_DYLINK_RUNTIME_PATH = 0x5;
214
+ var WASM_SYMBOL_TLS = 0x100;
215
+ var WASM_SYMBOL_BINDING_MASK = 0x3;
216
+ var WASM_SYMBOL_BINDING_WEAK = 0x1;
217
+ while (offset < end) {
218
+ var subsectionType = getU8();
219
+ var subsectionSize = getLEB();
220
+ if (subsectionType === WASM_DYLINK_MEM_INFO) {
221
+ customSection.memorySize = getLEB();
222
+ customSection.memoryAlign = getLEB();
223
+ customSection.tableSize = getLEB();
224
+ customSection.tableAlign = getLEB();
225
+ }
226
+ else if (subsectionType === WASM_DYLINK_NEEDED) {
227
+ customSection.neededDynlibs = getStringList();
228
+ }
229
+ else if (subsectionType === WASM_DYLINK_EXPORT_INFO) {
230
+ let count = getLEB();
231
+ while (count--) {
232
+ let symname = getString();
233
+ let flags = getLEB();
234
+ if (flags & WASM_SYMBOL_TLS) {
235
+ customSection.tlsExports.add(symname);
782
236
  }
783
- envObject.triggerFatalException(err);
784
- });
785
- };
786
- NodeEnv.prototype.callFinalizer = function (cb, data, hint) {
787
- this.callFinalizerInternal(1, cb, data, hint);
788
- };
789
- NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) {
790
- var f = this.makeDynCall_vppp(cb);
791
- var env = this.id;
792
- var scope = this.ctx.openScope(this);
793
- try {
794
- this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); });
795
- }
796
- finally {
797
- this.ctx.closeScope(this, scope);
798
- }
799
- };
800
- NodeEnv.prototype.enqueueFinalizer = function (finalizer) {
801
- var _this = this;
802
- _super.prototype.enqueueFinalizer.call(this, finalizer);
803
- if (!this.finalizationScheduled && !this.destructing) {
804
- this.finalizationScheduled = true;
805
- this.ref();
806
- _setImmediate(function () {
807
- _this.finalizationScheduled = false;
808
- _this.unref();
809
- _this.drainFinalizerQueue();
810
- });
811
237
  }
812
- };
813
- NodeEnv.prototype.drainFinalizerQueue = function () {
814
- while (this.pendingFinalizers.length > 0) {
815
- var refTracker = this.pendingFinalizers.shift();
816
- refTracker.finalize();
238
+ }
239
+ else if (subsectionType === WASM_DYLINK_IMPORT_INFO) {
240
+ let count = getLEB();
241
+ while (count--) {
242
+ getString();
243
+ let symname = getString();
244
+ let flags = getLEB();
245
+ if ((flags & WASM_SYMBOL_BINDING_MASK) === WASM_SYMBOL_BINDING_WEAK) {
246
+ customSection.weakImports.add(symname);
247
+ }
817
248
  }
818
- };
819
- return NodeEnv;
820
- }(Env));
821
- function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) {
822
- moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion;
823
- // Validate module_api_version.
824
- if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) {
825
- moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION;
826
249
  }
827
- else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) {
828
- throwNodeApiVersionError(filename, moduleApiVersion);
250
+ else if (subsectionType === WASM_DYLINK_RUNTIME_PATH) {
251
+ customSection.runtimePaths = getStringList();
252
+ }
253
+ else {
254
+ console.error('unknown dylink.0 subsection:', subsectionType);
255
+ offset += subsectionSize;
829
256
  }
830
- var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding);
831
- ctx.envStore.add(env);
832
- ctx.addCleanupHook(env, function () { env.unref(); }, 0);
833
- return env;
834
257
  }
258
+ var tableAlign = Math.pow(2, customSection.tableAlign);
259
+ failIf(tableAlign !== 1, `invalid tableAlign ${tableAlign}`);
260
+ failIf(offset !== end);
261
+ return customSection;
262
+ }
263
+ const version = "2.0.0-alpha.2";
264
+ const NODE_API_SUPPORTED_VERSION_MIN = 1;
265
+ const NODE_API_SUPPORTED_VERSION_MAX = 10;
266
+ const NAPI_VERSION_EXPERIMENTAL = 2147483647;
267
+ const NODE_API_DEFAULT_MODULE_API_VERSION = 8;
268
+ const NODE_MODULE_VERSION = 127;
835
269
 
836
- var EmnapiError = /*#__PURE__*/ (function (_super) {
837
- __extends(EmnapiError, _super);
838
- function EmnapiError(message) {
839
- var _newTarget = this.constructor;
840
- var _this = _super.call(this, message) || this;
841
- var ErrorConstructor = _newTarget;
842
- var proto = ErrorConstructor.prototype;
843
- if (!(_this instanceof EmnapiError)) {
844
- var setPrototypeOf = Object.setPrototypeOf;
845
- if (typeof setPrototypeOf === 'function') {
846
- setPrototypeOf.call(Object, _this, proto);
847
- }
848
- else {
849
- // eslint-disable-next-line no-proto
850
- _this.__proto__ = proto;
851
- }
852
- if (typeof Error.captureStackTrace === 'function') {
853
- Error.captureStackTrace(_this, ErrorConstructor);
854
- }
855
- }
856
- return _this;
857
- }
858
- return EmnapiError;
859
- }(Error));
860
- Object.defineProperty(EmnapiError.prototype, 'name', {
861
- configurable: true,
862
- writable: true,
863
- value: 'EmnapiError'
864
- });
865
- var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) {
866
- __extends(NotSupportWeakRefError, _super);
867
- function NotSupportWeakRefError(api, message) {
868
- return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this;
869
- }
870
- return NotSupportWeakRefError;
871
- }(EmnapiError));
872
- Object.defineProperty(NotSupportWeakRefError.prototype, 'name', {
873
- configurable: true,
874
- writable: true,
875
- value: 'NotSupportWeakRefError'
876
- });
877
- var NotSupportBufferError = /*#__PURE__*/ (function (_super) {
878
- __extends(NotSupportBufferError, _super);
879
- function NotSupportBufferError(api, message) {
880
- return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this;
881
- }
882
- return NotSupportBufferError;
883
- }(EmnapiError));
884
- Object.defineProperty(NotSupportBufferError.prototype, 'name', {
885
- configurable: true,
270
+ //#endregion src/util.ts
271
+
272
+ //#region src/Disaposable.ts
273
+ class Disposable {
274
+ }
275
+ if (typeof Symbol.dispose === 'symbol') {
276
+ Object.defineProperty(Disposable.prototype, Symbol.dispose, {
277
+ value() {
278
+ this.dispose();
279
+ },
886
280
  writable: true,
887
- value: 'NotSupportBufferError'
281
+ enumerable: false,
282
+ configurable: true
888
283
  });
284
+ }
285
+
286
+ //#endregion src/Disaposable.ts
889
287
 
890
- var StrongRef = /*#__PURE__*/ (function () {
891
- function StrongRef(value) {
892
- this._value = value;
288
+ //#region src/RefTracker.ts
289
+ class RefTracker extends Disposable {
290
+ constructor() {
291
+ super(...arguments);
292
+ this._next = null;
293
+ this._prev = null;
294
+ }
295
+ dispose() { }
296
+ finalize() { }
297
+ link(list) {
298
+ this._prev = list;
299
+ this._next = list._next;
300
+ if (this._next !== null) {
301
+ this._next._prev = this;
893
302
  }
894
- StrongRef.prototype.deref = function () {
895
- return this._value;
896
- };
897
- StrongRef.prototype.dispose = function () {
898
- this._value = undefined;
899
- };
900
- return StrongRef;
901
- }());
902
- var Persistent = /*#__PURE__*/ (function () {
903
- function Persistent(value) {
904
- this._ref = new StrongRef(value);
905
- }
906
- Persistent.prototype.setWeak = function (param, callback) {
907
- if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef)
908
- return;
909
- var value = this._ref.deref();
910
- try {
911
- Persistent._registry.register(value, this, this);
912
- var weakRef = new WeakRef(value);
913
- this._ref.dispose();
914
- this._ref = weakRef;
915
- this._param = param;
916
- this._callback = callback;
917
- }
918
- catch (err) {
919
- if (typeof value === 'symbol') ;
920
- else {
921
- throw err;
922
- }
923
- }
924
- };
925
- Persistent.prototype.clearWeak = function () {
926
- if (!supportFinalizer || this._ref === undefined)
927
- return;
928
- if (this._ref instanceof WeakRef) {
929
- try {
930
- Persistent._registry.unregister(this);
931
- }
932
- catch (_) { }
933
- this._param = undefined;
934
- this._callback = undefined;
935
- var value = this._ref.deref();
936
- if (value === undefined) {
937
- this._ref = value;
938
- }
939
- else {
940
- this._ref = new StrongRef(value);
941
- }
942
- }
943
- };
944
- Persistent.prototype.reset = function () {
945
- if (supportFinalizer) {
946
- try {
947
- Persistent._registry.unregister(this);
948
- }
949
- catch (_) { }
950
- }
951
- this._param = undefined;
952
- this._callback = undefined;
953
- if (this._ref instanceof StrongRef) {
954
- this._ref.dispose();
955
- }
956
- this._ref = undefined;
957
- };
958
- Persistent.prototype.isEmpty = function () {
959
- return this._ref === undefined;
960
- };
961
- Persistent.prototype.deref = function () {
962
- if (this._ref === undefined)
963
- return undefined;
964
- return this._ref.deref();
965
- };
966
- Persistent._registry = supportFinalizer
967
- ? new FinalizationRegistry(function (value) {
968
- value._ref = undefined;
969
- var callback = value._callback;
970
- var param = value._param;
971
- value._callback = undefined;
972
- value._param = undefined;
973
- if (typeof callback === 'function') {
974
- callback(param);
975
- }
976
- })
977
- : undefined;
978
- return Persistent;
979
- }());
303
+ list._next = this;
304
+ }
305
+ unlink() {
306
+ if (this._prev !== null) {
307
+ this._prev._next = this._next;
308
+ }
309
+ if (this._next !== null) {
310
+ this._next._prev = this._prev;
311
+ }
312
+ this._prev = null;
313
+ this._next = null;
314
+ }
315
+ static finalizeAll(list) {
316
+ while (list._next !== null) {
317
+ list._next.finalize();
318
+ }
319
+ }
320
+ }
980
321
 
981
- exports.ReferenceOwnership = void 0;
982
- (function (ReferenceOwnership) {
983
- ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime";
984
- ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland";
985
- })(exports.ReferenceOwnership || (exports.ReferenceOwnership = {}));
986
- function canBeHeldWeakly(value) {
987
- return value.isObject() || value.isFunction() || value.isSymbol();
988
- }
989
- var Reference = /*#__PURE__*/ (function (_super) {
990
- __extends(Reference, _super);
991
- function Reference(envObject, handle_id, initialRefcount, ownership) {
992
- var _this = _super.call(this) || this;
993
- _this.envObject = envObject;
994
- _this._refcount = initialRefcount;
995
- _this._ownership = ownership;
996
- var handle = envObject.ctx.handleStore.get(handle_id);
997
- _this.canBeWeak = canBeHeldWeakly(handle);
998
- _this.persistent = new Persistent(handle.value);
999
- _this.id = 0;
1000
- if (initialRefcount === 0) {
1001
- _this._setWeak();
1002
- }
1003
- return _this;
322
+ //#endregion src/RefTracker.ts
323
+
324
+ //#region src/Finalizer.ts
325
+ class Finalizer {
326
+ constructor(envObject, _finalizeCallback = 0, _finalizeData = 0, _finalizeHint = 0) {
327
+ this.envObject = envObject;
328
+ this._finalizeCallback = _finalizeCallback;
329
+ this._finalizeData = _finalizeData;
330
+ this._finalizeHint = _finalizeHint;
331
+ this._makeDynCall_vppp = envObject.bridge.makeDynCall_vppp;
332
+ }
333
+ copy() {
334
+ const newFina = Object.create(Finalizer.prototype);
335
+ newFina.envObject = this.envObject;
336
+ newFina._makeDynCall_vppp = this._makeDynCall_vppp;
337
+ newFina._finalizeCallback = this._finalizeCallback;
338
+ newFina._finalizeData = this._finalizeData;
339
+ newFina._finalizeHint = this._finalizeHint;
340
+ return newFina;
341
+ }
342
+ move(target) {
343
+ target._finalizeCallback = this._finalizeCallback;
344
+ target._finalizeData = this._finalizeData;
345
+ target._finalizeHint = this._finalizeHint;
346
+ target.envObject = this.envObject;
347
+ target._makeDynCall_vppp = this._makeDynCall_vppp;
348
+ this._finalizeCallback = 0;
349
+ this._finalizeData = 0;
350
+ this._finalizeHint = 0;
351
+ this.dispose();
352
+ }
353
+ callback() { return this._finalizeCallback; }
354
+ data() { return this._finalizeData; }
355
+ hint() { return this._finalizeHint; }
356
+ resetEnv() {
357
+ this.envObject = undefined;
358
+ }
359
+ resetFinalizer() {
360
+ this._finalizeCallback = 0;
361
+ this._finalizeData = 0;
362
+ this._finalizeHint = 0;
363
+ }
364
+ callFinalizer() {
365
+ const finalize_callback = this._finalizeCallback;
366
+ const finalize_data = this._finalizeData;
367
+ const finalize_hint = this._finalizeHint;
368
+ this.resetFinalizer();
369
+ if (!finalize_callback)
370
+ return;
371
+ const fini = Number(finalize_callback);
372
+ if (!this.envObject) {
373
+ this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint);
1004
374
  }
1005
- Reference.weakCallback = function (ref) {
1006
- ref.persistent.reset();
1007
- ref.invokeFinalizerFromGC();
1008
- };
1009
- Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) {
1010
- var ref = new Reference(envObject, handle_id, initialRefcount, ownership);
1011
- envObject.ctx.refStore.add(ref);
1012
- ref.link(envObject.reflist);
1013
- return ref;
1014
- };
1015
- Reference.prototype.ref = function () {
1016
- if (this.persistent.isEmpty()) {
1017
- return 0;
1018
- }
1019
- if (++this._refcount === 1 && this.canBeWeak) {
1020
- this.persistent.clearWeak();
1021
- }
1022
- return this._refcount;
1023
- };
1024
- Reference.prototype.unref = function () {
1025
- if (this.persistent.isEmpty() || this._refcount === 0) {
1026
- return 0;
1027
- }
1028
- if (--this._refcount === 0) {
1029
- this._setWeak();
1030
- }
1031
- return this._refcount;
1032
- };
1033
- Reference.prototype.get = function (envObject) {
1034
- if (envObject === void 0) { envObject = this.envObject; }
1035
- if (this.persistent.isEmpty()) {
1036
- return 0;
1037
- }
1038
- var obj = this.persistent.deref();
1039
- var handle = envObject.ensureHandle(obj);
1040
- return handle.id;
1041
- };
1042
- /** @virtual */
1043
- Reference.prototype.resetFinalizer = function () { };
1044
- /** @virtual */
1045
- Reference.prototype.data = function () { return 0; };
1046
- Reference.prototype.refcount = function () { return this._refcount; };
1047
- Reference.prototype.ownership = function () { return this._ownership; };
1048
- /** @virtual */
1049
- Reference.prototype.callUserFinalizer = function () { };
1050
- /** @virtual */
1051
- Reference.prototype.invokeFinalizerFromGC = function () {
1052
- this.finalize();
1053
- };
1054
- Reference.prototype._setWeak = function () {
1055
- if (this.canBeWeak) {
1056
- this.persistent.setWeak(this, Reference.weakCallback);
1057
- }
1058
- else {
1059
- this.persistent.reset();
1060
- }
1061
- };
1062
- Reference.prototype.finalize = function () {
1063
- this.persistent.reset();
1064
- var deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime;
1065
- this.unlink();
1066
- this.callUserFinalizer();
1067
- if (deleteMe) {
1068
- this.dispose();
1069
- }
1070
- };
1071
- Reference.prototype.dispose = function () {
1072
- if (this.id === 0)
1073
- return;
1074
- this.unlink();
1075
- this.persistent.reset();
1076
- this.envObject.ctx.refStore.remove(this.id);
1077
- _super.prototype.dispose.call(this);
1078
- this.envObject = undefined;
1079
- this.id = 0;
1080
- };
1081
- return Reference;
1082
- }(RefTracker));
1083
- var ReferenceWithData = /*#__PURE__*/ (function (_super) {
1084
- __extends(ReferenceWithData, _super);
1085
- function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) {
1086
- var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this;
1087
- _this._data = _data;
1088
- return _this;
1089
- }
1090
- ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) {
1091
- var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data);
1092
- envObject.ctx.refStore.add(reference);
1093
- reference.link(envObject.reflist);
1094
- return reference;
1095
- };
1096
- ReferenceWithData.prototype.data = function () {
1097
- return this._data;
1098
- };
1099
- return ReferenceWithData;
1100
- }(Reference));
1101
- var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) {
1102
- __extends(ReferenceWithFinalizer, _super);
1103
- function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) {
1104
- var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this;
1105
- _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint);
1106
- return _this;
1107
- }
1108
- ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) {
1109
- var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint);
1110
- envObject.ctx.refStore.add(reference);
1111
- reference.link(envObject.finalizing_reflist);
1112
- return reference;
1113
- };
1114
- ReferenceWithFinalizer.prototype.resetFinalizer = function () {
1115
- this._finalizer.resetFinalizer();
1116
- };
1117
- ReferenceWithFinalizer.prototype.data = function () {
1118
- return this._finalizer.data();
1119
- };
1120
- ReferenceWithFinalizer.prototype.callUserFinalizer = function () {
375
+ else {
376
+ this.envObject.callFinalizer(fini, finalize_data, finalize_hint);
377
+ }
378
+ }
379
+ dispose() {
380
+ this.envObject = undefined;
381
+ this._makeDynCall_vppp = undefined;
382
+ }
383
+ }
384
+
385
+ //#endregion src/Finalizer.ts
386
+
387
+ //#region src/TrackedFinalizer.ts
388
+ class TrackedFinalizer extends RefTracker {
389
+ static create(envObject, finalize_callback, finalize_data, finalize_hint) {
390
+ const finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint);
391
+ finalizer.link(envObject.finalizing_reflist);
392
+ return finalizer;
393
+ }
394
+ constructor(envObject, finalize_callback, finalize_data, finalize_hint) {
395
+ super();
396
+ this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint);
397
+ }
398
+ data() {
399
+ return this._finalizer.data();
400
+ }
401
+ dispose() {
402
+ if (!this._finalizer)
403
+ return;
404
+ this.unlink();
405
+ this._finalizer.envObject.dequeueFinalizer(this);
406
+ this._finalizer.dispose();
407
+ this._finalizer = undefined;
408
+ super.dispose();
409
+ }
410
+ finalize() {
411
+ this.unlink();
412
+ let error;
413
+ let caught = false;
414
+ try {
1121
415
  this._finalizer.callFinalizer();
1122
- };
1123
- ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () {
1124
- this._finalizer.envObject.invokeFinalizerFromGC(this);
1125
- };
1126
- ReferenceWithFinalizer.prototype.dispose = function () {
1127
- if (!this._finalizer)
1128
- return;
1129
- this._finalizer.envObject.dequeueFinalizer(this);
1130
- this._finalizer.dispose();
1131
- _super.prototype.dispose.call(this);
1132
- this._finalizer = undefined;
1133
- };
1134
- return ReferenceWithFinalizer;
1135
- }(Reference));
416
+ }
417
+ catch (err) {
418
+ caught = true;
419
+ error = err;
420
+ }
421
+ this.dispose();
422
+ if (caught) {
423
+ throw error;
424
+ }
425
+ }
426
+ }
1136
427
 
1137
- var Deferred = /*#__PURE__*/ (function () {
1138
- function Deferred(ctx, value) {
1139
- this.id = 0;
1140
- this.ctx = ctx;
1141
- this.value = value;
1142
- }
1143
- Deferred.create = function (ctx, value) {
1144
- var deferred = new Deferred(ctx, value);
1145
- ctx.deferredStore.add(deferred);
1146
- return deferred;
1147
- };
1148
- Deferred.prototype.resolve = function (value) {
1149
- this.value.resolve(value);
1150
- this.dispose();
1151
- };
1152
- Deferred.prototype.reject = function (reason) {
1153
- this.value.reject(reason);
1154
- this.dispose();
1155
- };
1156
- Deferred.prototype.dispose = function () {
1157
- this.ctx.deferredStore.remove(this.id);
1158
- this.id = 0;
1159
- this.value = null;
1160
- this.ctx = null;
1161
- };
1162
- return Deferred;
1163
- }());
428
+ //#endregion src/TrackedFinalizer.ts
429
+
430
+ //#region src/Store.ts
431
+ class CountIdAllocator extends Disposable {
432
+ constructor(initialNext = 1) {
433
+ super();
434
+ this.next = initialNext;
435
+ }
436
+ aquire() {
437
+ return this.next++;
438
+ }
439
+ release(_) { }
440
+ dispose() { }
441
+ }
442
+ class CountIdReuseAllocator extends CountIdAllocator {
443
+ constructor() {
444
+ super(...arguments);
445
+ this._freeList = [];
446
+ }
447
+ aquire() {
448
+ if (this._freeList.length) {
449
+ return this._freeList.shift();
450
+ }
451
+ return super.aquire();
452
+ }
453
+ release(id) {
454
+ this._freeList.push(id);
455
+ }
456
+ dispose() {
457
+ this._freeList.length = 0;
458
+ super.dispose();
459
+ }
460
+ }
461
+ class BaseArrayStore extends Disposable {
462
+ constructor(initialCapacity = 1) {
463
+ super();
464
+ this._values = Array(initialCapacity);
465
+ }
466
+ assign(id, value) {
467
+ this._values[id] = value;
468
+ return value;
469
+ }
470
+ deref(id) {
471
+ return this._values[id];
472
+ }
473
+ alloc(factory, ...args) {
474
+ return factory(...args);
475
+ }
476
+ dealloc(id) {
477
+ this._values[id] = undefined;
478
+ }
479
+ dispose() {
480
+ this._values.forEach((_, i) => this.dealloc(i));
481
+ }
482
+ }
483
+ class ArrayStore extends BaseArrayStore {
484
+ constructor(initialCapacity = 4) {
485
+ super(initialCapacity);
486
+ this._allocator = new CountIdReuseAllocator(1);
487
+ }
488
+ insert(value) {
489
+ const id = this._allocator.aquire();
490
+ while (id >= this._values.length) {
491
+ const cap = this._values.length;
492
+ this._values.length = cap + (cap >> 1) + 16;
493
+ }
494
+ value.id = id;
495
+ this._values[id] = value;
496
+ }
497
+ alloc(factory, ...args) {
498
+ const value = factory(...args);
499
+ this.insert(value);
500
+ return value;
501
+ }
502
+ dealloc(id) {
503
+ this._allocator.release(id);
504
+ super.dealloc(id);
505
+ }
506
+ }
507
+
508
+ //#endregion src/Store.ts
1164
509
 
1165
- var Store = /*#__PURE__*/ (function () {
1166
- function Store() {
1167
- this._values = [undefined];
1168
- this._values.length = 4;
1169
- this._size = 1;
1170
- this._freeList = [];
1171
- }
1172
- Store.prototype.add = function (value) {
1173
- var id;
1174
- if (this._freeList.length) {
1175
- id = this._freeList.shift();
510
+ //#region src/Persistent.ts
511
+ class PersistentStore extends ArrayStore {
512
+ constructor(initialCapacity = 4) {
513
+ super(initialCapacity);
514
+ this._recyleList = [];
515
+ }
516
+ markUnused(id) {
517
+ this._recyleList.push(id);
518
+ }
519
+ recycle() {
520
+ while (this._recyleList.length > 0) {
521
+ const id = this._recyleList.shift();
522
+ const persistent = this.deref(id);
523
+ persistent.dispose();
524
+ }
525
+ }
526
+ }
527
+ class StrongRef extends Disposable {
528
+ constructor(value) {
529
+ super();
530
+ this._value = value;
531
+ }
532
+ deref() {
533
+ return this._value;
534
+ }
535
+ dispose() {
536
+ this._value = undefined;
537
+ }
538
+ }
539
+ class Persistent extends Disposable {
540
+ constructor(isolate, ...args) {
541
+ super();
542
+ this.id = 0;
543
+ this._isolate = isolate;
544
+ isolate.insertRef(this);
545
+ this.setSlot(args.length === 0 ? undefined : new StrongRef(args[0]));
546
+ }
547
+ dispose() {
548
+ this.reset();
549
+ this.deleteSlot();
550
+ this._isolate.globalHandleStore.dealloc(this.id);
551
+ this._isolate = undefined;
552
+ this.id = 0;
553
+ }
554
+ copy() {
555
+ const target = new Persistent(this._isolate);
556
+ target._param = this._param;
557
+ target._callback = this._callback;
558
+ const ref = this.getSlot();
559
+ if (ref instanceof StrongRef) {
560
+ target.setSlot(new StrongRef(ref.deref()));
561
+ }
562
+ else if (ref instanceof WeakRef) {
563
+ const value = ref.deref();
564
+ if (value === undefined) {
565
+ target.setSlot(undefined);
1176
566
  }
1177
567
  else {
1178
- id = this._size;
1179
- this._size++;
1180
- var capacity = this._values.length;
1181
- if (id >= capacity) {
1182
- this._values.length = capacity + (capacity >> 1) + 16;
1183
- }
568
+ target.setSlot(new StrongRef(value));
569
+ target.setWeak(this._param, this._callback);
1184
570
  }
1185
- value.id = id;
1186
- this._values[id] = value;
1187
- };
1188
- Store.prototype.get = function (id) {
1189
- return this._values[id];
1190
- };
1191
- Store.prototype.has = function (id) {
1192
- return this._values[id] !== undefined;
1193
- };
1194
- Store.prototype.remove = function (id) {
1195
- var value = this._values[id];
1196
- if (value) {
1197
- value.id = 0;
1198
- this._values[id] = undefined;
1199
- this._freeList.push(Number(id));
571
+ }
572
+ else {
573
+ target.setSlot(undefined);
574
+ }
575
+ return target;
576
+ }
577
+ move(to) {
578
+ if (this === to)
579
+ return;
580
+ to.reset();
581
+ to._param = this._param;
582
+ to._callback = this._callback;
583
+ to._isolate = this._isolate;
584
+ to.setSlot(this.getSlot());
585
+ this.reset();
586
+ this.setSlot(undefined);
587
+ }
588
+ slot() {
589
+ return 0x80000000 + this.id;
590
+ }
591
+ getSlot() {
592
+ return this._isolate.getRefSlotValue(this.slot());
593
+ }
594
+ setSlot(ref) {
595
+ this._isolate.setRefSlotValue(this.slot(), ref);
596
+ }
597
+ deleteSlot() {
598
+ this._isolate.deleteRefSlotValue(this.slot());
599
+ }
600
+ setWeak(param, callback) {
601
+ const ref = this.getSlot();
602
+ if (!supportFinalizer || ref === undefined || ref instanceof WeakRef)
603
+ return;
604
+ const value = ref.deref();
605
+ try {
606
+ Persistent._registry.register(value, this, this);
607
+ const weakRef = new WeakRef(value);
608
+ ref.dispose();
609
+ this.setSlot(weakRef);
610
+ this._param = param;
611
+ this._callback = callback;
612
+ }
613
+ catch (err) {
614
+ if (typeof value === 'symbol') ;
615
+ else {
616
+ throw err;
1200
617
  }
1201
- };
1202
- Store.prototype.dispose = function () {
1203
- for (var i = 1; i < this._size; ++i) {
1204
- var value = this._values[i];
1205
- value === null || value === void 0 ? void 0 : value.dispose();
618
+ }
619
+ }
620
+ clearWeak() {
621
+ const ref = this.getSlot();
622
+ if (!supportFinalizer || ref === undefined)
623
+ return;
624
+ if (ref instanceof WeakRef) {
625
+ try {
626
+ Persistent._registry.unregister(this);
1206
627
  }
1207
- this._values = [undefined];
1208
- this._size = 1;
1209
- this._freeList = [];
1210
- };
1211
- return Store;
1212
- }());
1213
-
1214
- var kMaxReasonableBytes = BigInt(1) << BigInt(60);
1215
- var kMinReasonableBytes = -kMaxReasonableBytes;
1216
- var ExternalMemory = /*#__PURE__*/ (function () {
1217
- function ExternalMemory(onChange) {
1218
- this.total = BigInt(0);
1219
- this.onChange = onChange !== null && onChange !== void 0 ? onChange : null;
1220
- }
1221
- ExternalMemory.prototype.adjust = function (changeInBytes) {
1222
- changeInBytes = BigInt(changeInBytes);
1223
- if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) {
1224
- throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range"));
628
+ catch (_) { }
629
+ this._param = undefined;
630
+ this._callback = undefined;
631
+ const value = ref.deref();
632
+ if (value === undefined) {
633
+ this.setSlot(value);
1225
634
  }
1226
- var old = this.total;
1227
- this.total += changeInBytes;
1228
- var amount = this.total;
1229
- var onChange = this.onChange;
1230
- if (changeInBytes) {
1231
- onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes);
635
+ else {
636
+ this.setSlot(new StrongRef(value));
1232
637
  }
1233
- return amount;
1234
- };
1235
- return ExternalMemory;
1236
- }());
638
+ }
639
+ }
640
+ reset() {
641
+ if (supportFinalizer) {
642
+ try {
643
+ Persistent._registry.unregister(this);
644
+ }
645
+ catch (_) { }
646
+ }
647
+ this._param = undefined;
648
+ this._callback = undefined;
649
+ const ref = this.getSlot();
650
+ if (ref instanceof StrongRef) {
651
+ ref.dispose();
652
+ }
653
+ this.setSlot(undefined);
654
+ }
655
+ resetTo(value) {
656
+ this.reset();
657
+ this.setSlot(new StrongRef(value));
658
+ }
659
+ isEmpty() {
660
+ return this.getSlot() === undefined;
661
+ }
662
+ deref() {
663
+ const ref = this.getSlot();
664
+ if (ref === undefined)
665
+ return undefined;
666
+ return ref.deref();
667
+ }
668
+ }
669
+ Persistent._registry = supportFinalizer
670
+ ? new FinalizationRegistry((value) => {
671
+ value.setSlot(undefined);
672
+ const callback = value._callback;
673
+ const param = value._param;
674
+ value._callback = undefined;
675
+ value._param = undefined;
676
+ if (typeof callback === 'function') {
677
+ callback(param);
678
+ }
679
+ })
680
+ : undefined;
1237
681
 
1238
- var CleanupHookCallback = /*#__PURE__*/ (function () {
1239
- function CleanupHookCallback(envObject, fn, arg, order) {
1240
- this.envObject = envObject;
1241
- this.fn = fn;
1242
- this.arg = arg;
1243
- this.order = order;
1244
- }
1245
- return CleanupHookCallback;
1246
- }());
1247
- var CleanupQueue = /*#__PURE__*/ (function () {
1248
- function CleanupQueue() {
1249
- this._cleanupHooks = [];
1250
- this._cleanupHookCounter = 0;
1251
- }
1252
- CleanupQueue.prototype.empty = function () {
1253
- return this._cleanupHooks.length === 0;
1254
- };
1255
- CleanupQueue.prototype.add = function (envObject, fn, arg) {
1256
- if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) {
1257
- throw new Error('Can not add same fn and arg twice');
682
+ //#endregion src/Persistent.ts
683
+
684
+ //#region src/env.ts
685
+ function handleThrow(envObject, value) {
686
+ if (envObject.terminatedOrTerminating()) {
687
+ return;
688
+ }
689
+ throw value;
690
+ }
691
+ class Env extends Disposable {
692
+ constructor(ctx, store, bridge) {
693
+ super();
694
+ this.openHandleScopes = 0;
695
+ this.instanceData = null;
696
+ this.refs = 1;
697
+ this.reflist = new RefTracker();
698
+ this.finalizing_reflist = new RefTracker();
699
+ this.pendingFinalizers = [];
700
+ this.inGcFinalizer = false;
701
+ this._bindingMap = new WeakMap();
702
+ this.ctx = ctx;
703
+ this.store = store;
704
+ this.id = 0;
705
+ this.store.insert(this);
706
+ this.lastException = new Persistent(ctx.isolate);
707
+ this.bridge = bridge;
708
+ }
709
+ canCallIntoJs() {
710
+ return true;
711
+ }
712
+ terminatedOrTerminating() {
713
+ return !this.canCallIntoJs();
714
+ }
715
+ ref() {
716
+ this.refs++;
717
+ }
718
+ unref() {
719
+ this.refs--;
720
+ if (this.refs === 0) {
721
+ this.dispose();
722
+ }
723
+ }
724
+ clearLastError() {
725
+ this.bridge.setLastError(this.bridge.address, 0, 0, 0);
726
+ return 0;
727
+ }
728
+ setLastError(error_code, engine_error_code = 0, engine_reserved = 0) {
729
+ this.bridge.setLastError(this.bridge.address, error_code, engine_error_code, engine_reserved);
730
+ return error_code;
731
+ }
732
+ callIntoModule(fn, handleException = handleThrow) {
733
+ const openHandleScopesBefore = this.openHandleScopes;
734
+ this.clearLastError();
735
+ const r = fn(this);
736
+ if (openHandleScopesBefore !== this.openHandleScopes) {
737
+ this.bridge.abort('open_handle_scopes != open_handle_scopes_before');
738
+ }
739
+ if (!this.lastException.isEmpty()) {
740
+ const err = this.lastException.deref();
741
+ this.lastException.reset();
742
+ handleException(this, err);
743
+ }
744
+ return r;
745
+ }
746
+ invokeFinalizerFromGC(finalizer) {
747
+ if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) {
748
+ this.enqueueFinalizer(finalizer);
749
+ }
750
+ else {
751
+ const saved = this.inGcFinalizer;
752
+ this.inGcFinalizer = true;
753
+ try {
754
+ finalizer.finalize();
1258
755
  }
1259
- this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++));
1260
- };
1261
- CleanupQueue.prototype.remove = function (envObject, fn, arg) {
1262
- for (var i = 0; i < this._cleanupHooks.length; ++i) {
1263
- var hook = this._cleanupHooks[i];
1264
- if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) {
1265
- this._cleanupHooks.splice(i, 1);
1266
- return;
1267
- }
756
+ finally {
757
+ this.inGcFinalizer = saved;
1268
758
  }
759
+ }
760
+ }
761
+ checkGCAccess() {
762
+ if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) {
763
+ this.bridge.abort('Finalizer is calling a function that may affect GC state.\n' +
764
+ 'The finalizers are run directly from GC and must not affect GC ' +
765
+ 'state.\n' +
766
+ 'Use `node_api_post_finalizer` from inside of the finalizer to work ' +
767
+ 'around this issue.\n' +
768
+ 'It schedules the call as a new task in the event loop.');
769
+ }
770
+ }
771
+ enqueueFinalizer(finalizer) {
772
+ if (this.pendingFinalizers.indexOf(finalizer) === -1) {
773
+ this.pendingFinalizers.push(finalizer);
774
+ }
775
+ }
776
+ dequeueFinalizer(finalizer) {
777
+ const index = this.pendingFinalizers.indexOf(finalizer);
778
+ if (index !== -1) {
779
+ this.pendingFinalizers.splice(index, 1);
780
+ }
781
+ }
782
+ deleteMe() {
783
+ RefTracker.finalizeAll(this.finalizing_reflist);
784
+ RefTracker.finalizeAll(this.reflist);
785
+ this.lastException.reset();
786
+ this.store.dealloc(this.id);
787
+ this.bridge.deleteEnv(this.bridge.address);
788
+ }
789
+ dispose() {
790
+ if (this.id === 0)
791
+ return;
792
+ this.deleteMe();
793
+ this.finalizing_reflist.dispose();
794
+ this.reflist.dispose();
795
+ this.id = 0;
796
+ }
797
+ initObjectBinding(value) {
798
+ const binding = {
799
+ wrapped: 0,
800
+ tag: null
1269
801
  };
1270
- CleanupQueue.prototype.drain = function () {
1271
- var hooks = this._cleanupHooks.slice();
1272
- hooks.sort(function (a, b) { return (b.order - a.order); });
1273
- for (var i = 0; i < hooks.length; ++i) {
1274
- var cb = hooks[i];
1275
- if (typeof cb.fn === 'number') {
1276
- cb.envObject.makeDynCall_vp(cb.fn)(cb.arg);
1277
- }
1278
- else {
1279
- cb.fn(cb.arg);
802
+ this._bindingMap.set(value, binding);
803
+ return binding;
804
+ }
805
+ getObjectBinding(value) {
806
+ if (this._bindingMap.has(value)) {
807
+ return this._bindingMap.get(value);
808
+ }
809
+ return this.initObjectBinding(value);
810
+ }
811
+ setInstanceData(data, finalize_cb, finalize_hint) {
812
+ if (this.instanceData) {
813
+ this.instanceData.dispose();
814
+ }
815
+ this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint);
816
+ }
817
+ getInstanceData() {
818
+ return this.instanceData ? this.instanceData.data() : 0;
819
+ }
820
+ }
821
+ class NodeEnv extends Env {
822
+ constructor(ctx, store, bridge) {
823
+ super(ctx, store, bridge);
824
+ this.destructing = false;
825
+ this.finalizationScheduled = false;
826
+ this.bridge = bridge;
827
+ }
828
+ deleteMe() {
829
+ this.destructing = true;
830
+ this.drainFinalizerQueue();
831
+ super.deleteMe();
832
+ }
833
+ canCallIntoJs() {
834
+ return super.canCallIntoJs() && this.ctx.canCallIntoJs();
835
+ }
836
+ triggerFatalException(err) {
837
+ if (this.nodeBinding) {
838
+ this.nodeBinding.napi.fatalException(err);
839
+ }
840
+ else {
841
+ if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') {
842
+ const handled = process._fatalException(err);
843
+ if (!handled) {
844
+ console.error(err);
845
+ process.exit(1);
1280
846
  }
1281
- this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1);
1282
847
  }
1283
- };
1284
- CleanupQueue.prototype.dispose = function () {
1285
- this._cleanupHooks.length = 0;
1286
- this._cleanupHookCounter = 0;
1287
- };
1288
- return CleanupQueue;
1289
- }());
1290
- var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () {
1291
- function NodejsWaitingRequestCounter() {
1292
- this.refHandle = new _MessageChannel().port1;
1293
- this.count = 0;
1294
- }
1295
- NodejsWaitingRequestCounter.prototype.increase = function () {
1296
- if (this.count === 0) {
1297
- if (this.refHandle.ref) {
1298
- this.refHandle.ref();
1299
- }
848
+ else {
849
+ throw err;
1300
850
  }
1301
- this.count++;
1302
- };
1303
- NodejsWaitingRequestCounter.prototype.decrease = function () {
1304
- if (this.count === 0)
851
+ }
852
+ }
853
+ callbackIntoModule(enforceUncaughtExceptionPolicy, fn) {
854
+ return this.callIntoModule(fn, (envObject, err) => {
855
+ if (envObject.terminatedOrTerminating()) {
1305
856
  return;
1306
- if (this.count === 1) {
1307
- if (this.refHandle.unref) {
1308
- this.refHandle.unref();
1309
- }
1310
857
  }
1311
- this.count--;
1312
- };
1313
- return NodejsWaitingRequestCounter;
1314
- }());
1315
- var Context = /*#__PURE__*/ (function () {
1316
- function Context(options) {
1317
- var _this = this;
1318
- this._isStopping = false;
1319
- this._canCallIntoJs = true;
1320
- this._suppressDestroy = false;
1321
- this.envStore = new Store();
1322
- this.scopeStore = new ScopeStore();
1323
- this.refStore = new Store();
1324
- this.deferredStore = new Store();
1325
- this.handleStore = new HandleStore();
1326
- this.feature = {
1327
- supportReflect: supportReflect,
1328
- supportFinalizer: supportFinalizer,
1329
- supportWeakSymbol: supportWeakSymbol,
1330
- supportBigInt: supportBigInt,
1331
- supportNewFunction: supportNewFunction,
1332
- canSetFunctionName: canSetFunctionName,
1333
- setImmediate: _setImmediate,
1334
- Buffer: _Buffer,
1335
- MessageChannel: _MessageChannel
1336
- };
1337
- this.cleanupQueue = new CleanupQueue();
1338
- this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange);
1339
- if (typeof process === 'object' && process !== null && typeof process.once === 'function') {
1340
- this.refCounter = new NodejsWaitingRequestCounter();
1341
- process.once('beforeExit', function () {
1342
- if (!_this._suppressDestroy) {
1343
- _this.destroy();
1344
- }
1345
- });
858
+ const hasProcess = typeof process === 'object' && process !== null;
859
+ const hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false;
860
+ if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) {
861
+ const warn = hasProcess && typeof process.emitWarning === 'function'
862
+ ? process.emitWarning
863
+ : function (warning, type, code) {
864
+ if (warning instanceof Error) {
865
+ console.warn(warning.toString());
866
+ }
867
+ else {
868
+ const prefix = code ? `[${code}] ` : '';
869
+ console.warn(`${prefix}${type || 'Warning'}: ${warning}`);
870
+ }
871
+ };
872
+ warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168');
873
+ return;
1346
874
  }
875
+ envObject.triggerFatalException(err);
876
+ });
877
+ }
878
+ callFinalizer(cb, data, hint) {
879
+ this.callFinalizerInternal(1, cb, data, hint);
880
+ }
881
+ callFinalizerInternal(forceUncaught, cb, data, hint) {
882
+ const f = this.bridge.makeDynCall_vppp(cb);
883
+ const env = this.bridge.address;
884
+ const scope = this.ctx.openScope(this);
885
+ try {
886
+ this.callbackIntoModule(Boolean(forceUncaught), () => { f(env, data, hint); });
1347
887
  }
1348
- /**
1349
- * Suppress the destroy on `beforeExit` event in Node.js.
1350
- * Call this method if you want to keep the context and
1351
- * all associated {@link Env | Env} alive,
1352
- * this also means that cleanup hooks will not be called.
1353
- * After call this method, you should call
1354
- * {@link Context.destroy | `Context.prototype.destroy`} method manually.
1355
- */
1356
- Context.prototype.suppressDestroy = function () {
1357
- this._suppressDestroy = true;
1358
- };
1359
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
1360
- Context.prototype.getRuntimeVersions = function () {
1361
- return {
1362
- version: version,
1363
- NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX,
1364
- NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL,
1365
- NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION
1366
- };
1367
- };
1368
- Context.prototype.createNotSupportWeakRefError = function (api, message) {
1369
- return new NotSupportWeakRefError(api, message);
1370
- };
1371
- Context.prototype.createNotSupportBufferError = function (api, message) {
1372
- return new NotSupportBufferError(api, message);
1373
- };
1374
- Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) {
1375
- return Reference.create(envObject, handle_id, initialRefcount, ownership);
1376
- };
1377
- Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) {
1378
- return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data);
1379
- };
1380
- Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) {
1381
- if (finalize_callback === void 0) { finalize_callback = 0; }
1382
- if (finalize_data === void 0) { finalize_data = 0; }
1383
- if (finalize_hint === void 0) { finalize_hint = 0; }
1384
- return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint);
1385
- };
1386
- Context.prototype.createDeferred = function (value) {
1387
- return Deferred.create(this, value);
1388
- };
1389
- Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) {
1390
- return this._externalMemory.adjust(changeInBytes);
1391
- };
1392
- Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) {
1393
- return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding);
1394
- };
1395
- Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) {
1396
- return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint);
1397
- };
1398
- Context.prototype.getCurrentScope = function () {
1399
- return this.scopeStore.currentScope;
1400
- };
1401
- Context.prototype.addToCurrentScope = function (value) {
1402
- return this.scopeStore.currentScope.add(value);
1403
- };
1404
- Context.prototype.openScope = function (envObject) {
1405
- var scope = this.scopeStore.openScope(this.handleStore);
1406
- if (envObject)
1407
- envObject.openHandleScopes++;
1408
- return scope;
1409
- };
1410
- Context.prototype.closeScope = function (envObject, _scope) {
1411
- if (envObject && envObject.openHandleScopes === 0)
1412
- return;
1413
- this.scopeStore.closeScope();
1414
- if (envObject)
1415
- envObject.openHandleScopes--;
1416
- };
1417
- Context.prototype.ensureHandle = function (value) {
1418
- switch (value) {
1419
- case undefined: return HandleStore.UNDEFINED;
1420
- case null: return HandleStore.NULL;
1421
- case true: return HandleStore.TRUE;
1422
- case false: return HandleStore.FALSE;
1423
- case _global: return HandleStore.GLOBAL;
888
+ finally {
889
+ this.ctx.closeScope(this, scope);
890
+ }
891
+ }
892
+ enqueueFinalizer(finalizer) {
893
+ super.enqueueFinalizer(finalizer);
894
+ if (!this.finalizationScheduled && !this.destructing) {
895
+ this.finalizationScheduled = true;
896
+ this.ref();
897
+ this.ctx.features.setImmediate(() => {
898
+ this.finalizationScheduled = false;
899
+ this.unref();
900
+ this.drainFinalizerQueue();
901
+ });
902
+ }
903
+ }
904
+ drainFinalizerQueue() {
905
+ while (this.pendingFinalizers.length > 0) {
906
+ const refTracker = this.pendingFinalizers.shift();
907
+ refTracker.finalize();
908
+ }
909
+ }
910
+ }
911
+
912
+ //#endregion src/env.ts
913
+
914
+ //#region src/errors.ts
915
+ class EmnapiError extends Error {
916
+ constructor(message) {
917
+ super(message);
918
+ const ErrorConstructor = new.target;
919
+ const proto = ErrorConstructor.prototype;
920
+ if (!(this instanceof EmnapiError)) {
921
+ const setPrototypeOf = Object.setPrototypeOf;
922
+ if (typeof setPrototypeOf === 'function') {
923
+ setPrototypeOf.call(Object, this, proto);
1424
924
  }
1425
- return this.addToCurrentScope(value);
1426
- };
1427
- Context.prototype.addCleanupHook = function (envObject, fn, arg) {
1428
- this.cleanupQueue.add(envObject, fn, arg);
1429
- };
1430
- Context.prototype.removeCleanupHook = function (envObject, fn, arg) {
1431
- this.cleanupQueue.remove(envObject, fn, arg);
1432
- };
1433
- Context.prototype.runCleanup = function () {
1434
- while (!this.cleanupQueue.empty()) {
1435
- this.cleanupQueue.drain();
925
+ else {
926
+ this.__proto__ = proto;
1436
927
  }
1437
- };
1438
- Context.prototype.increaseWaitingRequestCounter = function () {
1439
- var _a;
1440
- (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase();
1441
- };
1442
- Context.prototype.decreaseWaitingRequestCounter = function () {
1443
- var _a;
1444
- (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease();
1445
- };
1446
- Context.prototype.setCanCallIntoJs = function (value) {
1447
- this._canCallIntoJs = value;
1448
- };
1449
- Context.prototype.setStopping = function (value) {
1450
- this._isStopping = value;
1451
- };
1452
- Context.prototype.canCallIntoJs = function () {
1453
- return this._canCallIntoJs && !this._isStopping;
1454
- };
1455
- /**
1456
- * Destroy the context and call cleanup hooks.
1457
- * Associated {@link Env | Env} will be destroyed.
1458
- */
1459
- Context.prototype.destroy = function () {
1460
- this.setStopping(true);
1461
- this.setCanCallIntoJs(false);
1462
- this.runCleanup();
1463
- };
1464
- return Context;
1465
- }());
1466
- var defaultContext;
1467
- function createContext(options) {
1468
- return new Context(options);
928
+ if (typeof Error.captureStackTrace === 'function') {
929
+ Error.captureStackTrace(this, ErrorConstructor);
930
+ }
931
+ }
932
+ }
933
+ }
934
+ Object.defineProperty(EmnapiError.prototype, 'name', {
935
+ configurable: true,
936
+ writable: true,
937
+ value: 'EmnapiError'
938
+ });
939
+ class NotSupportWeakRefError extends EmnapiError {
940
+ constructor(api, message) {
941
+ super(`${api}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${message ? ` ${message}` : ''}`);
942
+ }
943
+ }
944
+ Object.defineProperty(NotSupportWeakRefError.prototype, 'name', {
945
+ configurable: true,
946
+ writable: true,
947
+ value: 'NotSupportWeakRefError'
948
+ });
949
+ class NotSupportBufferError extends EmnapiError {
950
+ constructor(api, message) {
951
+ super(`${api}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${message ? ` ${message}` : ''}`);
952
+ }
953
+ }
954
+ Object.defineProperty(NotSupportBufferError.prototype, 'name', {
955
+ configurable: true,
956
+ writable: true,
957
+ value: 'NotSupportBufferError'
958
+ });
959
+
960
+ //#endregion src/errors.ts
961
+
962
+ //#region src/Reference.ts
963
+ var ReferenceOwnership;
964
+ (function (ReferenceOwnership) {
965
+ ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime";
966
+ ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland";
967
+ })(ReferenceOwnership || (ReferenceOwnership = {}));
968
+ function canBeHeldWeakly(value) {
969
+ if (!value)
970
+ return false;
971
+ const type = typeof value;
972
+ return type === 'object' || type === 'function' || type === 'symbol';
973
+ }
974
+ class Reference extends RefTracker {
975
+ static weakCallback(ref) {
976
+ const persistent = ref.getPersistent();
977
+ persistent.reset();
978
+ ref.invokeFinalizerFromGC();
979
+ }
980
+ static create(ctx, envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) {
981
+ const ref = new Reference(ctx, envObject, handle_id, initialRefcount, ownership);
982
+ if (envObject) {
983
+ ref.link(envObject.reflist);
984
+ }
985
+ return ref;
1469
986
  }
1470
- function getDefaultContext() {
1471
- if (!defaultContext) {
1472
- defaultContext = createContext();
987
+ constructor(ctx, envObject, handle_id, initialRefcount, ownership) {
988
+ super();
989
+ this.envObject = envObject;
990
+ this._refcount = initialRefcount;
991
+ this._ownership = ownership;
992
+ const value = envObject ? envObject.ctx.jsValueFromNapiValue(handle_id) : handle_id;
993
+ this.canBeWeak = canBeHeldWeakly(value);
994
+ this.ctx = ctx;
995
+ this.id = new Persistent(ctx.isolate, value).id;
996
+ ctx.refStore.set(this.id, this);
997
+ if (initialRefcount === 0) {
998
+ this._setWeak();
999
+ }
1000
+ }
1001
+ getPersistent() {
1002
+ return this.ctx.isolate.getRef(this.id);
1003
+ }
1004
+ ref() {
1005
+ const persistent = this.getPersistent();
1006
+ if (persistent.isEmpty()) {
1007
+ return 0;
1008
+ }
1009
+ if (++this._refcount === 1 && this.canBeWeak) {
1010
+ persistent.clearWeak();
1473
1011
  }
1474
- return defaultContext;
1012
+ return this._refcount;
1013
+ }
1014
+ unref() {
1015
+ const persistent = this.getPersistent();
1016
+ if (persistent.isEmpty() || this._refcount === 0) {
1017
+ return 0;
1018
+ }
1019
+ if (--this._refcount === 0) {
1020
+ this._setWeak();
1021
+ }
1022
+ return this._refcount;
1023
+ }
1024
+ deref() {
1025
+ const persistent = this.getPersistent();
1026
+ return persistent.deref();
1027
+ }
1028
+ get() {
1029
+ const persistent = this.getPersistent();
1030
+ if (persistent.isEmpty()) {
1031
+ return 0;
1032
+ }
1033
+ return persistent.slot();
1034
+ }
1035
+ resetFinalizer() { }
1036
+ data() { return 0; }
1037
+ refcount() { return this._refcount; }
1038
+ ownership() { return this._ownership; }
1039
+ callUserFinalizer() { }
1040
+ invokeFinalizerFromGC() {
1041
+ this.finalize();
1042
+ }
1043
+ _setWeak() {
1044
+ this.setWeakWithData(this, Reference.weakCallback);
1045
+ }
1046
+ setWeakWithData(data, callback) {
1047
+ const persistent = this.getPersistent();
1048
+ if (this.canBeWeak) {
1049
+ persistent.setWeak(data, callback);
1050
+ }
1051
+ else {
1052
+ persistent.reset();
1053
+ }
1054
+ }
1055
+ clearWeak() {
1056
+ const persistent = this.getPersistent();
1057
+ persistent.clearWeak();
1058
+ }
1059
+ finalize() {
1060
+ const persistent = this.getPersistent();
1061
+ persistent.reset();
1062
+ const deleteMe = this._ownership === ReferenceOwnership.kRuntime;
1063
+ this.unlink();
1064
+ this.callUserFinalizer();
1065
+ if (deleteMe) {
1066
+ this.dispose();
1067
+ }
1068
+ }
1069
+ dispose() {
1070
+ if (this.id === 0)
1071
+ return;
1072
+ this.unlink();
1073
+ this.ctx.isolate.removeRef(this.id);
1074
+ this.ctx.refStore.delete(this.id);
1075
+ super.dispose();
1076
+ this.ctx = undefined;
1077
+ this.envObject = undefined;
1078
+ this.id = 0;
1079
+ }
1080
+ }
1081
+ class ReferenceWithData extends Reference {
1082
+ static create(ctx, envObject, value, initialRefcount, ownership, data) {
1083
+ const reference = new ReferenceWithData(ctx, envObject, value, initialRefcount, ownership, data);
1084
+ if (envObject) {
1085
+ reference.link(envObject.reflist);
1086
+ }
1087
+ return reference;
1088
+ }
1089
+ constructor(ctx, envObject, value, initialRefcount, ownership, data) {
1090
+ super(ctx, envObject, value, initialRefcount, ownership);
1091
+ this._data = data;
1092
+ }
1093
+ data() {
1094
+ return this._data;
1095
+ }
1096
+ }
1097
+ class ReferenceWithFinalizer extends Reference {
1098
+ static create(ctx, envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) {
1099
+ if (!envObject) {
1100
+ throw new TypeError('envObject is required for ReferenceWithFinalizer');
1101
+ }
1102
+ const reference = new ReferenceWithFinalizer(ctx, envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint);
1103
+ reference.link(envObject.finalizing_reflist);
1104
+ return reference;
1105
+ }
1106
+ constructor(ctx, envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) {
1107
+ super(ctx, envObject, value, initialRefcount, ownership);
1108
+ this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint);
1109
+ }
1110
+ resetFinalizer() {
1111
+ this._finalizer.resetFinalizer();
1112
+ }
1113
+ data() {
1114
+ return this._finalizer.data();
1115
+ }
1116
+ callUserFinalizer() {
1117
+ this._finalizer.callFinalizer();
1118
+ }
1119
+ invokeFinalizerFromGC() {
1120
+ this._finalizer.envObject.invokeFinalizerFromGC(this);
1121
+ }
1122
+ dispose() {
1123
+ if (!this._finalizer)
1124
+ return;
1125
+ this._finalizer.envObject.dequeueFinalizer(this);
1126
+ this._finalizer.dispose();
1127
+ super.dispose();
1128
+ this._finalizer = undefined;
1129
+ }
1130
+ }
1131
+
1132
+ //#endregion src/Reference.ts
1133
+
1134
+ //#region src/Handle.ts
1135
+ class HandleStore extends BaseArrayStore {
1136
+ constructor(features) {
1137
+ super(HandleStore.MIN_ID);
1138
+ this._features = features;
1139
+ this._allocator = new CountIdAllocator(HandleStore.MIN_ID);
1140
+ this.refValues = new Map();
1141
+ this._values[2] = undefined;
1142
+ this._values[3] = null;
1143
+ this._values[4] = false;
1144
+ this._values[5] = true;
1145
+ this._values[6] = features.getGlobalThis();
1146
+ this._values[7] = '';
1147
+ const _erase = (start, end) => {
1148
+ for (let i = start; i < end; ++i) {
1149
+ this.dealloc(i);
1150
+ }
1151
+ };
1152
+ this._erase = this._features.finalizer
1153
+ ? this._features.weakSymbol
1154
+ ? (start, end, weak) => {
1155
+ if (!weak) {
1156
+ _erase(start, end);
1157
+ }
1158
+ else {
1159
+ for (let i = start; i < end; ++i) {
1160
+ const value = this._values[i];
1161
+ const type = typeof value;
1162
+ if ((type === 'object' && value !== null) || (type === 'function') || (type === 'symbol' && Symbol.keyFor(value) === undefined)) {
1163
+ this._values[i] = new WeakRef(value);
1164
+ }
1165
+ }
1166
+ }
1167
+ }
1168
+ : (start, end, weak) => {
1169
+ if (!weak) {
1170
+ _erase(start, end);
1171
+ }
1172
+ else {
1173
+ for (let i = start; i < end; ++i) {
1174
+ const value = this._values[i];
1175
+ const type = typeof value;
1176
+ if ((type === 'object' && value !== null) || (type === 'function')) {
1177
+ this._values[i] = new WeakRef(value);
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+ : _erase;
1183
+ this._deref = this._features.finalizer
1184
+ ? (id) => {
1185
+ id = Number(id);
1186
+ if (id < 0 || id > 0x7fffffff) {
1187
+ const ref = this.refValues.get(id >>> 0);
1188
+ if (ref === undefined)
1189
+ return undefined;
1190
+ return ref.deref();
1191
+ }
1192
+ const value = this._values[id];
1193
+ if (value instanceof WeakRef && this.isOutOfScope(id)) {
1194
+ return value.deref();
1195
+ }
1196
+ return value;
1197
+ }
1198
+ : (id) => {
1199
+ id = Number(id);
1200
+ if (id < 0 || id > 0x7fffffff) {
1201
+ const ref = this.refValues.get(id >>> 0);
1202
+ if (ref === undefined)
1203
+ return undefined;
1204
+ return ref.deref();
1205
+ }
1206
+ const value = this._values[id];
1207
+ return value;
1208
+ };
1209
+ }
1210
+ isOutOfScope(id) {
1211
+ return id >= this._allocator.next;
1212
+ }
1213
+ deepDeref(id) {
1214
+ return this._deref(id);
1215
+ }
1216
+ push(value) {
1217
+ const next = this._allocator.aquire();
1218
+ this._values[next] = value;
1219
+ return next;
1220
+ }
1221
+ erase(start, end, weak) {
1222
+ this._allocator.next = start;
1223
+ this._erase(start, end, weak);
1224
+ }
1225
+ swap(a, b) {
1226
+ const values = this._values;
1227
+ const h = values[a];
1228
+ values[a] = values[b];
1229
+ values[b] = h;
1230
+ }
1231
+ }
1232
+ HandleStore.MIN_ID = 8;
1233
+
1234
+ //#endregion src/Handle.ts
1235
+
1236
+ //#region src/External.ts
1237
+ const externalValue = new WeakMap();
1238
+ function isExternal(object) {
1239
+ return externalValue.has(object);
1240
+ }
1241
+ const External = (() => {
1242
+ function External(value) {
1243
+ Object.setPrototypeOf(this, null);
1244
+ externalValue.set(this, value);
1245
+ }
1246
+ External.prototype = null;
1247
+ return External;
1248
+ })();
1249
+ function getExternalValue(external) {
1250
+ if (!isExternal(external)) {
1251
+ throw new TypeError('not external');
1252
+ }
1253
+ return externalValue.get(external);
1254
+ }
1255
+
1256
+ //#endregion src/External.ts
1257
+
1258
+ //#region src/HandleScope.ts
1259
+ class HandleScope extends Disposable {
1260
+ static create(parentScope, handleStore, start = parentScope?.end ?? 1, end = start) {
1261
+ return new HandleScope(parentScope, handleStore, start, end);
1262
+ }
1263
+ constructor(parentScope, handleStore, start = parentScope?.end ?? 1, end = start) {
1264
+ super();
1265
+ this._escapeCalled = false;
1266
+ this.handleStore = handleStore;
1267
+ this.id = 0;
1268
+ this.parent = parentScope;
1269
+ this.child = null;
1270
+ if (parentScope !== null)
1271
+ parentScope.child = this;
1272
+ this.start = start;
1273
+ this.end = end;
1274
+ this.callbackInfo = {
1275
+ thiz: undefined,
1276
+ holder: undefined,
1277
+ data: 0,
1278
+ args: undefined,
1279
+ fn: undefined
1280
+ };
1281
+ }
1282
+ reuse(parentScope) {
1283
+ this.start = this.end = parentScope.end;
1284
+ this._escapeCalled = false;
1285
+ }
1286
+ add(value) {
1287
+ const h = this.handleStore.push(value);
1288
+ this.end = h + 1;
1289
+ return h;
1290
+ }
1291
+ addExternal(data) {
1292
+ return this.add(new External(data));
1293
+ }
1294
+ dispose() {
1295
+ const weak = this.callbackInfo.fn === undefined;
1296
+ if (!weak) {
1297
+ this.callbackInfo.data = 0;
1298
+ this.callbackInfo.args = undefined;
1299
+ this.callbackInfo.thiz = undefined;
1300
+ this.callbackInfo.holder = undefined;
1301
+ this.callbackInfo.fn = undefined;
1302
+ }
1303
+ if (this.start === this.end)
1304
+ return;
1305
+ this.handleStore.erase(this.start, this.end, weak);
1306
+ }
1307
+ escape(handle) {
1308
+ if (handle < this.start || handle >= this.end)
1309
+ return handle;
1310
+ if (this._escapeCalled)
1311
+ return 0;
1312
+ this._escapeCalled = true;
1313
+ if (handle < this.start || handle >= this.end) {
1314
+ return 0;
1315
+ }
1316
+ const id = this.start;
1317
+ this.handleStore.swap(handle, id);
1318
+ this.start++;
1319
+ this.parent.end++;
1320
+ return id;
1321
+ }
1322
+ escapeCalled() {
1323
+ return this._escapeCalled;
1324
+ }
1325
+ }
1326
+
1327
+ //#endregion src/HandleScope.ts
1328
+
1329
+ //#region src/ScopeStore.ts
1330
+ class ScopeStore extends BaseArrayStore {
1331
+ constructor() {
1332
+ super();
1333
+ this._rootScope = new HandleScope(null, null, 1, HandleStore.MIN_ID);
1334
+ this.currentScope = this._rootScope;
1335
+ }
1336
+ openScope(handleStore) {
1337
+ const currentScope = this.currentScope;
1338
+ let scope = currentScope.child;
1339
+ if (scope) {
1340
+ scope.reuse(currentScope);
1341
+ }
1342
+ else {
1343
+ scope = new HandleScope(currentScope, handleStore);
1344
+ const id = currentScope.id + 1;
1345
+ scope.id = id;
1346
+ this._values[id] = scope;
1347
+ }
1348
+ this.currentScope = scope;
1349
+ return scope;
1350
+ }
1351
+ closeScope() {
1352
+ const scope = this.currentScope;
1353
+ this.currentScope = scope.parent;
1354
+ scope.dispose();
1355
+ }
1356
+ isEmpty() {
1357
+ return this.currentScope === this._rootScope;
1358
+ }
1359
+ }
1360
+
1361
+ //#endregion src/ScopeStore.ts
1362
+
1363
+ //#region src/TryCatch.ts
1364
+ class TryCatch {
1365
+ constructor(id) {
1366
+ this.id = 0;
1367
+ this._exception = undefined;
1368
+ this._caught = false;
1369
+ this._next = null;
1370
+ this.id = id;
1371
+ this._next = TryCatch.top;
1372
+ TryCatch.top = this;
1373
+ TryCatch._map.set(id, this);
1374
+ }
1375
+ static deref(id) {
1376
+ return this._map.get(id);
1377
+ }
1378
+ static pop() {
1379
+ const top = TryCatch.top;
1380
+ if (top) {
1381
+ TryCatch._map.delete(top.id);
1382
+ TryCatch.top = top._next;
1383
+ top._next = null;
1384
+ top.id = 0;
1385
+ top._exception = undefined;
1386
+ top._caught = false;
1387
+ }
1388
+ }
1389
+ isEmpty() {
1390
+ return !this._caught;
1391
+ }
1392
+ hasCaught() {
1393
+ return this._caught;
1394
+ }
1395
+ exception() {
1396
+ return this._exception;
1397
+ }
1398
+ rethrow(ctx) {
1399
+ if (this._caught) {
1400
+ const e = this.extractException();
1401
+ ctx.setLastException(e);
1402
+ return e;
1403
+ }
1404
+ return undefined;
1405
+ }
1406
+ setError(err) {
1407
+ this._caught = true;
1408
+ this._exception = err;
1409
+ }
1410
+ reset() {
1411
+ this._caught = false;
1412
+ this._exception = undefined;
1413
+ }
1414
+ extractException() {
1415
+ const e = this._exception;
1416
+ this.reset();
1417
+ return e;
1418
+ }
1419
+ }
1420
+ TryCatch.top = null;
1421
+ TryCatch._map = new Map();
1422
+
1423
+ //#endregion src/TryCatch.ts
1424
+
1425
+ //#region src/Template.ts
1426
+ var PropertyAttribute;
1427
+ (function (PropertyAttribute) {
1428
+ PropertyAttribute[PropertyAttribute["None"] = 0] = "None";
1429
+ PropertyAttribute[PropertyAttribute["ReadOnly"] = 1] = "ReadOnly";
1430
+ PropertyAttribute[PropertyAttribute["DontEnum"] = 2] = "DontEnum";
1431
+ PropertyAttribute[PropertyAttribute["DontDelete"] = 4] = "DontDelete";
1432
+ })(PropertyAttribute || (PropertyAttribute = {}));
1433
+ class Template {
1434
+ constructor(ctx) {
1435
+ this._properties = new Map();
1436
+ this.ctx = ctx;
1437
+ }
1438
+ set(name, value, attr) {
1439
+ this._properties.set(name, [value, attr]);
1440
+ }
1441
+ _addPropertiesToInstance(instance) {
1442
+ this._properties.forEach((property, name) => {
1443
+ const [v, attr] = property;
1444
+ if (v instanceof Template) {
1445
+ if ('newInstance' in v) {
1446
+ Object.defineProperty(instance, name, {
1447
+ value: v.newInstance(6),
1448
+ writable: !(attr & 1),
1449
+ enumerable: !(attr & 2),
1450
+ configurable: !(attr & 4)
1451
+ });
1452
+ }
1453
+ else if ('getFunction' in v) {
1454
+ Object.defineProperty(instance, name, {
1455
+ value: v.getFunction(),
1456
+ writable: !(attr & 1),
1457
+ enumerable: !(attr & 2),
1458
+ configurable: !(attr & 4)
1459
+ });
1460
+ }
1461
+ }
1462
+ else {
1463
+ Object.defineProperty(instance, name, {
1464
+ value: v,
1465
+ writable: !(attr & 1),
1466
+ enumerable: !(attr & 2),
1467
+ configurable: !(attr & 4)
1468
+ });
1469
+ }
1470
+ });
1471
+ }
1472
+ }
1473
+
1474
+ //#endregion src/Template.ts
1475
+
1476
+ //#region src/ObjectTemplate.ts
1477
+ function findHolder(obj, _target) {
1478
+ return obj;
1479
+ }
1480
+ const internalField = new WeakMap();
1481
+ function getInternalFieldCount(instance) {
1482
+ return internalField.get(instance)?.length ?? 0;
1483
+ }
1484
+ function getInternalField(instance, index) {
1485
+ return internalField.get(instance)?.[index];
1486
+ }
1487
+ function setInternalField(instance, index, value) {
1488
+ let fields = internalField.get(instance);
1489
+ if (fields) {
1490
+ fields[index] = value;
1491
+ }
1492
+ else {
1493
+ fields = [];
1494
+ fields[index] = value;
1495
+ internalField.set(instance, fields);
1496
+ }
1497
+ }
1498
+ class ObjectTemplate extends Template {
1499
+ constructor(ctx, Ctor) {
1500
+ super(ctx);
1501
+ this.internalFieldCount = 0;
1502
+ this._accessors = new Map();
1503
+ this.Ctor = Ctor ?? Object;
1504
+ }
1505
+ setAccessor(name, getterWrap, setterWrap, getter, setter, data, attribute, getterSideEffectType, setterSideEffectType) {
1506
+ this._accessors.set(name, {
1507
+ name,
1508
+ getterWrap,
1509
+ setterWrap,
1510
+ getter,
1511
+ setter,
1512
+ data,
1513
+ attribute,
1514
+ getterSideEffectType,
1515
+ setterSideEffectType
1516
+ });
1517
+ }
1518
+ setInternalFieldCount(value) {
1519
+ this.internalFieldCount = value;
1520
+ }
1521
+ applyToInstance(instance) {
1522
+ internalField.set(instance, Array(this.internalFieldCount));
1523
+ this._addPropertiesToInstance(instance);
1524
+ const createAccessorWrapper = (type, data, cb) => {
1525
+ const { ctx } = this;
1526
+ function _(value) {
1527
+ const scope = ctx.openScope();
1528
+ const callbackInfo = scope.callbackInfo;
1529
+ let returnValue;
1530
+ try {
1531
+ callbackInfo.data = data;
1532
+ callbackInfo.args = type === 'getter' ? [] : [value];
1533
+ callbackInfo.thiz = this;
1534
+ callbackInfo.holder = findHolder(this, _) || this;
1535
+ callbackInfo.fn = _;
1536
+ const ret = cb(value);
1537
+ returnValue = ret ? ctx.jsValueFromNapiValue(ret) : undefined;
1538
+ }
1539
+ catch (err) {
1540
+ ctx.throwException(err);
1541
+ }
1542
+ ctx.closeScope(scope);
1543
+ if (ctx.hasPendingException()) {
1544
+ if (TryCatch.top) {
1545
+ TryCatch.top.setError(ctx.getAndClearLastException());
1546
+ }
1547
+ else {
1548
+ throw ctx.getAndClearLastException();
1549
+ }
1550
+ }
1551
+ return returnValue;
1552
+ }
1553
+ return _;
1554
+ };
1555
+ this._accessors.forEach((config, name) => {
1556
+ const { ctx } = this;
1557
+ const { getterWrap, setterWrap, getter, setter, data, attribute } = config;
1558
+ Object.defineProperty(instance, name, {
1559
+ get: getter
1560
+ ? createAccessorWrapper('getter', data, () => {
1561
+ return getterWrap(ctx.napiValueFromJsValue(name), ctx.getCurrentScope().id, getter);
1562
+ }).bind(instance)
1563
+ : undefined,
1564
+ set: setter
1565
+ ? createAccessorWrapper('setter', data, (value) => {
1566
+ return setterWrap(ctx.napiValueFromJsValue(name), ctx.napiValueFromJsValue(value), ctx.getCurrentScope().id, setter);
1567
+ }).bind(instance)
1568
+ : undefined,
1569
+ enumerable: !(attribute & 2),
1570
+ configurable: !(attribute & 4)
1571
+ });
1572
+ });
1573
+ }
1574
+ newInstance(_context) {
1575
+ const { ctx, Ctor } = this;
1576
+ let instance;
1577
+ try {
1578
+ instance = new Ctor();
1579
+ }
1580
+ catch (err) {
1581
+ ctx.throwException(err);
1582
+ }
1583
+ this.applyToInstance(instance);
1584
+ return instance;
1585
+ }
1586
+ }
1587
+
1588
+ //#endregion src/ObjectTemplate.ts
1589
+
1590
+ //#region src/FunctionTemplate.ts
1591
+ class Signature {
1592
+ constructor(receiver) {
1593
+ this.receiver = receiver;
1594
+ }
1595
+ }
1596
+ class FunctionTemplate extends Template {
1597
+ constructor(ctx, callback, v8FunctionCallback, data, signature) {
1598
+ super(ctx);
1599
+ this.ctx = ctx;
1600
+ this.callback = callback;
1601
+ this.v8FunctionCallback = v8FunctionCallback;
1602
+ this.data = data;
1603
+ this.className = undefined;
1604
+ this.signature = signature;
1605
+ this._cached = [undefined];
1606
+ }
1607
+ setClassName(name) {
1608
+ this.className = name;
1609
+ }
1610
+ instanceTemplate() {
1611
+ if (!this._instanceTemplate) {
1612
+ this._instanceTemplate = new ObjectTemplate(this.ctx);
1613
+ }
1614
+ return this._instanceTemplate;
1615
+ }
1616
+ prototypeTemplate() {
1617
+ if (!this._prototypeTemplate) {
1618
+ this._prototypeTemplate = new ObjectTemplate(this.ctx);
1619
+ }
1620
+ return this._prototypeTemplate;
1621
+ }
1622
+ getFunction() {
1623
+ if (this._cached[0]) {
1624
+ return this._cached[0];
1625
+ }
1626
+ const { ctx, callback, v8FunctionCallback, data, signature, _instanceTemplate } = this;
1627
+ function _(...args) {
1628
+ if (signature && signature.receiver) {
1629
+ const f = signature.receiver.getFunction();
1630
+ if (!(this instanceof f)) {
1631
+ throw new TypeError('Illegal invocation');
1632
+ }
1633
+ }
1634
+ const scope = ctx.openScope();
1635
+ const callbackInfo = scope.callbackInfo;
1636
+ let returnValue;
1637
+ try {
1638
+ callbackInfo.data = data;
1639
+ callbackInfo.args = args;
1640
+ callbackInfo.thiz = this;
1641
+ callbackInfo.holder = findHolder(this, _) || this;
1642
+ callbackInfo.fn = _;
1643
+ if (_instanceTemplate && this instanceof _) {
1644
+ _instanceTemplate.applyToInstance(this);
1645
+ }
1646
+ const ret = callback(ctx.getCurrentScope().id, v8FunctionCallback);
1647
+ returnValue = ret ? ctx.jsValueFromNapiValue(ret) : undefined;
1648
+ }
1649
+ catch (err) {
1650
+ if (err !== 'unwind') {
1651
+ ctx.throwException(err);
1652
+ }
1653
+ }
1654
+ finally {
1655
+ ctx.closeScope(scope);
1656
+ }
1657
+ if (ctx.hasPendingException()) {
1658
+ if (TryCatch.top) {
1659
+ TryCatch.top.setError(ctx.getAndClearLastException());
1660
+ }
1661
+ else {
1662
+ throw ctx.getAndClearLastException();
1663
+ }
1664
+ }
1665
+ return returnValue;
1666
+ }
1667
+ if (typeof this.className === 'string') {
1668
+ this.ctx.features.setFunctionName?.(_, this.className);
1669
+ }
1670
+ if (this._prototypeTemplate) {
1671
+ this._prototypeTemplate.applyToInstance(_.prototype);
1672
+ }
1673
+ this._addPropertiesToInstance(_);
1674
+ this._cached[0] = _;
1675
+ return _;
1676
+ }
1677
+ }
1678
+
1679
+ //#endregion src/FunctionTemplate.ts
1680
+
1681
+ //#region src/Private.ts
1682
+ const globalPrivateRegistry = new Map();
1683
+ const map = new WeakMap();
1684
+ class Private {
1685
+ constructor(name) {
1686
+ this._name = name;
1687
+ }
1688
+ name() {
1689
+ return this._name;
1690
+ }
1691
+ static forApi(name) {
1692
+ let privateInstance = globalPrivateRegistry.get(name);
1693
+ if (!privateInstance) {
1694
+ privateInstance = new Private(name);
1695
+ globalPrivateRegistry.set(name, privateInstance);
1696
+ }
1697
+ return privateInstance;
1698
+ }
1699
+ }
1700
+ function setPrivate(obj, key, value) {
1701
+ if (!(key instanceof Private)) {
1702
+ throw new TypeError('Expected key to be an instance of Private');
1703
+ }
1704
+ let m = map.get(key);
1705
+ if (!m) {
1706
+ m = new WeakMap();
1707
+ map.set(key, m);
1708
+ }
1709
+ m.set(obj, value);
1710
+ }
1711
+ function getPrivate(obj, key) {
1712
+ if (!(key instanceof Private)) {
1713
+ throw new TypeError('Expected key to be an instance of Private');
1714
+ }
1715
+ const m = map.get(key);
1716
+ if (!m) {
1717
+ return undefined;
1718
+ }
1719
+ return m.get(obj);
1720
+ }
1721
+ function hasPrivate(obj, key) {
1722
+ if (!(key instanceof Private)) {
1723
+ throw new TypeError('Expected key to be an instance of Private');
1724
+ }
1725
+ const m = map.get(key);
1726
+ if (!m) {
1727
+ return false;
1728
+ }
1729
+ return m.has(obj);
1730
+ }
1731
+ function deletePrivate(obj, key) {
1732
+ if (!(key instanceof Private)) {
1733
+ throw new TypeError('Expected key to be an instance of Private');
1734
+ }
1735
+ const m = map.get(key);
1736
+ if (!m || !m.has(obj)) {
1737
+ return true;
1738
+ }
1739
+ return m.delete(obj);
1740
+ }
1741
+
1742
+ //#endregion src/Private.ts
1743
+
1744
+ //#region src/ExternalMemory.ts
1745
+ const kMaxReasonableBytes = BigInt(1) << BigInt(60);
1746
+ const kMinReasonableBytes = -kMaxReasonableBytes;
1747
+ class ExternalMemory {
1748
+ constructor(onChange) {
1749
+ this.total = BigInt(0);
1750
+ this.onChange = onChange ?? null;
1751
+ }
1752
+ adjust(changeInBytes) {
1753
+ changeInBytes = BigInt(changeInBytes);
1754
+ if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) {
1755
+ throw new RangeError(`changeInBytes ${changeInBytes} is out of reasonable range`);
1756
+ }
1757
+ const old = this.total;
1758
+ this.total += changeInBytes;
1759
+ const amount = this.total;
1760
+ const onChange = this.onChange;
1761
+ if (changeInBytes) {
1762
+ onChange?.(amount, old, changeInBytes);
1763
+ }
1764
+ return amount;
1765
+ }
1766
+ }
1767
+
1768
+ //#endregion src/ExternalMemory.ts
1769
+
1770
+ //#region src/Isolate.ts
1771
+ class Isolate {
1772
+ constructor(options) {
1773
+ this.features = detectFeatures(options?.features);
1774
+ this._globalThis = this.features.getGlobalThis();
1775
+ this._scopeStore = new ScopeStore();
1776
+ this._handleStore = new HandleStore(this.features);
1777
+ this.globalHandleStore = new PersistentStore();
1778
+ this._lastException = new Persistent(this);
1779
+ this._externalMemory = new ExternalMemory(options?.onExternalMemoryChange);
1780
+ }
1781
+ napiValueFromJsValue(value) {
1782
+ switch (value) {
1783
+ case undefined: return 2;
1784
+ case null: return 3;
1785
+ case false: return 4;
1786
+ case true: return 5;
1787
+ case '': return 7;
1788
+ case this._globalThis: return 6;
1789
+ default: return this._scopeStore.currentScope.add(value);
1790
+ }
1791
+ }
1792
+ jsValueFromNapiValue(napiValue) {
1793
+ return this._handleStore.deepDeref(napiValue);
1794
+ }
1795
+ deleteRefSlotValue(id) {
1796
+ this._handleStore.refValues.delete(Number(id));
1797
+ }
1798
+ getRefSlotValue(id) {
1799
+ return this._handleStore.refValues.get(Number(id));
1800
+ }
1801
+ setRefSlotValue(id, ref) {
1802
+ this._handleStore.refValues.set(Number(id), ref);
1803
+ }
1804
+ createReference(...args) {
1805
+ return new Persistent(this, ...args);
1806
+ }
1807
+ insertRef(persistent) {
1808
+ this.globalHandleStore.insert(persistent);
1809
+ }
1810
+ getRef(ref) {
1811
+ return this.globalHandleStore.deref(ref);
1812
+ }
1813
+ removeRef(ref, force = false) {
1814
+ if (force || this._scopeStore.isEmpty()) {
1815
+ const persistent = this.globalHandleStore.deref(ref);
1816
+ persistent?.dispose();
1817
+ }
1818
+ else {
1819
+ this.globalHandleStore.markUnused(ref);
1820
+ }
1821
+ }
1822
+ getTryCatch(address) {
1823
+ return TryCatch.deref(address);
1824
+ }
1825
+ pushTryCatch(address) {
1826
+ const tryCatch = new TryCatch(address);
1827
+ return tryCatch;
1828
+ }
1829
+ popTryCatch(address) {
1830
+ if (address !== TryCatch.top?.id) {
1831
+ throw new Error('TryCatch mismatch');
1832
+ }
1833
+ return TryCatch.pop();
1834
+ }
1835
+ setLastException(err) {
1836
+ this._lastException.resetTo(err);
1837
+ }
1838
+ throwException(err) {
1839
+ if (TryCatch.top) {
1840
+ TryCatch.top.setError(err);
1841
+ }
1842
+ else {
1843
+ this.setLastException(err);
1844
+ }
1845
+ return err;
1846
+ }
1847
+ hasPendingException() {
1848
+ return !this._lastException.isEmpty();
1849
+ }
1850
+ getAndClearLastException() {
1851
+ const err = this._lastException.deref();
1852
+ this._lastException.reset();
1853
+ return err;
1854
+ }
1855
+ adjustAmountOfExternalAllocatedMemory(changeInBytes) {
1856
+ return this._externalMemory.adjust(changeInBytes);
1857
+ }
1858
+ createSignature(template) {
1859
+ return new Signature(template);
1860
+ }
1861
+ createObjectTemplate(constructor) {
1862
+ return new ObjectTemplate(this, constructor);
1863
+ }
1864
+ setInternalField(obj, index, value) {
1865
+ setInternalField(obj, index, value);
1866
+ }
1867
+ getInternalField(obj, index) {
1868
+ return getInternalField(obj, index);
1869
+ }
1870
+ getInternalFieldCount(obj) {
1871
+ return getInternalFieldCount(obj);
1872
+ }
1873
+ createFunctionTemplate(callback, v8FunctionCallback, data, signature) {
1874
+ const functionTemplate = new FunctionTemplate(this, callback, v8FunctionCallback, data, signature);
1875
+ return functionTemplate;
1876
+ }
1877
+ isScopeEmpty() {
1878
+ return this._scopeStore.isEmpty();
1879
+ }
1880
+ getCurrentScope() {
1881
+ return this._scopeStore.currentScope;
1882
+ }
1883
+ openScope() {
1884
+ return this._scopeStore.openScope(this._handleStore);
1885
+ }
1886
+ closeScope(_scope) {
1887
+ this._scopeStore.closeScope();
1888
+ if (this.isScopeEmpty()) {
1889
+ this.globalHandleStore.recycle();
1890
+ }
1891
+ }
1892
+ getHandleScope(scope) {
1893
+ return this._scopeStore.deref(scope);
1894
+ }
1895
+ getCallbackInfo(info) {
1896
+ return this._scopeStore.deref(info).callbackInfo;
1897
+ }
1898
+ createExternal(data) {
1899
+ return new External(data);
1900
+ }
1901
+ getExternalValue(external) {
1902
+ return getExternalValue(external);
1903
+ }
1904
+ isExternal(value) {
1905
+ return isExternal(value);
1906
+ }
1907
+ createResolver() {
1908
+ return this.features.withResolvers.call(Promise);
1909
+ }
1910
+ createPrivate(name) {
1911
+ return new Private(name);
1912
+ }
1913
+ getOrCreateGlobalPrivate(name) {
1914
+ return Private.forApi(name);
1915
+ }
1916
+ setPrivate(obj, key, value) {
1917
+ return setPrivate(obj, key, value);
1918
+ }
1919
+ getPrivate(obj, key) {
1920
+ return getPrivate(obj, key);
1921
+ }
1922
+ hasPrivate(obj, key) {
1923
+ return hasPrivate(obj, key);
1924
+ }
1925
+ deletePrivate(obj, key) {
1926
+ return deletePrivate(obj, key);
1927
+ }
1928
+ }
1929
+
1930
+ //#endregion src/Isolate.ts
1931
+
1932
+ //#region src/Context.ts
1933
+ const callbackWrapper = (envObject, callback) => {
1934
+ const napiValue = envObject.callIntoModule(callback);
1935
+ return (!napiValue) ? undefined : envObject.ctx.jsValueFromNapiValue(napiValue);
1936
+ };
1937
+ const withScope = (envObject, thiz, args, data, getFunction, wrapper, callback) => {
1938
+ const scope = envObject.ctx.openScope(envObject);
1939
+ const callbackInfo = scope.callbackInfo;
1940
+ callbackInfo.data = data;
1941
+ callbackInfo.args = args;
1942
+ callbackInfo.thiz = thiz;
1943
+ callbackInfo.fn = getFunction;
1944
+ try {
1945
+ return wrapper(envObject, callback);
1946
+ }
1947
+ catch (e) {
1948
+ if (e !== 'unwind') {
1949
+ throw e;
1950
+ }
1951
+ }
1952
+ finally {
1953
+ envObject.ctx.closeScope(envObject, scope);
1954
+ }
1955
+ };
1956
+ class CleanupHookCallback {
1957
+ constructor(envObject, fn, arg, order) {
1958
+ this.envObject = envObject;
1959
+ this.fn = fn;
1960
+ this.arg = arg;
1961
+ this.order = order;
1962
+ }
1963
+ }
1964
+ class CleanupQueue {
1965
+ constructor() {
1966
+ this._cleanupHooks = [];
1967
+ this._cleanupHookCounter = 0;
1968
+ }
1969
+ empty() {
1970
+ return this._cleanupHooks.length === 0;
1971
+ }
1972
+ add(envObject, fn, arg) {
1973
+ if (this._cleanupHooks.filter((hook) => (hook.envObject === envObject && hook.fn === fn && hook.arg === arg)).length > 0) {
1974
+ throw new Error('Can not add same fn and arg twice');
1975
+ }
1976
+ this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++));
1977
+ }
1978
+ remove(envObject, fn, arg) {
1979
+ for (let i = 0; i < this._cleanupHooks.length; ++i) {
1980
+ const hook = this._cleanupHooks[i];
1981
+ if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) {
1982
+ this._cleanupHooks.splice(i, 1);
1983
+ return;
1984
+ }
1985
+ }
1986
+ }
1987
+ drain() {
1988
+ const hooks = this._cleanupHooks.slice();
1989
+ hooks.sort((a, b) => (b.order - a.order));
1990
+ for (let i = 0; i < hooks.length; ++i) {
1991
+ const cb = hooks[i];
1992
+ if (typeof cb.fn === 'number') {
1993
+ cb.envObject.bridge.makeDynCall_vp(cb.fn)(cb.arg);
1994
+ }
1995
+ else {
1996
+ cb.fn(cb.arg);
1997
+ }
1998
+ this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1);
1999
+ }
2000
+ }
2001
+ dispose() {
2002
+ this._cleanupHooks.length = 0;
2003
+ this._cleanupHookCounter = 0;
2004
+ }
2005
+ }
2006
+ class NodejsWaitingRequestCounter {
2007
+ constructor(MessageChannel) {
2008
+ this.refHandle = new MessageChannel().port1;
2009
+ this.count = 0;
2010
+ }
2011
+ increase() {
2012
+ if (this.count === 0) {
2013
+ if (this.refHandle.ref) {
2014
+ this.refHandle.ref();
2015
+ }
2016
+ }
2017
+ this.count++;
2018
+ }
2019
+ decrease() {
2020
+ if (this.count === 0)
2021
+ return;
2022
+ if (this.count === 1) {
2023
+ if (this.refHandle.unref) {
2024
+ this.refHandle.unref();
2025
+ }
2026
+ }
2027
+ this.count--;
2028
+ }
2029
+ }
2030
+ class Context {
2031
+ constructor(options) {
2032
+ this._isStopping = false;
2033
+ this._canCallIntoJs = true;
2034
+ this._suppressDestroy = false;
2035
+ this.envStore = new ArrayStore();
2036
+ this.refStore = new Map();
2037
+ this.isolate = new Isolate(options);
2038
+ this.features = this.isolate.features;
2039
+ this.cleanupQueue = new CleanupQueue();
2040
+ if (typeof process === 'object' && process !== null && typeof process.once === 'function' && this.features.MessageChannel) {
2041
+ this.refCounter = new NodejsWaitingRequestCounter(this.features.MessageChannel);
2042
+ process.once('beforeExit', () => {
2043
+ if (!this._suppressDestroy) {
2044
+ this.destroy();
2045
+ }
2046
+ });
2047
+ }
2048
+ }
2049
+ getIsolate() {
2050
+ return this.isolate;
2051
+ }
2052
+ suppressDestroy() {
2053
+ this._suppressDestroy = true;
2054
+ }
2055
+ getRuntimeVersions() {
2056
+ return {
2057
+ version,
2058
+ NODE_API_SUPPORTED_VERSION_MAX,
2059
+ NAPI_VERSION_EXPERIMENTAL,
2060
+ NODE_API_DEFAULT_MODULE_API_VERSION,
2061
+ NODE_MODULE_VERSION
2062
+ };
2063
+ }
2064
+ createNotSupportWeakRefError(api, message) {
2065
+ return new NotSupportWeakRefError(api, message);
2066
+ }
2067
+ createNotSupportBufferError(api, message) {
2068
+ return new NotSupportBufferError(api, message);
2069
+ }
2070
+ createReference(envObject, handle_id, initialRefcount, ownership) {
2071
+ return Reference.create(this, envObject, handle_id, initialRefcount, ownership);
2072
+ }
2073
+ createReferenceWithData(envObject, handle_id, initialRefcount, ownership, data) {
2074
+ return ReferenceWithData.create(this, envObject, handle_id, initialRefcount, ownership, data);
2075
+ }
2076
+ createReferenceWithFinalizer(envObject, handle_id, initialRefcount, ownership, finalize_callback = 0, finalize_data = 0, finalize_hint = 0) {
2077
+ return ReferenceWithFinalizer.create(this, envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint);
2078
+ }
2079
+ createResolver() {
2080
+ return this.isolate.createResolver();
2081
+ }
2082
+ adjustAmountOfExternalAllocatedMemory(changeInBytes) {
2083
+ return this.isolate.adjustAmountOfExternalAllocatedMemory(changeInBytes);
2084
+ }
2085
+ createEnv(filename, moduleApiVersion, bridge, nodeBinding) {
2086
+ moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion;
2087
+ if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) {
2088
+ moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION;
2089
+ }
2090
+ else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) {
2091
+ const errorMessage = `${filename} requires Node-API version ${moduleApiVersion}, but this version of Node.js only supports version ${NODE_API_SUPPORTED_VERSION_MAX} add-ons.`;
2092
+ throw new Error(errorMessage);
2093
+ }
2094
+ const env = new NodeEnv(this, this.envStore, { ...bridge });
2095
+ env.filename = filename;
2096
+ env.moduleApiVersion = moduleApiVersion;
2097
+ env.nodeBinding = nodeBinding;
2098
+ this.addCleanupHook(env, () => { env.unref(); }, 0);
2099
+ return env;
2100
+ }
2101
+ createFunction(envObject, napiCallback, data, name, dynamicExecution) {
2102
+ if (envObject.ctx !== this) {
2103
+ throw new Error(`The napi_env (${envObject.bridge.address}) is not created by this context`);
2104
+ }
2105
+ const callback = (envObject) => {
2106
+ return napiCallback(envObject.bridge.address, envObject.ctx.getCurrentScope().id);
2107
+ };
2108
+ let _;
2109
+ const staticFunctionWrapper = (withScope, envObject, data, callbackWrapper, callback) => {
2110
+ return function (...args) {
2111
+ return withScope(envObject, this, args, data, _, callbackWrapper, callback);
2112
+ };
2113
+ };
2114
+ let functionWrapper;
2115
+ if (name && dynamicExecution && this.features.makeDynamicFunction) {
2116
+ try {
2117
+ functionWrapper = this.features.makeDynamicFunction('withScope', 'envObject', 'data', 'callbackWrapper', 'callback', 'return function ' + name + '(...args){' +
2118
+ 'return withScope(envObject,this,args,data,' + name + ',callbackWrapper,callback)' +
2119
+ '};');
2120
+ }
2121
+ catch (_) {
2122
+ functionWrapper = staticFunctionWrapper;
2123
+ }
2124
+ }
2125
+ else {
2126
+ functionWrapper = staticFunctionWrapper;
2127
+ }
2128
+ _ = functionWrapper(withScope, envObject, data, callbackWrapper, callback);
2129
+ if (functionWrapper === staticFunctionWrapper && this.features.setFunctionName && name) {
2130
+ this.features.setFunctionName(_, name);
2131
+ }
2132
+ return _;
2133
+ }
2134
+ createTrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) {
2135
+ return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint);
2136
+ }
2137
+ getCurrentScope() {
2138
+ return this.isolate.getCurrentScope();
2139
+ }
2140
+ openScope(envObject) {
2141
+ const scope = this.isolate.openScope();
2142
+ envObject.openHandleScopes++;
2143
+ return scope;
2144
+ }
2145
+ closeScope(envObject, scope) {
2146
+ this.isolate.closeScope(scope);
2147
+ envObject.openHandleScopes--;
2148
+ }
2149
+ getEnv(env) {
2150
+ return this.envStore.deref(env);
2151
+ }
2152
+ getRef(ref) {
2153
+ return this.refStore.get(Number(ref));
2154
+ }
2155
+ getHandleScope(scope) {
2156
+ return this.isolate.getHandleScope(scope);
2157
+ }
2158
+ getCallbackInfo(info) {
2159
+ return this.isolate.getCallbackInfo(info);
2160
+ }
2161
+ napiValueFromJsValue(value) {
2162
+ return this.isolate.napiValueFromJsValue(value);
2163
+ }
2164
+ jsValueFromNapiValue(napiValue) {
2165
+ return this.isolate.jsValueFromNapiValue(napiValue);
2166
+ }
2167
+ createExternal(data) {
2168
+ return this.isolate.createExternal(data);
2169
+ }
2170
+ getExternalValue(external) {
2171
+ return this.isolate.getExternalValue(external);
2172
+ }
2173
+ isExternal(value) {
2174
+ return this.isolate.isExternal(value);
2175
+ }
2176
+ addCleanupHook(envObject, fn, arg) {
2177
+ this.cleanupQueue.add(envObject, fn, arg);
2178
+ }
2179
+ removeCleanupHook(envObject, fn, arg) {
2180
+ this.cleanupQueue.remove(envObject, fn, arg);
2181
+ }
2182
+ runCleanup() {
2183
+ while (!this.cleanupQueue.empty()) {
2184
+ this.cleanupQueue.drain();
2185
+ }
2186
+ }
2187
+ increaseWaitingRequestCounter() {
2188
+ this.refCounter?.increase();
2189
+ }
2190
+ decreaseWaitingRequestCounter() {
2191
+ this.refCounter?.decrease();
2192
+ }
2193
+ setCanCallIntoJs(value) {
2194
+ this._canCallIntoJs = value;
2195
+ }
2196
+ setStopping(value) {
2197
+ this._isStopping = value;
2198
+ }
2199
+ canCallIntoJs() {
2200
+ return this._canCallIntoJs && !this._isStopping;
2201
+ }
2202
+ getDylinkMetadata(binary) {
2203
+ return getDylinkMetadata(binary);
2204
+ }
2205
+ destroy() {
2206
+ this.setStopping(true);
2207
+ this.setCanCallIntoJs(false);
2208
+ this.runCleanup();
2209
+ }
2210
+ }
2211
+ let defaultContext;
2212
+ function createContext(options) {
2213
+ return new Context(options);
2214
+ }
2215
+ function getDefaultContext() {
2216
+ if (!defaultContext) {
2217
+ defaultContext = createContext();
1475
2218
  }
2219
+ return defaultContext;
2220
+ }
1476
2221
 
1477
- exports.ConstHandle = ConstHandle;
1478
- exports.Context = Context;
1479
- exports.Deferred = Deferred;
1480
- exports.EmnapiError = EmnapiError;
1481
- exports.Env = Env;
1482
- exports.External = External;
1483
- exports.Finalizer = Finalizer;
1484
- exports.Handle = Handle;
1485
- exports.HandleScope = HandleScope;
1486
- exports.HandleStore = HandleStore;
1487
- exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL;
1488
- exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION;
1489
- exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX;
1490
- exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN;
1491
- exports.NodeEnv = NodeEnv;
1492
- exports.NotSupportBufferError = NotSupportBufferError;
1493
- exports.NotSupportWeakRefError = NotSupportWeakRefError;
1494
- exports.Persistent = Persistent;
1495
- exports.RefTracker = RefTracker;
1496
- exports.Reference = Reference;
1497
- exports.ReferenceWithData = ReferenceWithData;
1498
- exports.ReferenceWithFinalizer = ReferenceWithFinalizer;
1499
- exports.ScopeStore = ScopeStore;
1500
- exports.Store = Store;
1501
- exports.TrackedFinalizer = TrackedFinalizer;
1502
- exports.TryCatch = TryCatch;
1503
- exports.createContext = createContext;
1504
- exports.getDefaultContext = getDefaultContext;
1505
- exports.getExternalValue = getExternalValue;
1506
- exports.isExternal = isExternal;
1507
- exports.isReferenceType = isReferenceType;
1508
- exports.version = version;
2222
+ //#endregion src/Context.ts
1509
2223
 
1510
- }));
2224
+ export { ArrayStore, BaseArrayStore, Context, CountIdAllocator, CountIdReuseAllocator, Disposable, EmnapiError, Env, External, Finalizer, FunctionTemplate, HandleScope, HandleStore, Isolate, NAPI_VERSION_EXPERIMENTAL, NODE_API_DEFAULT_MODULE_API_VERSION, NODE_API_SUPPORTED_VERSION_MAX, NODE_API_SUPPORTED_VERSION_MIN, NodeEnv, NotSupportBufferError, NotSupportWeakRefError, ObjectTemplate, Persistent, PersistentStore, Private, RefTracker, Reference, ReferenceOwnership, ReferenceWithData, ReferenceWithFinalizer, ScopeStore, Signature, StrongRef, Template, TrackedFinalizer, TryCatch, createContext, deletePrivate, getDefaultContext, getDylinkMetadata, getExternalValue, getInternalField, getPrivate, hasPrivate, isExternal, isReferenceType, setInternalField, setPrivate, version };
2225
+ //# sourceMappingURL=emnapi.js.map