@webvpn/dgram 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/build/index.cjs +2235 -2327
  2. package/build/index.cjs.map +1 -1
  3. package/build/index.d.ts +5 -184
  4. package/build/index.js +10094 -2664
  5. package/build/index.js.map +1 -1
  6. package/package.json +4 -6
  7. package/src/index.ts +5 -698
  8. package/vite-plugin-node-stdlib-browser.cjs +61 -61
  9. package/vite.config.ts +29 -29
  10. package/build/index.mjs +0 -3252
  11. package/build/index.mjs.map +0 -1
  12. package/build/test.d.ts +0 -1
  13. package/build/utils.d.ts +0 -13
  14. package/index.html +0 -11
  15. package/src/chrome-dgram.js +0 -503
  16. package/src/flatbuffers/client-packet-type.ts +0 -40
  17. package/src/flatbuffers/client-packet.ts +0 -162
  18. package/src/flatbuffers/client-tcpserver-close.ts +0 -93
  19. package/src/flatbuffers/client-tcpserver-get-connections.ts +0 -93
  20. package/src/flatbuffers/client-tcpserver-listen.ts +0 -211
  21. package/src/flatbuffers/client-tcpserver.ts +0 -159
  22. package/src/flatbuffers/client-tcpsocket-connect.ts +0 -253
  23. package/src/flatbuffers/client-tcpsocket-destroy-soon.ts +0 -75
  24. package/src/flatbuffers/client-tcpsocket-destroy.ts +0 -93
  25. package/src/flatbuffers/client-tcpsocket-end.ts +0 -93
  26. package/src/flatbuffers/client-tcpsocket-pause.ts +0 -75
  27. package/src/flatbuffers/client-tcpsocket-reset-and-destroy.ts +0 -75
  28. package/src/flatbuffers/client-tcpsocket-resume.ts +0 -75
  29. package/src/flatbuffers/client-tcpsocket-set-encoding.ts +0 -93
  30. package/src/flatbuffers/client-tcpsocket-set-keep-alive.ts +0 -103
  31. package/src/flatbuffers/client-tcpsocket-set-no-delay.ts +0 -89
  32. package/src/flatbuffers/client-tcpsocket-set-timeout.ts +0 -107
  33. package/src/flatbuffers/client-tcpsocket-write.ts +0 -147
  34. package/src/flatbuffers/client-tcpsocket.ts +0 -89
  35. package/src/flatbuffers/client-udpsocket-add-membership.ts +0 -110
  36. package/src/flatbuffers/client-udpsocket-add-source-specific-membership.ts +0 -127
  37. package/src/flatbuffers/client-udpsocket-bind.ts +0 -138
  38. package/src/flatbuffers/client-udpsocket-close.ts +0 -93
  39. package/src/flatbuffers/client-udpsocket-disconnect.ts +0 -75
  40. package/src/flatbuffers/client-udpsocket-drop-membership.ts +0 -110
  41. package/src/flatbuffers/client-udpsocket-drop-source-specific-membership.ts +0 -127
  42. package/src/flatbuffers/client-udpsocket-send.ts +0 -189
  43. package/src/flatbuffers/client-udpsocket-set-broadcast.ts +0 -89
  44. package/src/flatbuffers/client-udpsocket-set-multicast-interface.ts +0 -93
  45. package/src/flatbuffers/client-udpsocket-set-multicast-loopback.ts +0 -89
  46. package/src/flatbuffers/client-udpsocket-set-multicast-ttl.ts +0 -89
  47. package/src/flatbuffers/client-udpsocket-set-recv-buffer-size.ts +0 -89
  48. package/src/flatbuffers/client-udpsocket-set-send-buffer-size.ts +0 -89
  49. package/src/flatbuffers/client-udpsocket-set-ttl.ts +0 -89
  50. package/src/flatbuffers/client-udpsocket.ts +0 -149
  51. package/src/flatbuffers/packet-handshake-type.ts +0 -9
  52. package/src/flatbuffers/packet.ts +0 -210
  53. package/src/flatbuffers/schema.ts +0 -75
  54. package/src/flatbuffers/server-packet-type.ts +0 -38
  55. package/src/flatbuffers/server-packet.ts +0 -158
  56. package/src/flatbuffers/server-tcpserver-callback-close.ts +0 -93
  57. package/src/flatbuffers/server-tcpserver-callback-get-connections.ts +0 -124
  58. package/src/flatbuffers/server-tcpserver-callback-listen.ts +0 -141
  59. package/src/flatbuffers/server-tcpserver-event-close.ts +0 -75
  60. package/src/flatbuffers/server-tcpserver-event-drop.ts +0 -75
  61. package/src/flatbuffers/server-tcpserver-event-error.ts +0 -75
  62. package/src/flatbuffers/server-tcpserver-event-listening.ts +0 -124
  63. package/src/flatbuffers/server-tcpsocket-callback-connect.ts +0 -189
  64. package/src/flatbuffers/server-tcpsocket-callback-end.ts +0 -93
  65. package/src/flatbuffers/server-tcpsocket-callback-set-timeout.ts +0 -93
  66. package/src/flatbuffers/server-tcpsocket-callback-write.ts +0 -93
  67. package/src/flatbuffers/server-tcpsocket-event-close.ts +0 -89
  68. package/src/flatbuffers/server-tcpsocket-event-connect.ts +0 -172
  69. package/src/flatbuffers/server-tcpsocket-event-connection-attempt-failed.ts +0 -138
  70. package/src/flatbuffers/server-tcpsocket-event-connection-attempt-timeout.ts +0 -121
  71. package/src/flatbuffers/server-tcpsocket-event-connection-attempt.ts +0 -121
  72. package/src/flatbuffers/server-tcpsocket-event-data.ts +0 -113
  73. package/src/flatbuffers/server-tcpsocket-event-drain.ts +0 -75
  74. package/src/flatbuffers/server-tcpsocket-event-end.ts +0 -75
  75. package/src/flatbuffers/server-tcpsocket-event-error.ts +0 -93
  76. package/src/flatbuffers/server-tcpsocket-event-lookup.ts +0 -141
  77. package/src/flatbuffers/server-tcpsocket-event-ready.ts +0 -75
  78. package/src/flatbuffers/server-tcpsocket-event-timeout.ts +0 -75
  79. package/src/flatbuffers/server-udpsocket-callback-bind.ts +0 -141
  80. package/src/flatbuffers/server-udpsocket-callback-close.ts +0 -93
  81. package/src/flatbuffers/server-udpsocket-callback-connect.ts +0 -141
  82. package/src/flatbuffers/server-udpsocket-callback-send.ts +0 -93
  83. package/src/flatbuffers/server-udpsocket-event-close.ts +0 -75
  84. package/src/flatbuffers/server-udpsocket-event-connect.ts +0 -75
  85. package/src/flatbuffers/server-udpsocket-event-error.ts +0 -93
  86. package/src/flatbuffers/server-udpsocket-event-listening.ts +0 -124
  87. package/src/flatbuffers/server-udpsocket-event-message.ts +0 -175
  88. package/src/net.js +0 -2442
  89. package/src/test.ts +0 -34
  90. package/src/types.ts +0 -16
  91. package/src/utils.ts +0 -45
package/build/index.mjs DELETED
@@ -1,3252 +0,0 @@
1
- var events = {exports: {}};
2
-
3
- var R = typeof Reflect === 'object' ? Reflect : null;
4
- var ReflectApply = R && typeof R.apply === 'function'
5
- ? R.apply
6
- : function ReflectApply(target, receiver, args) {
7
- return Function.prototype.apply.call(target, receiver, args);
8
- };
9
-
10
- var ReflectOwnKeys;
11
- if (R && typeof R.ownKeys === 'function') {
12
- ReflectOwnKeys = R.ownKeys;
13
- } else if (Object.getOwnPropertySymbols) {
14
- ReflectOwnKeys = function ReflectOwnKeys(target) {
15
- return Object.getOwnPropertyNames(target)
16
- .concat(Object.getOwnPropertySymbols(target));
17
- };
18
- } else {
19
- ReflectOwnKeys = function ReflectOwnKeys(target) {
20
- return Object.getOwnPropertyNames(target);
21
- };
22
- }
23
-
24
- function ProcessEmitWarning(warning) {
25
- if (console && console.warn) console.warn(warning);
26
- }
27
-
28
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
29
- return value !== value;
30
- };
31
-
32
- function EventEmitter() {
33
- EventEmitter.init.call(this);
34
- }
35
- events.exports = EventEmitter;
36
- events.exports.once = once;
37
-
38
- // Backwards-compat with node 0.10.x
39
- EventEmitter.EventEmitter = EventEmitter;
40
-
41
- EventEmitter.prototype._events = undefined;
42
- EventEmitter.prototype._eventsCount = 0;
43
- EventEmitter.prototype._maxListeners = undefined;
44
-
45
- // By default EventEmitters will print a warning if more than 10 listeners are
46
- // added to it. This is a useful default which helps finding memory leaks.
47
- var defaultMaxListeners = 10;
48
-
49
- function checkListener(listener) {
50
- if (typeof listener !== 'function') {
51
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
52
- }
53
- }
54
-
55
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
56
- enumerable: true,
57
- get: function() {
58
- return defaultMaxListeners;
59
- },
60
- set: function(arg) {
61
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
62
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
63
- }
64
- defaultMaxListeners = arg;
65
- }
66
- });
67
-
68
- EventEmitter.init = function() {
69
-
70
- if (this._events === undefined ||
71
- this._events === Object.getPrototypeOf(this)._events) {
72
- this._events = Object.create(null);
73
- this._eventsCount = 0;
74
- }
75
-
76
- this._maxListeners = this._maxListeners || undefined;
77
- };
78
-
79
- // Obviously not all Emitters should be limited to 10. This function allows
80
- // that to be increased. Set to zero for unlimited.
81
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
82
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
83
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
84
- }
85
- this._maxListeners = n;
86
- return this;
87
- };
88
-
89
- function _getMaxListeners(that) {
90
- if (that._maxListeners === undefined)
91
- return EventEmitter.defaultMaxListeners;
92
- return that._maxListeners;
93
- }
94
-
95
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
96
- return _getMaxListeners(this);
97
- };
98
-
99
- EventEmitter.prototype.emit = function emit(type) {
100
- var args = [];
101
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
102
- var doError = (type === 'error');
103
-
104
- var events = this._events;
105
- if (events !== undefined)
106
- doError = (doError && events.error === undefined);
107
- else if (!doError)
108
- return false;
109
-
110
- // If there is no 'error' event listener then throw.
111
- if (doError) {
112
- var er;
113
- if (args.length > 0)
114
- er = args[0];
115
- if (er instanceof Error) {
116
- // Note: The comments on the `throw` lines are intentional, they show
117
- // up in Node's output if this results in an unhandled exception.
118
- throw er; // Unhandled 'error' event
119
- }
120
- // At least give some kind of context to the user
121
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
122
- err.context = er;
123
- throw err; // Unhandled 'error' event
124
- }
125
-
126
- var handler = events[type];
127
-
128
- if (handler === undefined)
129
- return false;
130
-
131
- if (typeof handler === 'function') {
132
- ReflectApply(handler, this, args);
133
- } else {
134
- var len = handler.length;
135
- var listeners = arrayClone(handler, len);
136
- for (var i = 0; i < len; ++i)
137
- ReflectApply(listeners[i], this, args);
138
- }
139
-
140
- return true;
141
- };
142
-
143
- function _addListener(target, type, listener, prepend) {
144
- var m;
145
- var events;
146
- var existing;
147
-
148
- checkListener(listener);
149
-
150
- events = target._events;
151
- if (events === undefined) {
152
- events = target._events = Object.create(null);
153
- target._eventsCount = 0;
154
- } else {
155
- // To avoid recursion in the case that type === "newListener"! Before
156
- // adding it to the listeners, first emit "newListener".
157
- if (events.newListener !== undefined) {
158
- target.emit('newListener', type,
159
- listener.listener ? listener.listener : listener);
160
-
161
- // Re-assign `events` because a newListener handler could have caused the
162
- // this._events to be assigned to a new object
163
- events = target._events;
164
- }
165
- existing = events[type];
166
- }
167
-
168
- if (existing === undefined) {
169
- // Optimize the case of one listener. Don't need the extra array object.
170
- existing = events[type] = listener;
171
- ++target._eventsCount;
172
- } else {
173
- if (typeof existing === 'function') {
174
- // Adding the second element, need to change to array.
175
- existing = events[type] =
176
- prepend ? [listener, existing] : [existing, listener];
177
- // If we've already got an array, just append.
178
- } else if (prepend) {
179
- existing.unshift(listener);
180
- } else {
181
- existing.push(listener);
182
- }
183
-
184
- // Check for listener leak
185
- m = _getMaxListeners(target);
186
- if (m > 0 && existing.length > m && !existing.warned) {
187
- existing.warned = true;
188
- // No error code for this since it is a Warning
189
- // eslint-disable-next-line no-restricted-syntax
190
- var w = new Error('Possible EventEmitter memory leak detected. ' +
191
- existing.length + ' ' + String(type) + ' listeners ' +
192
- 'added. Use emitter.setMaxListeners() to ' +
193
- 'increase limit');
194
- w.name = 'MaxListenersExceededWarning';
195
- w.emitter = target;
196
- w.type = type;
197
- w.count = existing.length;
198
- ProcessEmitWarning(w);
199
- }
200
- }
201
-
202
- return target;
203
- }
204
-
205
- EventEmitter.prototype.addListener = function addListener(type, listener) {
206
- return _addListener(this, type, listener, false);
207
- };
208
-
209
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
210
-
211
- EventEmitter.prototype.prependListener =
212
- function prependListener(type, listener) {
213
- return _addListener(this, type, listener, true);
214
- };
215
-
216
- function onceWrapper() {
217
- if (!this.fired) {
218
- this.target.removeListener(this.type, this.wrapFn);
219
- this.fired = true;
220
- if (arguments.length === 0)
221
- return this.listener.call(this.target);
222
- return this.listener.apply(this.target, arguments);
223
- }
224
- }
225
-
226
- function _onceWrap(target, type, listener) {
227
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
228
- var wrapped = onceWrapper.bind(state);
229
- wrapped.listener = listener;
230
- state.wrapFn = wrapped;
231
- return wrapped;
232
- }
233
-
234
- EventEmitter.prototype.once = function once(type, listener) {
235
- checkListener(listener);
236
- this.on(type, _onceWrap(this, type, listener));
237
- return this;
238
- };
239
-
240
- EventEmitter.prototype.prependOnceListener =
241
- function prependOnceListener(type, listener) {
242
- checkListener(listener);
243
- this.prependListener(type, _onceWrap(this, type, listener));
244
- return this;
245
- };
246
-
247
- // Emits a 'removeListener' event if and only if the listener was removed.
248
- EventEmitter.prototype.removeListener =
249
- function removeListener(type, listener) {
250
- var list, events, position, i, originalListener;
251
-
252
- checkListener(listener);
253
-
254
- events = this._events;
255
- if (events === undefined)
256
- return this;
257
-
258
- list = events[type];
259
- if (list === undefined)
260
- return this;
261
-
262
- if (list === listener || list.listener === listener) {
263
- if (--this._eventsCount === 0)
264
- this._events = Object.create(null);
265
- else {
266
- delete events[type];
267
- if (events.removeListener)
268
- this.emit('removeListener', type, list.listener || listener);
269
- }
270
- } else if (typeof list !== 'function') {
271
- position = -1;
272
-
273
- for (i = list.length - 1; i >= 0; i--) {
274
- if (list[i] === listener || list[i].listener === listener) {
275
- originalListener = list[i].listener;
276
- position = i;
277
- break;
278
- }
279
- }
280
-
281
- if (position < 0)
282
- return this;
283
-
284
- if (position === 0)
285
- list.shift();
286
- else {
287
- spliceOne(list, position);
288
- }
289
-
290
- if (list.length === 1)
291
- events[type] = list[0];
292
-
293
- if (events.removeListener !== undefined)
294
- this.emit('removeListener', type, originalListener || listener);
295
- }
296
-
297
- return this;
298
- };
299
-
300
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
301
-
302
- EventEmitter.prototype.removeAllListeners =
303
- function removeAllListeners(type) {
304
- var listeners, events, i;
305
-
306
- events = this._events;
307
- if (events === undefined)
308
- return this;
309
-
310
- // not listening for removeListener, no need to emit
311
- if (events.removeListener === undefined) {
312
- if (arguments.length === 0) {
313
- this._events = Object.create(null);
314
- this._eventsCount = 0;
315
- } else if (events[type] !== undefined) {
316
- if (--this._eventsCount === 0)
317
- this._events = Object.create(null);
318
- else
319
- delete events[type];
320
- }
321
- return this;
322
- }
323
-
324
- // emit removeListener for all listeners on all events
325
- if (arguments.length === 0) {
326
- var keys = Object.keys(events);
327
- var key;
328
- for (i = 0; i < keys.length; ++i) {
329
- key = keys[i];
330
- if (key === 'removeListener') continue;
331
- this.removeAllListeners(key);
332
- }
333
- this.removeAllListeners('removeListener');
334
- this._events = Object.create(null);
335
- this._eventsCount = 0;
336
- return this;
337
- }
338
-
339
- listeners = events[type];
340
-
341
- if (typeof listeners === 'function') {
342
- this.removeListener(type, listeners);
343
- } else if (listeners !== undefined) {
344
- // LIFO order
345
- for (i = listeners.length - 1; i >= 0; i--) {
346
- this.removeListener(type, listeners[i]);
347
- }
348
- }
349
-
350
- return this;
351
- };
352
-
353
- function _listeners(target, type, unwrap) {
354
- var events = target._events;
355
-
356
- if (events === undefined)
357
- return [];
358
-
359
- var evlistener = events[type];
360
- if (evlistener === undefined)
361
- return [];
362
-
363
- if (typeof evlistener === 'function')
364
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
365
-
366
- return unwrap ?
367
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
368
- }
369
-
370
- EventEmitter.prototype.listeners = function listeners(type) {
371
- return _listeners(this, type, true);
372
- };
373
-
374
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
375
- return _listeners(this, type, false);
376
- };
377
-
378
- EventEmitter.listenerCount = function(emitter, type) {
379
- if (typeof emitter.listenerCount === 'function') {
380
- return emitter.listenerCount(type);
381
- } else {
382
- return listenerCount.call(emitter, type);
383
- }
384
- };
385
-
386
- EventEmitter.prototype.listenerCount = listenerCount;
387
- function listenerCount(type) {
388
- var events = this._events;
389
-
390
- if (events !== undefined) {
391
- var evlistener = events[type];
392
-
393
- if (typeof evlistener === 'function') {
394
- return 1;
395
- } else if (evlistener !== undefined) {
396
- return evlistener.length;
397
- }
398
- }
399
-
400
- return 0;
401
- }
402
-
403
- EventEmitter.prototype.eventNames = function eventNames() {
404
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
405
- };
406
-
407
- function arrayClone(arr, n) {
408
- var copy = new Array(n);
409
- for (var i = 0; i < n; ++i)
410
- copy[i] = arr[i];
411
- return copy;
412
- }
413
-
414
- function spliceOne(list, index) {
415
- for (; index + 1 < list.length; index++)
416
- list[index] = list[index + 1];
417
- list.pop();
418
- }
419
-
420
- function unwrapListeners(arr) {
421
- var ret = new Array(arr.length);
422
- for (var i = 0; i < ret.length; ++i) {
423
- ret[i] = arr[i].listener || arr[i];
424
- }
425
- return ret;
426
- }
427
-
428
- function once(emitter, name) {
429
- return new Promise(function (resolve, reject) {
430
- function errorListener(err) {
431
- emitter.removeListener(name, resolver);
432
- reject(err);
433
- }
434
-
435
- function resolver() {
436
- if (typeof emitter.removeListener === 'function') {
437
- emitter.removeListener('error', errorListener);
438
- }
439
- resolve([].slice.call(arguments));
440
- }
441
- eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
442
- if (name !== 'error') {
443
- addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
444
- }
445
- });
446
- }
447
-
448
- function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
449
- if (typeof emitter.on === 'function') {
450
- eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
451
- }
452
- }
453
-
454
- function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
455
- if (typeof emitter.on === 'function') {
456
- if (flags.once) {
457
- emitter.once(name, listener);
458
- } else {
459
- emitter.on(name, listener);
460
- }
461
- } else if (typeof emitter.addEventListener === 'function') {
462
- // EventTarget does not have `error` event semantics like Node
463
- // EventEmitters, we do not listen for `error` events here.
464
- emitter.addEventListener(name, function wrapListener(arg) {
465
- // IE does not have builtin `{ once: true }` support so we
466
- // have to do it manually.
467
- if (flags.once) {
468
- emitter.removeEventListener(name, wrapListener);
469
- }
470
- listener(arg);
471
- });
472
- } else {
473
- throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
474
- }
475
- }
476
-
477
- var eventsExports = events.exports;
478
-
479
- var decoder;
480
- try {
481
- decoder = new TextDecoder();
482
- } catch(error) {}
483
- var src;
484
- var srcEnd;
485
- var position$1 = 0;
486
- var currentUnpackr = {};
487
- var currentStructures;
488
- var srcString;
489
- var srcStringStart = 0;
490
- var srcStringEnd = 0;
491
- var bundledStrings$1;
492
- var referenceMap;
493
- var currentExtensions = [];
494
- var dataView;
495
- var defaultOptions = {
496
- useRecords: false,
497
- mapsAsObjects: true
498
- };
499
- class C1Type {}
500
- const C1 = new C1Type();
501
- C1.name = 'MessagePack 0xC1';
502
- var sequentialMode = false;
503
- var inlineObjectReadThreshold = 2;
504
- var readStruct;
505
- // no-eval build
506
- try {
507
- new Function('');
508
- } catch(error) {
509
- // if eval variants are not supported, do not create inline object readers ever
510
- inlineObjectReadThreshold = Infinity;
511
- }
512
-
513
- class Unpackr {
514
- constructor(options) {
515
- if (options) {
516
- if (options.useRecords === false && options.mapsAsObjects === undefined)
517
- options.mapsAsObjects = true;
518
- if (options.sequential && options.trusted !== false) {
519
- options.trusted = true;
520
- if (!options.structures && options.useRecords != false) {
521
- options.structures = [];
522
- if (!options.maxSharedStructures)
523
- options.maxSharedStructures = 0;
524
- }
525
- }
526
- if (options.structures)
527
- options.structures.sharedLength = options.structures.length;
528
- else if (options.getStructures) {
529
- (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures
530
- options.structures.sharedLength = 0;
531
- }
532
- if (options.int64AsNumber) {
533
- options.int64AsType = 'number';
534
- }
535
- }
536
- Object.assign(this, options);
537
- }
538
- unpack(source, options) {
539
- if (src) {
540
- // re-entrant execution, save the state and restore it after we do this unpack
541
- return saveState(() => {
542
- clearSource();
543
- return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options)
544
- })
545
- }
546
- if (!source.buffer && source.constructor === ArrayBuffer)
547
- source = typeof Buffer !== 'undefined' ? Buffer.from(source) : new Uint8Array(source);
548
- if (typeof options === 'object') {
549
- srcEnd = options.end || source.length;
550
- position$1 = options.start || 0;
551
- } else {
552
- position$1 = 0;
553
- srcEnd = options > -1 ? options : source.length;
554
- }
555
- srcStringEnd = 0;
556
- srcString = null;
557
- bundledStrings$1 = null;
558
- src = source;
559
- // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend
560
- // technique for getting data from a database where it can be copied into an existing buffer instead of creating
561
- // new ones
562
- try {
563
- dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength));
564
- } catch(error) {
565
- // if it doesn't have a buffer, maybe it is the wrong type of object
566
- src = null;
567
- if (source instanceof Uint8Array)
568
- throw error
569
- throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))
570
- }
571
- if (this instanceof Unpackr) {
572
- currentUnpackr = this;
573
- if (this.structures) {
574
- currentStructures = this.structures;
575
- return checkedRead(options)
576
- } else if (!currentStructures || currentStructures.length > 0) {
577
- currentStructures = [];
578
- }
579
- } else {
580
- currentUnpackr = defaultOptions;
581
- if (!currentStructures || currentStructures.length > 0)
582
- currentStructures = [];
583
- }
584
- return checkedRead(options)
585
- }
586
- unpackMultiple(source, forEach) {
587
- let values, lastPosition = 0;
588
- try {
589
- sequentialMode = true;
590
- let size = source.length;
591
- let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size);
592
- if (forEach) {
593
- if (forEach(value, lastPosition, position$1) === false) return;
594
- while(position$1 < size) {
595
- lastPosition = position$1;
596
- if (forEach(checkedRead(), lastPosition, position$1) === false) {
597
- return
598
- }
599
- }
600
- }
601
- else {
602
- values = [ value ];
603
- while(position$1 < size) {
604
- lastPosition = position$1;
605
- values.push(checkedRead());
606
- }
607
- return values
608
- }
609
- } catch(error) {
610
- error.lastPosition = lastPosition;
611
- error.values = values;
612
- throw error
613
- } finally {
614
- sequentialMode = false;
615
- clearSource();
616
- }
617
- }
618
- _mergeStructures(loadedStructures, existingStructures) {
619
- loadedStructures = loadedStructures || [];
620
- if (Object.isFrozen(loadedStructures))
621
- loadedStructures = loadedStructures.map(structure => structure.slice(0));
622
- for (let i = 0, l = loadedStructures.length; i < l; i++) {
623
- let structure = loadedStructures[i];
624
- if (structure) {
625
- structure.isShared = true;
626
- if (i >= 32)
627
- structure.highByte = (i - 32) >> 5;
628
- }
629
- }
630
- loadedStructures.sharedLength = loadedStructures.length;
631
- for (let id in existingStructures || []) {
632
- if (id >= 0) {
633
- let structure = loadedStructures[id];
634
- let existing = existingStructures[id];
635
- if (existing) {
636
- if (structure)
637
- (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure;
638
- loadedStructures[id] = existing;
639
- }
640
- }
641
- }
642
- return this.structures = loadedStructures
643
- }
644
- decode(source, options) {
645
- return this.unpack(source, options)
646
- }
647
- }
648
- function checkedRead(options) {
649
- try {
650
- if (!currentUnpackr.trusted && !sequentialMode) {
651
- let sharedLength = currentStructures.sharedLength || 0;
652
- if (sharedLength < currentStructures.length)
653
- currentStructures.length = sharedLength;
654
- }
655
- let result;
656
- if (currentUnpackr.randomAccessStructure && src[position$1] < 0x40 && src[position$1] >= 0x20 && readStruct) {
657
- result = readStruct(src, position$1, srcEnd, currentUnpackr);
658
- src = null; // dispose of this so that recursive unpack calls don't save state
659
- if (!(options && options.lazy) && result)
660
- result = result.toJSON();
661
- position$1 = srcEnd;
662
- } else
663
- result = read();
664
- if (bundledStrings$1) { // bundled strings to skip past
665
- position$1 = bundledStrings$1.postBundlePosition;
666
- bundledStrings$1 = null;
667
- }
668
- if (sequentialMode)
669
- // we only need to restore the structures if there was an error, but if we completed a read,
670
- // we can clear this out and keep the structures we read
671
- currentStructures.restoreStructures = null;
672
-
673
- if (position$1 == srcEnd) {
674
- // finished reading this source, cleanup references
675
- if (currentStructures && currentStructures.restoreStructures)
676
- restoreStructures();
677
- currentStructures = null;
678
- src = null;
679
- if (referenceMap)
680
- referenceMap = null;
681
- } else if (position$1 > srcEnd) {
682
- // over read
683
- throw new Error('Unexpected end of MessagePack data')
684
- } else if (!sequentialMode) {
685
- let jsonView;
686
- try {
687
- jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100);
688
- } catch(error) {
689
- jsonView = '(JSON view not available ' + error + ')';
690
- }
691
- throw new Error('Data read, but end of buffer not reached ' + jsonView)
692
- }
693
- // else more to read, but we are reading sequentially, so don't clear source yet
694
- return result
695
- } catch(error) {
696
- if (currentStructures && currentStructures.restoreStructures)
697
- restoreStructures();
698
- clearSource();
699
- if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer') || position$1 > srcEnd) {
700
- error.incomplete = true;
701
- }
702
- throw error
703
- }
704
- }
705
-
706
- function restoreStructures() {
707
- for (let id in currentStructures.restoreStructures) {
708
- currentStructures[id] = currentStructures.restoreStructures[id];
709
- }
710
- currentStructures.restoreStructures = null;
711
- }
712
-
713
- function read() {
714
- let token = src[position$1++];
715
- if (token < 0xa0) {
716
- if (token < 0x80) {
717
- if (token < 0x40)
718
- return token
719
- else {
720
- let structure = currentStructures[token & 0x3f] ||
721
- currentUnpackr.getStructures && loadStructures()[token & 0x3f];
722
- if (structure) {
723
- if (!structure.read) {
724
- structure.read = createStructureReader(structure, token & 0x3f);
725
- }
726
- return structure.read()
727
- } else
728
- return token
729
- }
730
- } else if (token < 0x90) {
731
- // map
732
- token -= 0x80;
733
- if (currentUnpackr.mapsAsObjects) {
734
- let object = {};
735
- for (let i = 0; i < token; i++) {
736
- let key = readKey();
737
- if (key === '__proto__')
738
- key = '__proto_';
739
- object[key] = read();
740
- }
741
- return object
742
- } else {
743
- let map = new Map();
744
- for (let i = 0; i < token; i++) {
745
- map.set(read(), read());
746
- }
747
- return map
748
- }
749
- } else {
750
- token -= 0x90;
751
- let array = new Array(token);
752
- for (let i = 0; i < token; i++) {
753
- array[i] = read();
754
- }
755
- if (currentUnpackr.freezeData)
756
- return Object.freeze(array)
757
- return array
758
- }
759
- } else if (token < 0xc0) {
760
- // fixstr
761
- let length = token - 0xa0;
762
- if (srcStringEnd >= position$1) {
763
- return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
764
- }
765
- if (srcStringEnd == 0 && srcEnd < 140) {
766
- // for small blocks, avoiding the overhead of the extract call is helpful
767
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
768
- if (string != null)
769
- return string
770
- }
771
- return readFixedString(length)
772
- } else {
773
- let value;
774
- switch (token) {
775
- case 0xc0: return null
776
- case 0xc1:
777
- if (bundledStrings$1) {
778
- value = read(); // followed by the length of the string in characters (not bytes!)
779
- if (value > 0)
780
- return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value)
781
- else
782
- return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value)
783
- }
784
- return C1; // "never-used", return special object to denote that
785
- case 0xc2: return false
786
- case 0xc3: return true
787
- case 0xc4:
788
- // bin 8
789
- value = src[position$1++];
790
- if (value === undefined)
791
- throw new Error('Unexpected end of buffer')
792
- return readBin(value)
793
- case 0xc5:
794
- // bin 16
795
- value = dataView.getUint16(position$1);
796
- position$1 += 2;
797
- return readBin(value)
798
- case 0xc6:
799
- // bin 32
800
- value = dataView.getUint32(position$1);
801
- position$1 += 4;
802
- return readBin(value)
803
- case 0xc7:
804
- // ext 8
805
- return readExt(src[position$1++])
806
- case 0xc8:
807
- // ext 16
808
- value = dataView.getUint16(position$1);
809
- position$1 += 2;
810
- return readExt(value)
811
- case 0xc9:
812
- // ext 32
813
- value = dataView.getUint32(position$1);
814
- position$1 += 4;
815
- return readExt(value)
816
- case 0xca:
817
- value = dataView.getFloat32(position$1);
818
- if (currentUnpackr.useFloat32 > 2) {
819
- // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
820
- let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)];
821
- position$1 += 4;
822
- return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier
823
- }
824
- position$1 += 4;
825
- return value
826
- case 0xcb:
827
- value = dataView.getFloat64(position$1);
828
- position$1 += 8;
829
- return value
830
- // uint handlers
831
- case 0xcc:
832
- return src[position$1++]
833
- case 0xcd:
834
- value = dataView.getUint16(position$1);
835
- position$1 += 2;
836
- return value
837
- case 0xce:
838
- value = dataView.getUint32(position$1);
839
- position$1 += 4;
840
- return value
841
- case 0xcf:
842
- if (currentUnpackr.int64AsType === 'number') {
843
- value = dataView.getUint32(position$1) * 0x100000000;
844
- value += dataView.getUint32(position$1 + 4);
845
- } else if (currentUnpackr.int64AsType === 'string') {
846
- value = dataView.getBigUint64(position$1).toString();
847
- } else if (currentUnpackr.int64AsType === 'auto') {
848
- value = dataView.getBigUint64(position$1);
849
- if (value<=BigInt(2)<<BigInt(52)) value=Number(value);
850
- } else
851
- value = dataView.getBigUint64(position$1);
852
- position$1 += 8;
853
- return value
854
-
855
- // int handlers
856
- case 0xd0:
857
- return dataView.getInt8(position$1++)
858
- case 0xd1:
859
- value = dataView.getInt16(position$1);
860
- position$1 += 2;
861
- return value
862
- case 0xd2:
863
- value = dataView.getInt32(position$1);
864
- position$1 += 4;
865
- return value
866
- case 0xd3:
867
- if (currentUnpackr.int64AsType === 'number') {
868
- value = dataView.getInt32(position$1) * 0x100000000;
869
- value += dataView.getUint32(position$1 + 4);
870
- } else if (currentUnpackr.int64AsType === 'string') {
871
- value = dataView.getBigInt64(position$1).toString();
872
- } else if (currentUnpackr.int64AsType === 'auto') {
873
- value = dataView.getBigInt64(position$1);
874
- if (value>=BigInt(-2)<<BigInt(52)&&value<=BigInt(2)<<BigInt(52)) value=Number(value);
875
- } else
876
- value = dataView.getBigInt64(position$1);
877
- position$1 += 8;
878
- return value
879
-
880
- case 0xd4:
881
- // fixext 1
882
- value = src[position$1++];
883
- if (value == 0x72) {
884
- return recordDefinition(src[position$1++] & 0x3f)
885
- } else {
886
- let extension = currentExtensions[value];
887
- if (extension) {
888
- if (extension.read) {
889
- position$1++; // skip filler byte
890
- return extension.read(read())
891
- } else if (extension.noBuffer) {
892
- position$1++; // skip filler byte
893
- return extension()
894
- } else
895
- return extension(src.subarray(position$1, ++position$1))
896
- } else
897
- throw new Error('Unknown extension ' + value)
898
- }
899
- case 0xd5:
900
- // fixext 2
901
- value = src[position$1];
902
- if (value == 0x72) {
903
- position$1++;
904
- return recordDefinition(src[position$1++] & 0x3f, src[position$1++])
905
- } else
906
- return readExt(2)
907
- case 0xd6:
908
- // fixext 4
909
- return readExt(4)
910
- case 0xd7:
911
- // fixext 8
912
- return readExt(8)
913
- case 0xd8:
914
- // fixext 16
915
- return readExt(16)
916
- case 0xd9:
917
- // str 8
918
- value = src[position$1++];
919
- if (srcStringEnd >= position$1) {
920
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
921
- }
922
- return readString8(value)
923
- case 0xda:
924
- // str 16
925
- value = dataView.getUint16(position$1);
926
- position$1 += 2;
927
- if (srcStringEnd >= position$1) {
928
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
929
- }
930
- return readString16(value)
931
- case 0xdb:
932
- // str 32
933
- value = dataView.getUint32(position$1);
934
- position$1 += 4;
935
- if (srcStringEnd >= position$1) {
936
- return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart)
937
- }
938
- return readString32(value)
939
- case 0xdc:
940
- // array 16
941
- value = dataView.getUint16(position$1);
942
- position$1 += 2;
943
- return readArray(value)
944
- case 0xdd:
945
- // array 32
946
- value = dataView.getUint32(position$1);
947
- position$1 += 4;
948
- return readArray(value)
949
- case 0xde:
950
- // map 16
951
- value = dataView.getUint16(position$1);
952
- position$1 += 2;
953
- return readMap(value)
954
- case 0xdf:
955
- // map 32
956
- value = dataView.getUint32(position$1);
957
- position$1 += 4;
958
- return readMap(value)
959
- default: // negative int
960
- if (token >= 0xe0)
961
- return token - 0x100
962
- if (token === undefined) {
963
- let error = new Error('Unexpected end of MessagePack data');
964
- error.incomplete = true;
965
- throw error
966
- }
967
- throw new Error('Unknown MessagePack token ' + token)
968
-
969
- }
970
- }
971
- }
972
- const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/;
973
- function createStructureReader(structure, firstId) {
974
- function readObject() {
975
- // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function
976
- if (readObject.count++ > inlineObjectReadThreshold) {
977
- let readObject = structure.read = (new Function('r', 'return function(){return ' + (currentUnpackr.freezeData ? 'Object.freeze' : '') +
978
- '({' + structure.map(key => key === '__proto__' ? '__proto_:r()' : validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '})}'))(read);
979
- if (structure.highByte === 0)
980
- structure.read = createSecondByteReader(firstId, structure.read);
981
- return readObject() // second byte is already read, if there is one so immediately read object
982
- }
983
- let object = {};
984
- for (let i = 0, l = structure.length; i < l; i++) {
985
- let key = structure[i];
986
- if (key === '__proto__')
987
- key = '__proto_';
988
- object[key] = read();
989
- }
990
- if (currentUnpackr.freezeData)
991
- return Object.freeze(object);
992
- return object
993
- }
994
- readObject.count = 0;
995
- if (structure.highByte === 0) {
996
- return createSecondByteReader(firstId, readObject)
997
- }
998
- return readObject
999
- }
1000
-
1001
- const createSecondByteReader = (firstId, read0) => {
1002
- return function() {
1003
- let highByte = src[position$1++];
1004
- if (highByte === 0)
1005
- return read0()
1006
- let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5);
1007
- let structure = currentStructures[id] || loadStructures()[id];
1008
- if (!structure) {
1009
- throw new Error('Record id is not defined for ' + id)
1010
- }
1011
- if (!structure.read)
1012
- structure.read = createStructureReader(structure, firstId);
1013
- return structure.read()
1014
- }
1015
- };
1016
-
1017
- function loadStructures() {
1018
- let loadedStructures = saveState(() => {
1019
- // save the state in case getStructures modifies our buffer
1020
- src = null;
1021
- return currentUnpackr.getStructures()
1022
- });
1023
- return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures)
1024
- }
1025
-
1026
- var readFixedString = readStringJS;
1027
- var readString8 = readStringJS;
1028
- var readString16 = readStringJS;
1029
- var readString32 = readStringJS;
1030
- function readStringJS(length) {
1031
- let result;
1032
- if (length < 16) {
1033
- if (result = shortStringInJS(length))
1034
- return result
1035
- }
1036
- if (length > 64 && decoder)
1037
- return decoder.decode(src.subarray(position$1, position$1 += length))
1038
- const end = position$1 + length;
1039
- const units = [];
1040
- result = '';
1041
- while (position$1 < end) {
1042
- const byte1 = src[position$1++];
1043
- if ((byte1 & 0x80) === 0) {
1044
- // 1 byte
1045
- units.push(byte1);
1046
- } else if ((byte1 & 0xe0) === 0xc0) {
1047
- // 2 bytes
1048
- const byte2 = src[position$1++] & 0x3f;
1049
- units.push(((byte1 & 0x1f) << 6) | byte2);
1050
- } else if ((byte1 & 0xf0) === 0xe0) {
1051
- // 3 bytes
1052
- const byte2 = src[position$1++] & 0x3f;
1053
- const byte3 = src[position$1++] & 0x3f;
1054
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
1055
- } else if ((byte1 & 0xf8) === 0xf0) {
1056
- // 4 bytes
1057
- const byte2 = src[position$1++] & 0x3f;
1058
- const byte3 = src[position$1++] & 0x3f;
1059
- const byte4 = src[position$1++] & 0x3f;
1060
- let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
1061
- if (unit > 0xffff) {
1062
- unit -= 0x10000;
1063
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
1064
- unit = 0xdc00 | (unit & 0x3ff);
1065
- }
1066
- units.push(unit);
1067
- } else {
1068
- units.push(byte1);
1069
- }
1070
-
1071
- if (units.length >= 0x1000) {
1072
- result += fromCharCode.apply(String, units);
1073
- units.length = 0;
1074
- }
1075
- }
1076
-
1077
- if (units.length > 0) {
1078
- result += fromCharCode.apply(String, units);
1079
- }
1080
-
1081
- return result
1082
- }
1083
-
1084
- function readArray(length) {
1085
- let array = new Array(length);
1086
- for (let i = 0; i < length; i++) {
1087
- array[i] = read();
1088
- }
1089
- if (currentUnpackr.freezeData)
1090
- return Object.freeze(array)
1091
- return array
1092
- }
1093
-
1094
- function readMap(length) {
1095
- if (currentUnpackr.mapsAsObjects) {
1096
- let object = {};
1097
- for (let i = 0; i < length; i++) {
1098
- let key = readKey();
1099
- if (key === '__proto__')
1100
- key = '__proto_';
1101
- object[key] = read();
1102
- }
1103
- return object
1104
- } else {
1105
- let map = new Map();
1106
- for (let i = 0; i < length; i++) {
1107
- map.set(read(), read());
1108
- }
1109
- return map
1110
- }
1111
- }
1112
-
1113
- var fromCharCode = String.fromCharCode;
1114
- function longStringInJS(length) {
1115
- let start = position$1;
1116
- let bytes = new Array(length);
1117
- for (let i = 0; i < length; i++) {
1118
- const byte = src[position$1++];
1119
- if ((byte & 0x80) > 0) {
1120
- position$1 = start;
1121
- return
1122
- }
1123
- bytes[i] = byte;
1124
- }
1125
- return fromCharCode.apply(String, bytes)
1126
- }
1127
- function shortStringInJS(length) {
1128
- if (length < 4) {
1129
- if (length < 2) {
1130
- if (length === 0)
1131
- return ''
1132
- else {
1133
- let a = src[position$1++];
1134
- if ((a & 0x80) > 1) {
1135
- position$1 -= 1;
1136
- return
1137
- }
1138
- return fromCharCode(a)
1139
- }
1140
- } else {
1141
- let a = src[position$1++];
1142
- let b = src[position$1++];
1143
- if ((a & 0x80) > 0 || (b & 0x80) > 0) {
1144
- position$1 -= 2;
1145
- return
1146
- }
1147
- if (length < 3)
1148
- return fromCharCode(a, b)
1149
- let c = src[position$1++];
1150
- if ((c & 0x80) > 0) {
1151
- position$1 -= 3;
1152
- return
1153
- }
1154
- return fromCharCode(a, b, c)
1155
- }
1156
- } else {
1157
- let a = src[position$1++];
1158
- let b = src[position$1++];
1159
- let c = src[position$1++];
1160
- let d = src[position$1++];
1161
- if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {
1162
- position$1 -= 4;
1163
- return
1164
- }
1165
- if (length < 6) {
1166
- if (length === 4)
1167
- return fromCharCode(a, b, c, d)
1168
- else {
1169
- let e = src[position$1++];
1170
- if ((e & 0x80) > 0) {
1171
- position$1 -= 5;
1172
- return
1173
- }
1174
- return fromCharCode(a, b, c, d, e)
1175
- }
1176
- } else if (length < 8) {
1177
- let e = src[position$1++];
1178
- let f = src[position$1++];
1179
- if ((e & 0x80) > 0 || (f & 0x80) > 0) {
1180
- position$1 -= 6;
1181
- return
1182
- }
1183
- if (length < 7)
1184
- return fromCharCode(a, b, c, d, e, f)
1185
- let g = src[position$1++];
1186
- if ((g & 0x80) > 0) {
1187
- position$1 -= 7;
1188
- return
1189
- }
1190
- return fromCharCode(a, b, c, d, e, f, g)
1191
- } else {
1192
- let e = src[position$1++];
1193
- let f = src[position$1++];
1194
- let g = src[position$1++];
1195
- let h = src[position$1++];
1196
- if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {
1197
- position$1 -= 8;
1198
- return
1199
- }
1200
- if (length < 10) {
1201
- if (length === 8)
1202
- return fromCharCode(a, b, c, d, e, f, g, h)
1203
- else {
1204
- let i = src[position$1++];
1205
- if ((i & 0x80) > 0) {
1206
- position$1 -= 9;
1207
- return
1208
- }
1209
- return fromCharCode(a, b, c, d, e, f, g, h, i)
1210
- }
1211
- } else if (length < 12) {
1212
- let i = src[position$1++];
1213
- let j = src[position$1++];
1214
- if ((i & 0x80) > 0 || (j & 0x80) > 0) {
1215
- position$1 -= 10;
1216
- return
1217
- }
1218
- if (length < 11)
1219
- return fromCharCode(a, b, c, d, e, f, g, h, i, j)
1220
- let k = src[position$1++];
1221
- if ((k & 0x80) > 0) {
1222
- position$1 -= 11;
1223
- return
1224
- }
1225
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k)
1226
- } else {
1227
- let i = src[position$1++];
1228
- let j = src[position$1++];
1229
- let k = src[position$1++];
1230
- let l = src[position$1++];
1231
- if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {
1232
- position$1 -= 12;
1233
- return
1234
- }
1235
- if (length < 14) {
1236
- if (length === 12)
1237
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)
1238
- else {
1239
- let m = src[position$1++];
1240
- if ((m & 0x80) > 0) {
1241
- position$1 -= 13;
1242
- return
1243
- }
1244
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)
1245
- }
1246
- } else {
1247
- let m = src[position$1++];
1248
- let n = src[position$1++];
1249
- if ((m & 0x80) > 0 || (n & 0x80) > 0) {
1250
- position$1 -= 14;
1251
- return
1252
- }
1253
- if (length < 15)
1254
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)
1255
- let o = src[position$1++];
1256
- if ((o & 0x80) > 0) {
1257
- position$1 -= 15;
1258
- return
1259
- }
1260
- return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
1261
- }
1262
- }
1263
- }
1264
- }
1265
- }
1266
-
1267
- function readOnlyJSString() {
1268
- let token = src[position$1++];
1269
- let length;
1270
- if (token < 0xc0) {
1271
- // fixstr
1272
- length = token - 0xa0;
1273
- } else {
1274
- switch(token) {
1275
- case 0xd9:
1276
- // str 8
1277
- length = src[position$1++];
1278
- break
1279
- case 0xda:
1280
- // str 16
1281
- length = dataView.getUint16(position$1);
1282
- position$1 += 2;
1283
- break
1284
- case 0xdb:
1285
- // str 32
1286
- length = dataView.getUint32(position$1);
1287
- position$1 += 4;
1288
- break
1289
- default:
1290
- throw new Error('Expected string')
1291
- }
1292
- }
1293
- return readStringJS(length)
1294
- }
1295
-
1296
-
1297
- function readBin(length) {
1298
- return currentUnpackr.copyBuffers ?
1299
- // specifically use the copying slice (not the node one)
1300
- Uint8Array.prototype.slice.call(src, position$1, position$1 += length) :
1301
- src.subarray(position$1, position$1 += length)
1302
- }
1303
- function readExt(length) {
1304
- let type = src[position$1++];
1305
- if (currentExtensions[type]) {
1306
- let end;
1307
- return currentExtensions[type](src.subarray(position$1, end = (position$1 += length)), (readPosition) => {
1308
- position$1 = readPosition;
1309
- try {
1310
- return read();
1311
- } finally {
1312
- position$1 = end;
1313
- }
1314
- })
1315
- }
1316
- else
1317
- throw new Error('Unknown extension type ' + type)
1318
- }
1319
-
1320
- var keyCache = new Array(4096);
1321
- function readKey() {
1322
- let length = src[position$1++];
1323
- if (length >= 0xa0 && length < 0xc0) {
1324
- // fixstr, potentially use key cache
1325
- length = length - 0xa0;
1326
- if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway)
1327
- return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart)
1328
- else if (!(srcStringEnd == 0 && srcEnd < 180))
1329
- return readFixedString(length)
1330
- } else { // not cacheable, go back and do a standard read
1331
- position$1--;
1332
- return asSafeString(read())
1333
- }
1334
- let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff;
1335
- let entry = keyCache[key];
1336
- let checkPosition = position$1;
1337
- let end = position$1 + length - 3;
1338
- let chunk;
1339
- let i = 0;
1340
- if (entry && entry.bytes == length) {
1341
- while (checkPosition < end) {
1342
- chunk = dataView.getUint32(checkPosition);
1343
- if (chunk != entry[i++]) {
1344
- checkPosition = 0x70000000;
1345
- break
1346
- }
1347
- checkPosition += 4;
1348
- }
1349
- end += 3;
1350
- while (checkPosition < end) {
1351
- chunk = src[checkPosition++];
1352
- if (chunk != entry[i++]) {
1353
- checkPosition = 0x70000000;
1354
- break
1355
- }
1356
- }
1357
- if (checkPosition === end) {
1358
- position$1 = checkPosition;
1359
- return entry.string
1360
- }
1361
- end -= 3;
1362
- checkPosition = position$1;
1363
- }
1364
- entry = [];
1365
- keyCache[key] = entry;
1366
- entry.bytes = length;
1367
- while (checkPosition < end) {
1368
- chunk = dataView.getUint32(checkPosition);
1369
- entry.push(chunk);
1370
- checkPosition += 4;
1371
- }
1372
- end += 3;
1373
- while (checkPosition < end) {
1374
- chunk = src[checkPosition++];
1375
- entry.push(chunk);
1376
- }
1377
- // for small blocks, avoiding the overhead of the extract call is helpful
1378
- let string = length < 16 ? shortStringInJS(length) : longStringInJS(length);
1379
- if (string != null)
1380
- return entry.string = string
1381
- return entry.string = readFixedString(length)
1382
- }
1383
-
1384
- function asSafeString(property) {
1385
- // protect against expensive (DoS) string conversions
1386
- if (typeof property === 'string') return property;
1387
- if (typeof property === 'number' || typeof property === 'boolean' || typeof property === 'bigint') return property.toString();
1388
- if (property == null) return property + '';
1389
- throw new Error('Invalid property type for record', typeof property);
1390
- }
1391
- // the registration of the record definition extension (as "r")
1392
- const recordDefinition = (id, highByte) => {
1393
- let structure = read().map(asSafeString); // ensure that all keys are strings and
1394
- // that the array is mutable
1395
- let firstByte = id;
1396
- if (highByte !== undefined) {
1397
- id = id < 32 ? -((highByte << 5) + id) : ((highByte << 5) + id);
1398
- structure.highByte = highByte;
1399
- }
1400
- let existingStructure = currentStructures[id];
1401
- // If it is a shared structure, we need to restore any changes after reading.
1402
- // Also in sequential mode, we may get incomplete reads and thus errors, and we need to restore
1403
- // to the state prior to an incomplete read in order to properly resume.
1404
- if (existingStructure && (existingStructure.isShared || sequentialMode)) {
1405
- (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure;
1406
- }
1407
- currentStructures[id] = structure;
1408
- structure.read = createStructureReader(structure, firstByte);
1409
- return structure.read()
1410
- };
1411
- currentExtensions[0] = () => {}; // notepack defines extension 0 to mean undefined, so use that as the default here
1412
- currentExtensions[0].noBuffer = true;
1413
-
1414
- currentExtensions[0x42] = (data) => {
1415
- // decode bigint
1416
- let length = data.length;
1417
- let value = BigInt(data[0] & 0x80 ? data[0] - 0x100 : data[0]);
1418
- for (let i = 1; i < length; i++) {
1419
- value <<= 8n;
1420
- value += BigInt(data[i]);
1421
- }
1422
- return value;
1423
- };
1424
-
1425
- let errors = { Error, TypeError, ReferenceError };
1426
- currentExtensions[0x65] = () => {
1427
- let data = read();
1428
- return (errors[data[0]] || Error)(data[1], { cause: data[2] })
1429
- };
1430
-
1431
- currentExtensions[0x69] = (data) => {
1432
- // id extension (for structured clones)
1433
- if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
1434
- let id = dataView.getUint32(position$1 - 4);
1435
- if (!referenceMap)
1436
- referenceMap = new Map();
1437
- let token = src[position$1];
1438
- let target;
1439
- // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read
1440
- // ahead past references to record structure definitions
1441
- if (token >= 0x90 && token < 0xa0 || token == 0xdc || token == 0xdd)
1442
- target = [];
1443
- else
1444
- target = {};
1445
-
1446
- let refEntry = { target }; // a placeholder object
1447
- referenceMap.set(id, refEntry);
1448
- let targetProperties = read(); // read the next value as the target object to id
1449
- if (refEntry.used) // there is a cycle, so we have to assign properties to original target
1450
- return Object.assign(target, targetProperties)
1451
- refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one
1452
- return targetProperties // no cycle, can just use the returned read object
1453
- };
1454
-
1455
- currentExtensions[0x70] = (data) => {
1456
- // pointer extension (for structured clones)
1457
- if (currentUnpackr.structuredClone === false) throw new Error('Structured clone extension is disabled')
1458
- let id = dataView.getUint32(position$1 - 4);
1459
- let refEntry = referenceMap.get(id);
1460
- refEntry.used = true;
1461
- return refEntry.target
1462
- };
1463
-
1464
- currentExtensions[0x73] = () => new Set(read());
1465
-
1466
- const typedArrays = ['Int8','Uint8','Uint8Clamped','Int16','Uint16','Int32','Uint32','Float32','Float64','BigInt64','BigUint64'].map(type => type + 'Array');
1467
-
1468
- let glbl = typeof globalThis === 'object' ? globalThis : window;
1469
- currentExtensions[0x74] = (data) => {
1470
- let typeCode = data[0];
1471
- let typedArrayName = typedArrays[typeCode];
1472
- if (!typedArrayName) {
1473
- if (typeCode === 16) {
1474
- let ab = new ArrayBuffer(data.length - 1);
1475
- let u8 = new Uint8Array(ab);
1476
- u8.set(data.subarray(1));
1477
- return ab;
1478
- }
1479
- throw new Error('Could not find typed array for code ' + typeCode)
1480
- }
1481
- // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned
1482
- return new glbl[typedArrayName](Uint8Array.prototype.slice.call(data, 1).buffer)
1483
- };
1484
- currentExtensions[0x78] = () => {
1485
- let data = read();
1486
- return new RegExp(data[0], data[1])
1487
- };
1488
- const TEMP_BUNDLE = [];
1489
- currentExtensions[0x62] = (data) => {
1490
- let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3];
1491
- let dataPosition = position$1;
1492
- position$1 += dataSize - data.length;
1493
- bundledStrings$1 = TEMP_BUNDLE;
1494
- bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()];
1495
- bundledStrings$1.position0 = 0;
1496
- bundledStrings$1.position1 = 0;
1497
- bundledStrings$1.postBundlePosition = position$1;
1498
- position$1 = dataPosition;
1499
- return read()
1500
- };
1501
-
1502
- currentExtensions[0xff] = (data) => {
1503
- // 32-bit date extension
1504
- if (data.length == 4)
1505
- return new Date((data[0] * 0x1000000 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000)
1506
- else if (data.length == 8)
1507
- return new Date(
1508
- ((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1000000 +
1509
- ((data[3] & 0x3) * 0x100000000 + data[4] * 0x1000000 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000)
1510
- else if (data.length == 12)// TODO: Implement support for negative
1511
- return new Date(
1512
- ((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1000000 +
1513
- (((data[4] & 0x80) ? -0x1000000000000 : 0) + data[6] * 0x10000000000 + data[7] * 0x100000000 + data[8] * 0x1000000 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000)
1514
- else
1515
- return new Date('invalid')
1516
- }; // notepack defines extension 0 to mean undefined, so use that as the default here
1517
- // registration of bulk record definition?
1518
- // currentExtensions[0x52] = () =>
1519
-
1520
- function saveState(callback) {
1521
- let savedSrcEnd = srcEnd;
1522
- let savedPosition = position$1;
1523
- let savedSrcStringStart = srcStringStart;
1524
- let savedSrcStringEnd = srcStringEnd;
1525
- let savedSrcString = srcString;
1526
- let savedReferenceMap = referenceMap;
1527
- let savedBundledStrings = bundledStrings$1;
1528
-
1529
- // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)
1530
- let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed
1531
- let savedStructures = currentStructures;
1532
- let savedStructuresContents = currentStructures.slice(0, currentStructures.length);
1533
- let savedPackr = currentUnpackr;
1534
- let savedSequentialMode = sequentialMode;
1535
- let value = callback();
1536
- srcEnd = savedSrcEnd;
1537
- position$1 = savedPosition;
1538
- srcStringStart = savedSrcStringStart;
1539
- srcStringEnd = savedSrcStringEnd;
1540
- srcString = savedSrcString;
1541
- referenceMap = savedReferenceMap;
1542
- bundledStrings$1 = savedBundledStrings;
1543
- src = savedSrc;
1544
- sequentialMode = savedSequentialMode;
1545
- currentStructures = savedStructures;
1546
- currentStructures.splice(0, currentStructures.length, ...savedStructuresContents);
1547
- currentUnpackr = savedPackr;
1548
- dataView = new DataView(src.buffer, src.byteOffset, src.byteLength);
1549
- return value
1550
- }
1551
- function clearSource() {
1552
- src = null;
1553
- referenceMap = null;
1554
- currentStructures = null;
1555
- }
1556
-
1557
- const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding
1558
- for (let i = 0; i < 256; i++) {
1559
- mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
1560
- }
1561
- var defaultUnpackr = new Unpackr({ useRecords: false });
1562
- defaultUnpackr.unpack;
1563
- defaultUnpackr.unpackMultiple;
1564
- defaultUnpackr.unpack;
1565
- let f32Array = new Float32Array(1);
1566
- new Uint8Array(f32Array.buffer, 0, 4);
1567
-
1568
- let textEncoder;
1569
- try {
1570
- textEncoder = new TextEncoder();
1571
- } catch (error) {}
1572
- let extensions, extensionClasses;
1573
- const hasNodeBuffer = typeof Buffer !== 'undefined';
1574
- const ByteArrayAllocate = hasNodeBuffer ?
1575
- function(length) { return Buffer.allocUnsafeSlow(length) } : Uint8Array;
1576
- const ByteArray = hasNodeBuffer ? Buffer : Uint8Array;
1577
- const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000;
1578
- let target, keysTarget;
1579
- let targetView;
1580
- let position = 0;
1581
- let safeEnd;
1582
- let bundledStrings = null;
1583
- let writeStructSlots;
1584
- const MAX_BUNDLE_SIZE = 0x5500; // maximum characters such that the encoded bytes fits in 16 bits.
1585
- const hasNonLatin = /[\u0080-\uFFFF]/;
1586
- const RECORD_SYMBOL = Symbol('record-id');
1587
- class Packr extends Unpackr {
1588
- constructor(options) {
1589
- super(options);
1590
- this.offset = 0;
1591
- let start;
1592
- let hasSharedUpdate;
1593
- let structures;
1594
- let referenceMap;
1595
- let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position) {
1596
- return target.utf8Write(string, position, 0xffffffff)
1597
- } : (textEncoder && textEncoder.encodeInto) ?
1598
- function(string, position) {
1599
- return textEncoder.encodeInto(string, target.subarray(position)).written
1600
- } : false;
1601
-
1602
- let packr = this;
1603
- if (!options)
1604
- options = {};
1605
- let isSequential = options && options.sequential;
1606
- let hasSharedStructures = options.structures || options.saveStructures;
1607
- let maxSharedStructures = options.maxSharedStructures;
1608
- if (maxSharedStructures == null)
1609
- maxSharedStructures = hasSharedStructures ? 32 : 0;
1610
- if (maxSharedStructures > 8160)
1611
- throw new Error('Maximum maxSharedStructure is 8160')
1612
- if (options.structuredClone && options.moreTypes == undefined) {
1613
- this.moreTypes = true;
1614
- }
1615
- let maxOwnStructures = options.maxOwnStructures;
1616
- if (maxOwnStructures == null)
1617
- maxOwnStructures = hasSharedStructures ? 32 : 64;
1618
- if (!this.structures && options.useRecords != false)
1619
- this.structures = [];
1620
- // two byte record ids for shared structures
1621
- let useTwoByteRecords = maxSharedStructures > 32 || (maxOwnStructures + maxSharedStructures > 64);
1622
- let sharedLimitId = maxSharedStructures + 0x40;
1623
- let maxStructureId = maxSharedStructures + maxOwnStructures + 0x40;
1624
- if (maxStructureId > 8256) {
1625
- throw new Error('Maximum maxSharedStructure + maxOwnStructure is 8192')
1626
- }
1627
- let recordIdsToRemove = [];
1628
- let transitionsCount = 0;
1629
- let serializationsSinceTransitionRebuild = 0;
1630
-
1631
- this.pack = this.encode = function(value, encodeOptions) {
1632
- if (!target) {
1633
- target = new ByteArrayAllocate(8192);
1634
- targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192));
1635
- position = 0;
1636
- }
1637
- safeEnd = target.length - 10;
1638
- if (safeEnd - position < 0x800) {
1639
- // don't start too close to the end,
1640
- target = new ByteArrayAllocate(target.length);
1641
- targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length));
1642
- safeEnd = target.length - 10;
1643
- position = 0;
1644
- } else
1645
- position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster
1646
- start = position;
1647
- if (encodeOptions & RESERVE_START_SPACE) position += (encodeOptions & 0xff);
1648
- referenceMap = packr.structuredClone ? new Map() : null;
1649
- if (packr.bundleStrings && typeof value !== 'string') {
1650
- bundledStrings = [];
1651
- bundledStrings.size = Infinity; // force a new bundle start on first string
1652
- } else
1653
- bundledStrings = null;
1654
- structures = packr.structures;
1655
- if (structures) {
1656
- if (structures.uninitialized)
1657
- structures = packr._mergeStructures(packr.getStructures());
1658
- let sharedLength = structures.sharedLength || 0;
1659
- if (sharedLength > maxSharedStructures) {
1660
- //if (maxSharedStructures <= 32 && structures.sharedLength > 32) // TODO: could support this, but would need to update the limit ids
1661
- throw new Error('Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to ' + structures.sharedLength)
1662
- }
1663
- if (!structures.transitions) {
1664
- // rebuild our structure transitions
1665
- structures.transitions = Object.create(null);
1666
- for (let i = 0; i < sharedLength; i++) {
1667
- let keys = structures[i];
1668
- if (!keys)
1669
- continue
1670
- let nextTransition, transition = structures.transitions;
1671
- for (let j = 0, l = keys.length; j < l; j++) {
1672
- let key = keys[j];
1673
- nextTransition = transition[key];
1674
- if (!nextTransition) {
1675
- nextTransition = transition[key] = Object.create(null);
1676
- }
1677
- transition = nextTransition;
1678
- }
1679
- transition[RECORD_SYMBOL] = i + 0x40;
1680
- }
1681
- this.lastNamedStructuresLength = sharedLength;
1682
- }
1683
- if (!isSequential) {
1684
- structures.nextId = sharedLength + 0x40;
1685
- }
1686
- }
1687
- if (hasSharedUpdate)
1688
- hasSharedUpdate = false;
1689
- let encodingError;
1690
- try {
1691
- if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object)
1692
- writeStruct(value);
1693
- else
1694
- pack(value);
1695
- let lastBundle = bundledStrings;
1696
- if (bundledStrings)
1697
- writeBundles(start, pack, 0);
1698
- if (referenceMap && referenceMap.idsToInsert) {
1699
- let idsToInsert = referenceMap.idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1);
1700
- let i = idsToInsert.length;
1701
- let incrementPosition = -1;
1702
- while (lastBundle && i > 0) {
1703
- let insertionPoint = idsToInsert[--i].offset + start;
1704
- if (insertionPoint < (lastBundle.stringsPosition + start) && incrementPosition === -1)
1705
- incrementPosition = 0;
1706
- if (insertionPoint > (lastBundle.position + start)) {
1707
- if (incrementPosition >= 0)
1708
- incrementPosition += 6;
1709
- } else {
1710
- if (incrementPosition >= 0) {
1711
- // update the bundle reference now
1712
- targetView.setUint32(lastBundle.position + start,
1713
- targetView.getUint32(lastBundle.position + start) + incrementPosition);
1714
- incrementPosition = -1; // reset
1715
- }
1716
- lastBundle = lastBundle.previous;
1717
- i++;
1718
- }
1719
- }
1720
- if (incrementPosition >= 0 && lastBundle) {
1721
- // update the bundle reference now
1722
- targetView.setUint32(lastBundle.position + start,
1723
- targetView.getUint32(lastBundle.position + start) + incrementPosition);
1724
- }
1725
- position += idsToInsert.length * 6;
1726
- if (position > safeEnd)
1727
- makeRoom(position);
1728
- packr.offset = position;
1729
- let serialized = insertIds(target.subarray(start, position), idsToInsert);
1730
- referenceMap = null;
1731
- return serialized
1732
- }
1733
- packr.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially
1734
- if (encodeOptions & REUSE_BUFFER_MODE) {
1735
- target.start = start;
1736
- target.end = position;
1737
- return target
1738
- }
1739
- return target.subarray(start, position) // position can change if we call pack again in saveStructures, so we get the buffer now
1740
- } catch(error) {
1741
- encodingError = error;
1742
- throw error;
1743
- } finally {
1744
- if (structures) {
1745
- resetStructures();
1746
- if (hasSharedUpdate && packr.saveStructures) {
1747
- let sharedLength = structures.sharedLength || 0;
1748
- // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save
1749
- let returnBuffer = target.subarray(start, position);
1750
- let newSharedData = prepareStructures(structures, packr);
1751
- if (!encodingError) { // TODO: If there is an encoding error, should make the structures as uninitialized so they get rebuilt next time
1752
- if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) {
1753
- // get updated structures and try again if the update failed
1754
- return packr.pack(value, encodeOptions)
1755
- }
1756
- packr.lastNamedStructuresLength = sharedLength;
1757
- // don't keep large buffers around
1758
- if (target.length > 0x40000000) target = null;
1759
- return returnBuffer
1760
- }
1761
- }
1762
- }
1763
- // don't keep large buffers around, they take too much memory and cause problems (limit at 1GB)
1764
- if (target.length > 0x40000000) target = null;
1765
- if (encodeOptions & RESET_BUFFER_MODE)
1766
- position = start;
1767
- }
1768
- };
1769
- const resetStructures = () => {
1770
- if (serializationsSinceTransitionRebuild < 10)
1771
- serializationsSinceTransitionRebuild++;
1772
- let sharedLength = structures.sharedLength || 0;
1773
- if (structures.length > sharedLength && !isSequential)
1774
- structures.length = sharedLength;
1775
- if (transitionsCount > 10000) {
1776
- // force a rebuild occasionally after a lot of transitions so it can get cleaned up
1777
- structures.transitions = null;
1778
- serializationsSinceTransitionRebuild = 0;
1779
- transitionsCount = 0;
1780
- if (recordIdsToRemove.length > 0)
1781
- recordIdsToRemove = [];
1782
- } else if (recordIdsToRemove.length > 0 && !isSequential) {
1783
- for (let i = 0, l = recordIdsToRemove.length; i < l; i++) {
1784
- recordIdsToRemove[i][RECORD_SYMBOL] = 0;
1785
- }
1786
- recordIdsToRemove = [];
1787
- }
1788
- };
1789
- const packArray = (value) => {
1790
- var length = value.length;
1791
- if (length < 0x10) {
1792
- target[position++] = 0x90 | length;
1793
- } else if (length < 0x10000) {
1794
- target[position++] = 0xdc;
1795
- target[position++] = length >> 8;
1796
- target[position++] = length & 0xff;
1797
- } else {
1798
- target[position++] = 0xdd;
1799
- targetView.setUint32(position, length);
1800
- position += 4;
1801
- }
1802
- for (let i = 0; i < length; i++) {
1803
- pack(value[i]);
1804
- }
1805
- };
1806
- const pack = (value) => {
1807
- if (position > safeEnd)
1808
- target = makeRoom(position);
1809
-
1810
- var type = typeof value;
1811
- var length;
1812
- if (type === 'string') {
1813
- let strLength = value.length;
1814
- if (bundledStrings && strLength >= 4 && strLength < 0x1000) {
1815
- if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {
1816
- let extStart;
1817
- let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10;
1818
- if (position + maxBytes > safeEnd)
1819
- target = makeRoom(position + maxBytes);
1820
- let lastBundle;
1821
- if (bundledStrings.position) { // here we use the 0x62 extension to write the last bundle and reserve space for the reference pointer to the next/current bundle
1822
- lastBundle = bundledStrings;
1823
- target[position] = 0xc8; // ext 16
1824
- position += 3; // reserve for the writing bundle size
1825
- target[position++] = 0x62; // 'b'
1826
- extStart = position - start;
1827
- position += 4; // reserve for writing bundle reference
1828
- writeBundles(start, pack, 0); // write the last bundles
1829
- targetView.setUint16(extStart + start - 3, position - start - extStart);
1830
- } else { // here we use the 0x62 extension just to reserve the space for the reference pointer to the bundle (will be updated once the bundle is written)
1831
- target[position++] = 0xd6; // fixext 4
1832
- target[position++] = 0x62; // 'b'
1833
- extStart = position - start;
1834
- position += 4; // reserve for writing bundle reference
1835
- }
1836
- bundledStrings = ['', '']; // create new ones
1837
- bundledStrings.previous = lastBundle;
1838
- bundledStrings.size = 0;
1839
- bundledStrings.position = extStart;
1840
- }
1841
- let twoByte = hasNonLatin.test(value);
1842
- bundledStrings[twoByte ? 0 : 1] += value;
1843
- target[position++] = 0xc1;
1844
- pack(twoByte ? -strLength : strLength);
1845
- return
1846
- }
1847
- let headerSize;
1848
- // first we estimate the header size, so we can write to the correct location
1849
- if (strLength < 0x20) {
1850
- headerSize = 1;
1851
- } else if (strLength < 0x100) {
1852
- headerSize = 2;
1853
- } else if (strLength < 0x10000) {
1854
- headerSize = 3;
1855
- } else {
1856
- headerSize = 5;
1857
- }
1858
- let maxBytes = strLength * 3;
1859
- if (position + maxBytes > safeEnd)
1860
- target = makeRoom(position + maxBytes);
1861
-
1862
- if (strLength < 0x40 || !encodeUtf8) {
1863
- let i, c1, c2, strPosition = position + headerSize;
1864
- for (i = 0; i < strLength; i++) {
1865
- c1 = value.charCodeAt(i);
1866
- if (c1 < 0x80) {
1867
- target[strPosition++] = c1;
1868
- } else if (c1 < 0x800) {
1869
- target[strPosition++] = c1 >> 6 | 0xc0;
1870
- target[strPosition++] = c1 & 0x3f | 0x80;
1871
- } else if (
1872
- (c1 & 0xfc00) === 0xd800 &&
1873
- ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
1874
- ) {
1875
- c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
1876
- i++;
1877
- target[strPosition++] = c1 >> 18 | 0xf0;
1878
- target[strPosition++] = c1 >> 12 & 0x3f | 0x80;
1879
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1880
- target[strPosition++] = c1 & 0x3f | 0x80;
1881
- } else {
1882
- target[strPosition++] = c1 >> 12 | 0xe0;
1883
- target[strPosition++] = c1 >> 6 & 0x3f | 0x80;
1884
- target[strPosition++] = c1 & 0x3f | 0x80;
1885
- }
1886
- }
1887
- length = strPosition - position - headerSize;
1888
- } else {
1889
- length = encodeUtf8(value, position + headerSize);
1890
- }
1891
-
1892
- if (length < 0x20) {
1893
- target[position++] = 0xa0 | length;
1894
- } else if (length < 0x100) {
1895
- if (headerSize < 2) {
1896
- target.copyWithin(position + 2, position + 1, position + 1 + length);
1897
- }
1898
- target[position++] = 0xd9;
1899
- target[position++] = length;
1900
- } else if (length < 0x10000) {
1901
- if (headerSize < 3) {
1902
- target.copyWithin(position + 3, position + 2, position + 2 + length);
1903
- }
1904
- target[position++] = 0xda;
1905
- target[position++] = length >> 8;
1906
- target[position++] = length & 0xff;
1907
- } else {
1908
- if (headerSize < 5) {
1909
- target.copyWithin(position + 5, position + 3, position + 3 + length);
1910
- }
1911
- target[position++] = 0xdb;
1912
- targetView.setUint32(position, length);
1913
- position += 4;
1914
- }
1915
- position += length;
1916
- } else if (type === 'number') {
1917
- if (value >>> 0 === value) {// positive integer, 32-bit or less
1918
- // positive uint
1919
- if (value < 0x20 || (value < 0x80 && this.useRecords === false) || (value < 0x40 && !this.randomAccessStructure)) {
1920
- target[position++] = value;
1921
- } else if (value < 0x100) {
1922
- target[position++] = 0xcc;
1923
- target[position++] = value;
1924
- } else if (value < 0x10000) {
1925
- target[position++] = 0xcd;
1926
- target[position++] = value >> 8;
1927
- target[position++] = value & 0xff;
1928
- } else {
1929
- target[position++] = 0xce;
1930
- targetView.setUint32(position, value);
1931
- position += 4;
1932
- }
1933
- } else if (value >> 0 === value) { // negative integer
1934
- if (value >= -0x20) {
1935
- target[position++] = 0x100 + value;
1936
- } else if (value >= -0x80) {
1937
- target[position++] = 0xd0;
1938
- target[position++] = value + 0x100;
1939
- } else if (value >= -0x8000) {
1940
- target[position++] = 0xd1;
1941
- targetView.setInt16(position, value);
1942
- position += 2;
1943
- } else {
1944
- target[position++] = 0xd2;
1945
- targetView.setInt32(position, value);
1946
- position += 4;
1947
- }
1948
- } else {
1949
- let useFloat32;
1950
- if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {
1951
- target[position++] = 0xca;
1952
- targetView.setFloat32(position, value);
1953
- let xShifted;
1954
- if (useFloat32 < 4 ||
1955
- // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved
1956
- ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {
1957
- position += 4;
1958
- return
1959
- } else
1960
- position--; // move back into position for writing a double
1961
- }
1962
- target[position++] = 0xcb;
1963
- targetView.setFloat64(position, value);
1964
- position += 8;
1965
- }
1966
- } else if (type === 'object' || type === 'function') {
1967
- if (!value)
1968
- target[position++] = 0xc0;
1969
- else {
1970
- if (referenceMap) {
1971
- let referee = referenceMap.get(value);
1972
- if (referee) {
1973
- if (!referee.id) {
1974
- let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []);
1975
- referee.id = idsToInsert.push(referee);
1976
- }
1977
- target[position++] = 0xd6; // fixext 4
1978
- target[position++] = 0x70; // "p" for pointer
1979
- targetView.setUint32(position, referee.id);
1980
- position += 4;
1981
- return
1982
- } else
1983
- referenceMap.set(value, { offset: position - start });
1984
- }
1985
- let constructor = value.constructor;
1986
- if (constructor === Object) {
1987
- writeObject(value);
1988
- } else if (constructor === Array) {
1989
- packArray(value);
1990
- } else if (constructor === Map) {
1991
- if (this.mapAsEmptyObject) target[position++] = 0x80;
1992
- else {
1993
- length = value.size;
1994
- if (length < 0x10) {
1995
- target[position++] = 0x80 | length;
1996
- } else if (length < 0x10000) {
1997
- target[position++] = 0xde;
1998
- target[position++] = length >> 8;
1999
- target[position++] = length & 0xff;
2000
- } else {
2001
- target[position++] = 0xdf;
2002
- targetView.setUint32(position, length);
2003
- position += 4;
2004
- }
2005
- for (let [key, entryValue] of value) {
2006
- pack(key);
2007
- pack(entryValue);
2008
- }
2009
- }
2010
- } else {
2011
- for (let i = 0, l = extensions.length; i < l; i++) {
2012
- let extensionClass = extensionClasses[i];
2013
- if (value instanceof extensionClass) {
2014
- let extension = extensions[i];
2015
- if (extension.write) {
2016
- if (extension.type) {
2017
- target[position++] = 0xd4; // one byte "tag" extension
2018
- target[position++] = extension.type;
2019
- target[position++] = 0;
2020
- }
2021
- let writeResult = extension.write.call(this, value);
2022
- if (writeResult === value) { // avoid infinite recursion
2023
- if (Array.isArray(value)) {
2024
- packArray(value);
2025
- } else {
2026
- writeObject(value);
2027
- }
2028
- } else {
2029
- pack(writeResult);
2030
- }
2031
- return
2032
- }
2033
- let currentTarget = target;
2034
- let currentTargetView = targetView;
2035
- let currentPosition = position;
2036
- target = null;
2037
- let result;
2038
- try {
2039
- result = extension.pack.call(this, value, (size) => {
2040
- // restore target and use it
2041
- target = currentTarget;
2042
- currentTarget = null;
2043
- position += size;
2044
- if (position > safeEnd)
2045
- makeRoom(position);
2046
- return {
2047
- target, targetView, position: position - size
2048
- }
2049
- }, pack);
2050
- } finally {
2051
- // restore current target information (unless already restored)
2052
- if (currentTarget) {
2053
- target = currentTarget;
2054
- targetView = currentTargetView;
2055
- position = currentPosition;
2056
- safeEnd = target.length - 10;
2057
- }
2058
- }
2059
- if (result) {
2060
- if (result.length + position > safeEnd)
2061
- makeRoom(result.length + position);
2062
- position = writeExtensionData(result, target, position, extension.type);
2063
- }
2064
- return
2065
- }
2066
- }
2067
- // check isArray after extensions, because extensions can extend Array
2068
- if (Array.isArray(value)) {
2069
- packArray(value);
2070
- } else {
2071
- // use this as an alternate mechanism for expressing how to serialize
2072
- if (value.toJSON) {
2073
- const json = value.toJSON();
2074
- // if for some reason value.toJSON returns itself it'll loop forever
2075
- if (json !== value)
2076
- return pack(json)
2077
- }
2078
-
2079
- // if there is a writeFunction, use it, otherwise just encode as undefined
2080
- if (type === 'function')
2081
- return pack(this.writeFunction && this.writeFunction(value));
2082
-
2083
- // no extension found, write as plain object
2084
- writeObject(value);
2085
- }
2086
- }
2087
- }
2088
- } else if (type === 'boolean') {
2089
- target[position++] = value ? 0xc3 : 0xc2;
2090
- } else if (type === 'bigint') {
2091
- if (value < (BigInt(1)<<BigInt(63)) && value >= -(BigInt(1)<<BigInt(63))) {
2092
- // use a signed int as long as it fits
2093
- target[position++] = 0xd3;
2094
- targetView.setBigInt64(position, value);
2095
- } else if (value < (BigInt(1)<<BigInt(64)) && value > 0) {
2096
- // if we can fit an unsigned int, use that
2097
- target[position++] = 0xcf;
2098
- targetView.setBigUint64(position, value);
2099
- } else {
2100
- // overflow
2101
- if (this.largeBigIntToFloat) {
2102
- target[position++] = 0xcb;
2103
- targetView.setFloat64(position, Number(value));
2104
- } else if (this.useBigIntExtension && value < 2n**(1023n) && value > -(2n**(1023n))) {
2105
- target[position++] = 0xc7;
2106
- position++;
2107
- target[position++] = 0x42; // "B" for BigInt
2108
- let bytes = [];
2109
- let alignedSign;
2110
- do {
2111
- let byte = value & 0xffn;
2112
- alignedSign = (byte & 0x80n) === (value < 0n ? 0x80n : 0n);
2113
- bytes.push(byte);
2114
- value >>= 8n;
2115
- } while (!((value === 0n || value === -1n) && alignedSign));
2116
- target[position-2] = bytes.length;
2117
- for (let i = bytes.length; i > 0;) {
2118
- target[position++] = Number(bytes[--i]);
2119
- }
2120
- return
2121
- } else {
2122
- throw new RangeError(value + ' was too large to fit in MessagePack 64-bit integer format, use' +
2123
- ' useBigIntExtension or set largeBigIntToFloat to convert to float-64')
2124
- }
2125
- }
2126
- position += 8;
2127
- } else if (type === 'undefined') {
2128
- if (this.encodeUndefinedAsNil)
2129
- target[position++] = 0xc0;
2130
- else {
2131
- target[position++] = 0xd4; // a number of implementations use fixext1 with type 0, data 0 to denote undefined, so we follow suite
2132
- target[position++] = 0;
2133
- target[position++] = 0;
2134
- }
2135
- } else {
2136
- throw new Error('Unknown type: ' + type)
2137
- }
2138
- };
2139
-
2140
- const writePlainObject = (this.variableMapSize || this.coercibleKeyAsNumber) ? (object) => {
2141
- // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects)
2142
- let keys = Object.keys(object);
2143
- let length = keys.length;
2144
- if (length < 0x10) {
2145
- target[position++] = 0x80 | length;
2146
- } else if (length < 0x10000) {
2147
- target[position++] = 0xde;
2148
- target[position++] = length >> 8;
2149
- target[position++] = length & 0xff;
2150
- } else {
2151
- target[position++] = 0xdf;
2152
- targetView.setUint32(position, length);
2153
- position += 4;
2154
- }
2155
- let key;
2156
- if (this.coercibleKeyAsNumber) {
2157
- for (let i = 0; i < length; i++) {
2158
- key = keys[i];
2159
- let num = Number(key);
2160
- pack(isNaN(num) ? key : num);
2161
- pack(object[key]);
2162
- }
2163
-
2164
- } else {
2165
- for (let i = 0; i < length; i++) {
2166
- pack(key = keys[i]);
2167
- pack(object[key]);
2168
- }
2169
- }
2170
- } :
2171
- (object) => {
2172
- target[position++] = 0xde; // always using map 16, so we can preallocate and set the length afterwards
2173
- let objectOffset = position - start;
2174
- position += 2;
2175
- let size = 0;
2176
- for (let key in object) {
2177
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
2178
- pack(key);
2179
- pack(object[key]);
2180
- size++;
2181
- }
2182
- }
2183
- target[objectOffset++ + start] = size >> 8;
2184
- target[objectOffset + start] = size & 0xff;
2185
- };
2186
-
2187
- const writeRecord = this.useRecords === false ? writePlainObject :
2188
- (options.progressiveRecords && !useTwoByteRecords) ? // this is about 2% faster for highly stable structures, since it only requires one for-in loop (but much more expensive when new structure needs to be written)
2189
- (object) => {
2190
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
2191
- let objectOffset = position++ - start;
2192
- let wroteKeys;
2193
- for (let key in object) {
2194
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
2195
- nextTransition = transition[key];
2196
- if (nextTransition)
2197
- transition = nextTransition;
2198
- else {
2199
- // record doesn't exist, create full new record and insert it
2200
- let keys = Object.keys(object);
2201
- let lastTransition = transition;
2202
- transition = structures.transitions;
2203
- let newTransitions = 0;
2204
- for (let i = 0, l = keys.length; i < l; i++) {
2205
- let key = keys[i];
2206
- nextTransition = transition[key];
2207
- if (!nextTransition) {
2208
- nextTransition = transition[key] = Object.create(null);
2209
- newTransitions++;
2210
- }
2211
- transition = nextTransition;
2212
- }
2213
- if (objectOffset + start + 1 == position) {
2214
- // first key, so we don't need to insert, we can just write record directly
2215
- position--;
2216
- newRecord(transition, keys, newTransitions);
2217
- } else // otherwise we need to insert the record, moving existing data after the record
2218
- insertNewRecord(transition, keys, objectOffset, newTransitions);
2219
- wroteKeys = true;
2220
- transition = lastTransition[key];
2221
- }
2222
- pack(object[key]);
2223
- }
2224
- }
2225
- if (!wroteKeys) {
2226
- let recordId = transition[RECORD_SYMBOL];
2227
- if (recordId)
2228
- target[objectOffset + start] = recordId;
2229
- else
2230
- insertNewRecord(transition, Object.keys(object), objectOffset, 0);
2231
- }
2232
- } :
2233
- (object) => {
2234
- let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null));
2235
- let newTransitions = 0;
2236
- for (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
2237
- nextTransition = transition[key];
2238
- if (!nextTransition) {
2239
- nextTransition = transition[key] = Object.create(null);
2240
- newTransitions++;
2241
- }
2242
- transition = nextTransition;
2243
- }
2244
- let recordId = transition[RECORD_SYMBOL];
2245
- if (recordId) {
2246
- if (recordId >= 0x60 && useTwoByteRecords) {
2247
- target[position++] = ((recordId -= 0x60) & 0x1f) + 0x60;
2248
- target[position++] = recordId >> 5;
2249
- } else
2250
- target[position++] = recordId;
2251
- } else {
2252
- newRecord(transition, transition.__keys__ || Object.keys(object), newTransitions);
2253
- }
2254
- // now write the values
2255
- for (let key in object)
2256
- if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {
2257
- pack(object[key]);
2258
- }
2259
- };
2260
-
2261
- // craete reference to useRecords if useRecords is a function
2262
- const checkUseRecords = typeof this.useRecords == 'function' && this.useRecords;
2263
-
2264
- const writeObject = checkUseRecords ? (object) => {
2265
- checkUseRecords(object) ? writeRecord(object) : writePlainObject(object);
2266
- } : writeRecord;
2267
-
2268
- const makeRoom = (end) => {
2269
- let newSize;
2270
- if (end > 0x1000000) {
2271
- // special handling for really large buffers
2272
- if ((end - start) > MAX_BUFFER_SIZE)
2273
- throw new Error('Packed buffer would be larger than maximum buffer size')
2274
- newSize = Math.min(MAX_BUFFER_SIZE,
2275
- Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000);
2276
- } else // faster handling for smaller buffers
2277
- newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12;
2278
- let newBuffer = new ByteArrayAllocate(newSize);
2279
- targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize));
2280
- end = Math.min(end, target.length);
2281
- if (target.copy)
2282
- target.copy(newBuffer, 0, start, end);
2283
- else
2284
- newBuffer.set(target.slice(start, end));
2285
- position -= start;
2286
- start = 0;
2287
- safeEnd = newBuffer.length - 10;
2288
- return target = newBuffer
2289
- };
2290
- const newRecord = (transition, keys, newTransitions) => {
2291
- let recordId = structures.nextId;
2292
- if (!recordId)
2293
- recordId = 0x40;
2294
- if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) {
2295
- recordId = structures.nextOwnId;
2296
- if (!(recordId < maxStructureId))
2297
- recordId = sharedLimitId;
2298
- structures.nextOwnId = recordId + 1;
2299
- } else {
2300
- if (recordId >= maxStructureId)// cycle back around
2301
- recordId = sharedLimitId;
2302
- structures.nextId = recordId + 1;
2303
- }
2304
- let highByte = keys.highByte = recordId >= 0x60 && useTwoByteRecords ? (recordId - 0x60) >> 5 : -1;
2305
- transition[RECORD_SYMBOL] = recordId;
2306
- transition.__keys__ = keys;
2307
- structures[recordId - 0x40] = keys;
2308
-
2309
- if (recordId < sharedLimitId) {
2310
- keys.isShared = true;
2311
- structures.sharedLength = recordId - 0x3f;
2312
- hasSharedUpdate = true;
2313
- if (highByte >= 0) {
2314
- target[position++] = (recordId & 0x1f) + 0x60;
2315
- target[position++] = highByte;
2316
- } else {
2317
- target[position++] = recordId;
2318
- }
2319
- } else {
2320
- if (highByte >= 0) {
2321
- target[position++] = 0xd5; // fixext 2
2322
- target[position++] = 0x72; // "r" record defintion extension type
2323
- target[position++] = (recordId & 0x1f) + 0x60;
2324
- target[position++] = highByte;
2325
- } else {
2326
- target[position++] = 0xd4; // fixext 1
2327
- target[position++] = 0x72; // "r" record defintion extension type
2328
- target[position++] = recordId;
2329
- }
2330
-
2331
- if (newTransitions)
2332
- transitionsCount += serializationsSinceTransitionRebuild * newTransitions;
2333
- // record the removal of the id, we can maintain our shared structure
2334
- if (recordIdsToRemove.length >= maxOwnStructures)
2335
- recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; // we are cycling back through, and have to remove old ones
2336
- recordIdsToRemove.push(transition);
2337
- pack(keys);
2338
- }
2339
- };
2340
- const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => {
2341
- let mainTarget = target;
2342
- let mainPosition = position;
2343
- let mainSafeEnd = safeEnd;
2344
- let mainStart = start;
2345
- target = keysTarget;
2346
- position = 0;
2347
- start = 0;
2348
- if (!target)
2349
- keysTarget = target = new ByteArrayAllocate(8192);
2350
- safeEnd = target.length - 10;
2351
- newRecord(transition, keys, newTransitions);
2352
- keysTarget = target;
2353
- let keysPosition = position;
2354
- target = mainTarget;
2355
- position = mainPosition;
2356
- safeEnd = mainSafeEnd;
2357
- start = mainStart;
2358
- if (keysPosition > 1) {
2359
- let newEnd = position + keysPosition - 1;
2360
- if (newEnd > safeEnd)
2361
- makeRoom(newEnd);
2362
- let insertionPosition = insertionOffset + start;
2363
- target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position);
2364
- target.set(keysTarget.slice(0, keysPosition), insertionPosition);
2365
- position = newEnd;
2366
- } else {
2367
- target[insertionOffset + start] = keysTarget[0];
2368
- }
2369
- };
2370
- const writeStruct = (object) => {
2371
- let newPosition = writeStructSlots(object, target, start, position, structures, makeRoom, (value, newPosition, notifySharedUpdate) => {
2372
- if (notifySharedUpdate)
2373
- return hasSharedUpdate = true;
2374
- position = newPosition;
2375
- let startTarget = target;
2376
- pack(value);
2377
- resetStructures();
2378
- if (startTarget !== target) {
2379
- return { position, targetView, target }; // indicate the buffer was re-allocated
2380
- }
2381
- return position;
2382
- }, this);
2383
- if (newPosition === 0) // bail and go to a msgpack object
2384
- return writeObject(object);
2385
- position = newPosition;
2386
- };
2387
- }
2388
- useBuffer(buffer) {
2389
- // this means we are finished using our own buffer and we can write over it safely
2390
- target = buffer;
2391
- targetView = new DataView(target.buffer, target.byteOffset, target.byteLength);
2392
- position = 0;
2393
- }
2394
- clearSharedData() {
2395
- if (this.structures)
2396
- this.structures = [];
2397
- if (this.typedStructs)
2398
- this.typedStructs = [];
2399
- }
2400
- }
2401
-
2402
- extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/, C1Type ];
2403
- extensions = [{
2404
- pack(date, allocateForWrite, pack) {
2405
- let seconds = date.getTime() / 1000;
2406
- if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {
2407
- // Timestamp 32
2408
- let { target, targetView, position} = allocateForWrite(6);
2409
- target[position++] = 0xd6;
2410
- target[position++] = 0xff;
2411
- targetView.setUint32(position, seconds);
2412
- } else if (seconds > 0 && seconds < 0x100000000) {
2413
- // Timestamp 64
2414
- let { target, targetView, position} = allocateForWrite(10);
2415
- target[position++] = 0xd7;
2416
- target[position++] = 0xff;
2417
- targetView.setUint32(position, date.getMilliseconds() * 4000000 + ((seconds / 1000 / 0x100000000) >> 0));
2418
- targetView.setUint32(position + 4, seconds);
2419
- } else if (isNaN(seconds)) {
2420
- if (this.onInvalidDate) {
2421
- allocateForWrite(0);
2422
- return pack(this.onInvalidDate())
2423
- }
2424
- // Intentionally invalid timestamp
2425
- let { target, targetView, position} = allocateForWrite(3);
2426
- target[position++] = 0xd4;
2427
- target[position++] = 0xff;
2428
- target[position++] = 0xff;
2429
- } else {
2430
- // Timestamp 96
2431
- let { target, targetView, position} = allocateForWrite(15);
2432
- target[position++] = 0xc7;
2433
- target[position++] = 12;
2434
- target[position++] = 0xff;
2435
- targetView.setUint32(position, date.getMilliseconds() * 1000000);
2436
- targetView.setBigInt64(position + 4, BigInt(Math.floor(seconds)));
2437
- }
2438
- }
2439
- }, {
2440
- pack(set, allocateForWrite, pack) {
2441
- if (this.setAsEmptyObject) {
2442
- allocateForWrite(0);
2443
- return pack({})
2444
- }
2445
- let array = Array.from(set);
2446
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
2447
- if (this.moreTypes) {
2448
- target[position++] = 0xd4;
2449
- target[position++] = 0x73; // 's' for Set
2450
- target[position++] = 0;
2451
- }
2452
- pack(array);
2453
- }
2454
- }, {
2455
- pack(error, allocateForWrite, pack) {
2456
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
2457
- if (this.moreTypes) {
2458
- target[position++] = 0xd4;
2459
- target[position++] = 0x65; // 'e' for error
2460
- target[position++] = 0;
2461
- }
2462
- pack([ error.name, error.message, error.cause ]);
2463
- }
2464
- }, {
2465
- pack(regex, allocateForWrite, pack) {
2466
- let { target, position} = allocateForWrite(this.moreTypes ? 3 : 0);
2467
- if (this.moreTypes) {
2468
- target[position++] = 0xd4;
2469
- target[position++] = 0x78; // 'x' for regeXp
2470
- target[position++] = 0;
2471
- }
2472
- pack([ regex.source, regex.flags ]);
2473
- }
2474
- }, {
2475
- pack(arrayBuffer, allocateForWrite) {
2476
- if (this.moreTypes)
2477
- writeExtBuffer(arrayBuffer, 0x10, allocateForWrite);
2478
- else
2479
- writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite);
2480
- }
2481
- }, {
2482
- pack(typedArray, allocateForWrite) {
2483
- let constructor = typedArray.constructor;
2484
- if (constructor !== ByteArray && this.moreTypes)
2485
- writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite);
2486
- else
2487
- writeBuffer(typedArray, allocateForWrite);
2488
- }
2489
- }, {
2490
- pack(c1, allocateForWrite) { // specific 0xC1 object
2491
- let { target, position} = allocateForWrite(1);
2492
- target[position] = 0xc1;
2493
- }
2494
- }];
2495
-
2496
- function writeExtBuffer(typedArray, type, allocateForWrite, encode) {
2497
- let length = typedArray.byteLength;
2498
- if (length + 1 < 0x100) {
2499
- var { target, position } = allocateForWrite(4 + length);
2500
- target[position++] = 0xc7;
2501
- target[position++] = length + 1;
2502
- } else if (length + 1 < 0x10000) {
2503
- var { target, position } = allocateForWrite(5 + length);
2504
- target[position++] = 0xc8;
2505
- target[position++] = (length + 1) >> 8;
2506
- target[position++] = (length + 1) & 0xff;
2507
- } else {
2508
- var { target, position, targetView } = allocateForWrite(7 + length);
2509
- target[position++] = 0xc9;
2510
- targetView.setUint32(position, length + 1); // plus one for the type byte
2511
- position += 4;
2512
- }
2513
- target[position++] = 0x74; // "t" for typed array
2514
- target[position++] = type;
2515
- if (!typedArray.buffer) typedArray = new Uint8Array(typedArray);
2516
- target.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position);
2517
- }
2518
- function writeBuffer(buffer, allocateForWrite) {
2519
- let length = buffer.byteLength;
2520
- var target, position;
2521
- if (length < 0x100) {
2522
- var { target, position } = allocateForWrite(length + 2);
2523
- target[position++] = 0xc4;
2524
- target[position++] = length;
2525
- } else if (length < 0x10000) {
2526
- var { target, position } = allocateForWrite(length + 3);
2527
- target[position++] = 0xc5;
2528
- target[position++] = length >> 8;
2529
- target[position++] = length & 0xff;
2530
- } else {
2531
- var { target, position, targetView } = allocateForWrite(length + 5);
2532
- target[position++] = 0xc6;
2533
- targetView.setUint32(position, length);
2534
- position += 4;
2535
- }
2536
- target.set(buffer, position);
2537
- }
2538
-
2539
- function writeExtensionData(result, target, position, type) {
2540
- let length = result.length;
2541
- switch (length) {
2542
- case 1:
2543
- target[position++] = 0xd4;
2544
- break
2545
- case 2:
2546
- target[position++] = 0xd5;
2547
- break
2548
- case 4:
2549
- target[position++] = 0xd6;
2550
- break
2551
- case 8:
2552
- target[position++] = 0xd7;
2553
- break
2554
- case 16:
2555
- target[position++] = 0xd8;
2556
- break
2557
- default:
2558
- if (length < 0x100) {
2559
- target[position++] = 0xc7;
2560
- target[position++] = length;
2561
- } else if (length < 0x10000) {
2562
- target[position++] = 0xc8;
2563
- target[position++] = length >> 8;
2564
- target[position++] = length & 0xff;
2565
- } else {
2566
- target[position++] = 0xc9;
2567
- target[position++] = length >> 24;
2568
- target[position++] = (length >> 16) & 0xff;
2569
- target[position++] = (length >> 8) & 0xff;
2570
- target[position++] = length & 0xff;
2571
- }
2572
- }
2573
- target[position++] = type;
2574
- target.set(result, position);
2575
- position += length;
2576
- return position
2577
- }
2578
-
2579
- function insertIds(serialized, idsToInsert) {
2580
- // insert the ids that need to be referenced for structured clones
2581
- let nextId;
2582
- let distanceToMove = idsToInsert.length * 6;
2583
- let lastEnd = serialized.length - distanceToMove;
2584
- while (nextId = idsToInsert.pop()) {
2585
- let offset = nextId.offset;
2586
- let id = nextId.id;
2587
- serialized.copyWithin(offset + distanceToMove, offset, lastEnd);
2588
- distanceToMove -= 6;
2589
- let position = offset + distanceToMove;
2590
- serialized[position++] = 0xd6;
2591
- serialized[position++] = 0x69; // 'i'
2592
- serialized[position++] = id >> 24;
2593
- serialized[position++] = (id >> 16) & 0xff;
2594
- serialized[position++] = (id >> 8) & 0xff;
2595
- serialized[position++] = id & 0xff;
2596
- lastEnd = offset;
2597
- }
2598
- return serialized
2599
- }
2600
-
2601
- function writeBundles(start, pack, incrementPosition) {
2602
- if (bundledStrings.length > 0) {
2603
- targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start);
2604
- bundledStrings.stringsPosition = position - start;
2605
- let writeStrings = bundledStrings;
2606
- bundledStrings = null;
2607
- pack(writeStrings[0]);
2608
- pack(writeStrings[1]);
2609
- }
2610
- }
2611
- function prepareStructures(structures, packr) {
2612
- structures.isCompatible = (existingStructures) => {
2613
- let compatible = !existingStructures || ((packr.lastNamedStructuresLength || 0) === existingStructures.length);
2614
- if (!compatible) // we want to merge these existing structures immediately since we already have it and we are in the right transaction
2615
- packr._mergeStructures(existingStructures);
2616
- return compatible;
2617
- };
2618
- return structures
2619
- }
2620
-
2621
- let defaultPackr = new Packr({ useRecords: false });
2622
- defaultPackr.pack;
2623
- defaultPackr.pack;
2624
- const REUSE_BUFFER_MODE = 512;
2625
- const RESET_BUFFER_MODE = 1024;
2626
- const RESERVE_START_SPACE = 2048;
2627
-
2628
- // src/shared.ts
2629
- var MESSAGE_SOURCE_KEY = "osra-message";
2630
-
2631
- // src/utils.ts
2632
- var isClonable = (value) => globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true : false;
2633
- var isTransferable = (value) => globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true : false;
2634
- var getTransferableObjects = (value) => {
2635
- const transferables = [];
2636
- const recurse = (value2) => isClonable(value2) ? void 0 : isTransferable(value2) ? transferables.push(value2) : Array.isArray(value2) ? value2.map(recurse) : value2 && typeof value2 === "object" ? Object.values(value2).map(recurse) : void 0;
2637
- recurse(value);
2638
- return transferables;
2639
- };
2640
- var PROXY_FUNCTION_PROPERTY = "__proxyFunctionPort__";
2641
- var makeProxyFunction = (func) => {
2642
- const { port1, port2 } = new MessageChannel();
2643
- port1.addEventListener("message", async (ev) => {
2644
- try {
2645
- const result = await func(...ev.data);
2646
- const proxiedResult = proxyObjectFunctions(result);
2647
- const transferables = getTransferableObjects(proxiedResult);
2648
- port1.postMessage({ result: proxiedResult }, { transfer: transferables });
2649
- } catch (err) {
2650
- port1.postMessage({ error: err });
2651
- }
2652
- });
2653
- port1.start();
2654
- return port2;
2655
- };
2656
- var proxyObjectFunctions = (value) => isClonable(value) ? value : isTransferable(value) ? value : typeof value === "function" ? { [PROXY_FUNCTION_PROPERTY]: makeProxyFunction(value) } : Array.isArray(value) ? value.map(proxyObjectFunctions) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([key, value2]) => [
2657
- key,
2658
- proxyObjectFunctions(value2)
2659
- ])) : value;
2660
- var makeProxiedFunction = (port) => (...args) => new Promise((resolve, reject) => {
2661
- const proxiedArguments = proxyObjectFunctions(args);
2662
- const transferables = getTransferableObjects(proxiedArguments);
2663
- port.addEventListener("message", (ev) => {
2664
- if (ev.data.error)
2665
- reject(ev.data.error);
2666
- else
2667
- resolve(makeObjectProxiedFunctions(ev.data.result));
2668
- });
2669
- port.start();
2670
- port.postMessage(proxiedArguments, { transfer: transferables });
2671
- });
2672
- var makeObjectProxiedFunctions = (value) => isClonable(value) ? value : isTransferable(value) ? value : value && typeof value === "object" && value[PROXY_FUNCTION_PROPERTY] ? makeProxiedFunction(value[PROXY_FUNCTION_PROPERTY]) : Array.isArray(value) ? value.map(proxyObjectFunctions) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([key, value2]) => [
2673
- key,
2674
- makeObjectProxiedFunctions(value2)
2675
- ])) : value;
2676
-
2677
- // src/call.ts
2678
- var call = (target, { key = MESSAGE_SOURCE_KEY } = { key: MESSAGE_SOURCE_KEY }) => (type, data) => new Promise((resolve, reject) => {
2679
- const { port1, port2 } = new MessageChannel();
2680
- port1.addEventListener("message", ({ data: data2 }) => {
2681
- if (data2.error) {
2682
- reject(data2.error);
2683
- } else {
2684
- const proxiedData2 = makeObjectProxiedFunctions(data2.result);
2685
- resolve(proxiedData2);
2686
- }
2687
- port1.close();
2688
- port2.close();
2689
- }, { once: true });
2690
- port1.start();
2691
- const proxiedData = proxyObjectFunctions(data);
2692
- const transferables = getTransferableObjects(proxiedData);
2693
- target.postMessage({
2694
- source: key,
2695
- type,
2696
- data: proxiedData,
2697
- port: port2
2698
- }, {
2699
- targetOrigin: "*",
2700
- transfer: [port2, ...transferables ?? []]
2701
- });
2702
- });
2703
-
2704
- let c, i;
2705
- const d = () => (i = new Promise((t, e) => {
2706
- c = t;
2707
- }), i), p = d(), m = async (t) => {
2708
- t === p && d(), c(await t);
2709
- }, h = "https://fkn.app", f = globalThis.window === void 0, o = globalThis?.document.querySelector(`iframe[src="${h}/sandbox-api"]`), n = globalThis.document?.createElement("iframe");
2710
- !o && n && (n.src = `${h}/sandbox-api`, n.style.display = "none", document.body.appendChild(n));
2711
- const w = o || n, l = w?.contentWindow, u = () => i;
2712
- if (f) {
2713
- let t = !1;
2714
- i.then(() => {
2715
- t = !0;
2716
- }), setTimeout(() => {
2717
- t || console.warn("@fkn/lib's api target has not resolved after 250ms while in a worker, make sure to call `setApiTarget(messagePort)`");
2718
- }, 250);
2719
- } else {
2720
- if (!w)
2721
- throw new Error("Missing appended iframe");
2722
- const t = setInterval(
2723
- () => call(l, { key: "fkn-sandbox" })("APP_READY", {}).then(() => {
2724
- m(l), clearInterval(t);
2725
- }).catch(() => {
2726
- console.warn("Failed to connect to sandbox, trying again in 10ms");
2727
- }),
2728
- 10
2729
- );
2730
- }
2731
- const _ = (t, e) => u().then(
2732
- (a) => call(a, { key: "fkn-sandbox-api" })(t, e)
2733
- );
2734
- class M {
2735
- _internals;
2736
- _awaitedInternals;
2737
- closed;
2738
- constructor() {
2739
- this.closed = new Promise((e) => {
2740
- this._internals = _(
2741
- "WEBVPN_WEBTRANSPORT",
2742
- {
2743
- close: ({ closeCode: a, reason: s }) => e({ closeCode: a, reason: s })
2744
- }
2745
- ), this._internals.then((a) => {
2746
- this._awaitedInternals = a;
2747
- });
2748
- });
2749
- }
2750
- close(e) {
2751
- this._internals.then(({ close: a }) => a(e ?? {}));
2752
- }
2753
- get ready() {
2754
- return this._internals.then(() => {
2755
- });
2756
- }
2757
- get incomingBidirectionalStreams() {
2758
- return this._awaitedInternals.incomingBidirectionalStreams;
2759
- }
2760
- get incomingUnidirectionalStreams() {
2761
- return this._awaitedInternals.incomingUnidirectionalStreams;
2762
- }
2763
- async createBidirectionalStream() {
2764
- const { readable: e, writable: a } = await this._awaitedInternals.createBidirectionalStream();
2765
- return { readable: e, writable: a };
2766
- }
2767
- createUnidirectionalStream() {
2768
- return this._awaitedInternals.createUnidirectionalStream();
2769
- }
2770
- get datagrams() {
2771
- const e = this;
2772
- return {
2773
- get incomingHighWaterMark() {
2774
- return e._awaitedInternals.datagrams.incomingHighWaterMark;
2775
- },
2776
- set incomingHighWaterMark(a) {
2777
- e._awaitedInternals.datagrams.setIncomingHighWaterMark(a);
2778
- },
2779
- get incomingMaxAge() {
2780
- return e._awaitedInternals.datagrams.incomingMaxAge;
2781
- },
2782
- set incomingMaxAge(a) {
2783
- e._awaitedInternals.datagrams.setIncomingMaxAge(a);
2784
- },
2785
- get maxDatagramSize() {
2786
- return e._awaitedInternals.datagrams.maxDatagramSize;
2787
- },
2788
- get outgoingHighWaterMark() {
2789
- return e._awaitedInternals.datagrams.outgoingHighWaterMark;
2790
- },
2791
- set outgoingHighWaterMark(a) {
2792
- e._awaitedInternals.datagrams.setOutgoingHighWaterMark(a);
2793
- },
2794
- get outgoingMaxAge() {
2795
- return e._awaitedInternals.datagrams.outgoingMaxAge;
2796
- },
2797
- set outgoingMaxAge(a) {
2798
- e._awaitedInternals.datagrams.setOutgoingMaxAge(a);
2799
- },
2800
- get readable() {
2801
- return e._awaitedInternals.datagrams.readable;
2802
- },
2803
- get writable() {
2804
- return e._awaitedInternals.datagrams.writable;
2805
- }
2806
- };
2807
- }
2808
- }
2809
-
2810
- const packr = new Packr();
2811
- const packPacket = (packet) => packr.pack(packet);
2812
- const unpackMultiplePackets = (data) => packr.unpackMultiple(data);
2813
- const makeWebVPNWebtransport = async () => {
2814
- const webtransport = new M();
2815
- await webtransport.ready;
2816
- return webtransport;
2817
- };
2818
-
2819
- const normalizeBindArgs = (args) => {
2820
- if (args.length === 1) {
2821
- return {
2822
- port: void 0,
2823
- address: void 0,
2824
- callback: args[0]
2825
- };
2826
- } else if (args.length === 2) {
2827
- if (typeof args[0] === "number") {
2828
- return {
2829
- port: args[0],
2830
- address: void 0,
2831
- callback: args[1]
2832
- };
2833
- }
2834
- if (args[0].fd !== void 0) {
2835
- throw new Error("FKN WebVPN does not support file descriptors");
2836
- }
2837
- return {
2838
- ...args[0],
2839
- callback: args[1]
2840
- };
2841
- }
2842
- return {
2843
- port: args[0],
2844
- address: args[1],
2845
- callback: args[2]
2846
- };
2847
- };
2848
- const normalizeConnectArgs = (args) => {
2849
- if (args.length === 2) {
2850
- return {
2851
- port: args[0],
2852
- address: void 0,
2853
- callback: args[1]
2854
- };
2855
- } else {
2856
- return {
2857
- port: args[0],
2858
- address: args[1],
2859
- callback: args[2]
2860
- };
2861
- }
2862
- };
2863
- const normalizeSendArgs = (args) => {
2864
- if (args.length === 6) {
2865
- return {
2866
- msg: args[0],
2867
- offset: args[1],
2868
- length: args[2],
2869
- port: args[3],
2870
- address: args[4],
2871
- callback: args[5]
2872
- };
2873
- } else if (args.length === 5) {
2874
- return {
2875
- msg: args[0],
2876
- offset: args[1],
2877
- length: args[2],
2878
- port: args[3],
2879
- address: void 0,
2880
- callback: args[4]
2881
- };
2882
- } else if (args.length === 4) {
2883
- if (typeof args[3] === "string") {
2884
- return {
2885
- msg: args[0],
2886
- offset: void 0,
2887
- length: void 0,
2888
- port: args[1],
2889
- address: args[2],
2890
- callback: args[3]
2891
- };
2892
- } else {
2893
- return {
2894
- msg: args[0],
2895
- offset: args[1],
2896
- length: void 0,
2897
- port: args[2],
2898
- address: void 0,
2899
- callback: args[3]
2900
- };
2901
- }
2902
- } else if (args.length === 3) {
2903
- return {
2904
- msg: args[0],
2905
- offset: void 0,
2906
- length: void 0,
2907
- port: args[1],
2908
- address: void 0,
2909
- callback: args[2]
2910
- };
2911
- } else if (args.length === 2) {
2912
- return {
2913
- msg: args[0],
2914
- offset: void 0,
2915
- length: void 0,
2916
- port: void 0,
2917
- address: void 0,
2918
- callback: args[1]
2919
- };
2920
- } else {
2921
- return {
2922
- msg: args[0],
2923
- offset: void 0,
2924
- length: void 0,
2925
- port: void 0,
2926
- address: void 0,
2927
- callback: void 0
2928
- };
2929
- }
2930
- };
2931
- class Socket extends eventsExports.EventEmitter {
2932
- constructor(options) {
2933
- super(options);
2934
- this._type = options.type;
2935
- this._address = void 0;
2936
- this._webVPN = makeWebVPNWebtransport().then(async (webtransport) => {
2937
- const connectionDatagramReader = webtransport.datagrams.readable.getReader();
2938
- const connectionDatagramWriter = webtransport.datagrams.writable.getWriter();
2939
- await connectionDatagramWriter.ready;
2940
- const webTransportBidirectionalStream = await webtransport.createBidirectionalStream();
2941
- const { readable, writable } = webTransportBidirectionalStream;
2942
- const reader = readable.getReader();
2943
- const writer = writable.getWriter();
2944
- await writer.ready;
2945
- await writer.write(packPacket({ type: "udp-socket", socketType: options.type }));
2946
- const read = async () => {
2947
- const { done, value } = await reader.read();
2948
- if (done)
2949
- return;
2950
- try {
2951
- const packets = unpackMultiplePackets(value);
2952
- for (const packet of packets) {
2953
- if (packet.type === "event-close") {
2954
- this.emit("close");
2955
- } else if (packet.type === "event-connect") {
2956
- this.emit("connect");
2957
- } else if (packet.type === "event-error") {
2958
- this.emit("error", new Error(packet.exception));
2959
- } else if (packet.type === "event-listening") {
2960
- this._address = packet.address;
2961
- this.emit("listening");
2962
- } else if (packet.type === "callback-bind") {
2963
- this._address = packet.address;
2964
- this.emit("callback-bind", { uuid: packet.uuid });
2965
- } else if (packet.type === "callback-close") {
2966
- this.emit("callback-close", { uuid: packet.uuid });
2967
- } else if (packet.type === "callback-connect") {
2968
- this._remoteAddress = packet.remoteAddress;
2969
- this.emit("callback-connect", { uuid: packet.uuid });
2970
- } else if (packet.type === "callback-send") {
2971
- this.emit("callback-send", { uuid: packet.uuid });
2972
- } else {
2973
- console.error("unknown packet type", packet);
2974
- }
2975
- }
2976
- } catch (err) {
2977
- console.error(err);
2978
- } finally {
2979
- await read();
2980
- }
2981
- };
2982
- read();
2983
- return {
2984
- webtransport,
2985
- reader,
2986
- writer,
2987
- datagramReader: connectionDatagramReader,
2988
- datagramWriter: connectionDatagramWriter
2989
- };
2990
- });
2991
- }
2992
- addMembership(multicastAddress, multicastInterface) {
2993
- this._webVPN.then((webVPN) => {
2994
- webVPN.writer.write(
2995
- packPacket({
2996
- type: "addMembership",
2997
- multicastAddress,
2998
- multicastInterface
2999
- })
3000
- );
3001
- });
3002
- }
3003
- address() {
3004
- if (!this._address)
3005
- throw new Error("EBADF");
3006
- return this._address;
3007
- }
3008
- bind(args) {
3009
- const normalizedOptions = normalizeBindArgs(args);
3010
- this._webVPN.then((webVPN) => {
3011
- const uuid = normalizedOptions.callback ? self.crypto.randomUUID() : void 0;
3012
- if (uuid && normalizedOptions.callback) {
3013
- this.on("callback-bind", function callbackBind({ uuid: _uuid }) {
3014
- if (_uuid !== uuid)
3015
- return;
3016
- this.off("callback-bind", callbackBind);
3017
- normalizedOptions.callback();
3018
- });
3019
- }
3020
- webVPN.writer.write(
3021
- packPacket({
3022
- type: "bind",
3023
- uuid,
3024
- port: normalizedOptions.port,
3025
- address: normalizedOptions.address,
3026
- exclusive: normalizedOptions.exclusive
3027
- })
3028
- );
3029
- });
3030
- return this;
3031
- }
3032
- close(callback) {
3033
- this._webVPN.then((webVPN) => {
3034
- const uuid = callback ? self.crypto.randomUUID() : void 0;
3035
- if (uuid && callback) {
3036
- this.on("callback-close", function callbackClose({ uuid: _uuid }) {
3037
- if (_uuid !== uuid)
3038
- return;
3039
- this.off("callback-close", callbackClose);
3040
- callback();
3041
- });
3042
- }
3043
- webVPN.writer.write(
3044
- packPacket({
3045
- type: "close",
3046
- uuid
3047
- })
3048
- );
3049
- });
3050
- return this;
3051
- }
3052
- connect(...args) {
3053
- const normalizedOptions = normalizeConnectArgs(args);
3054
- const address = normalizedOptions.address;
3055
- const port = normalizedOptions.port;
3056
- if (!address)
3057
- throw new Error("port is required");
3058
- if (!port)
3059
- throw new Error("address is required");
3060
- this._webVPN.then((webVPN) => {
3061
- const uuid = normalizedOptions.callback ? self.crypto.randomUUID() : void 0;
3062
- if (uuid && normalizedOptions.callback) {
3063
- this.on("callback-connect", function callbackConnect({ uuid: _uuid }) {
3064
- if (_uuid !== uuid)
3065
- return;
3066
- this.off("callback-connect", callbackConnect);
3067
- normalizedOptions.callback();
3068
- });
3069
- }
3070
- webVPN.writer.write(
3071
- packPacket({
3072
- type: "connect",
3073
- uuid,
3074
- address,
3075
- port
3076
- })
3077
- );
3078
- });
3079
- }
3080
- disconnect() {
3081
- if (!this._address)
3082
- throw new Error("ERR_SOCKET_DGRAM_NOT_CONNECTED");
3083
- this._address = void 0;
3084
- this._webVPN.then((webVPN) => {
3085
- webVPN.writer.write(packPacket({ type: "disconnect" }));
3086
- });
3087
- }
3088
- dropMembership(multicastAddress, multicastInterface) {
3089
- this._webVPN.then((webVPN) => {
3090
- webVPN.writer.write(
3091
- packPacket({
3092
- type: "dropMembership",
3093
- multicastAddress,
3094
- multicastInterface
3095
- })
3096
- );
3097
- });
3098
- }
3099
- getRecvBufferSize() {
3100
- return 0;
3101
- }
3102
- getSendBufferSize() {
3103
- return 0;
3104
- }
3105
- getSendQueueSize() {
3106
- return 0;
3107
- }
3108
- getSendQueueCount() {
3109
- return 0;
3110
- }
3111
- ref() {
3112
- return this;
3113
- }
3114
- remoteAddress() {
3115
- if (!this._remoteAddress)
3116
- throw new Error("ERR_SOCKET_DGRAM_NOT_CONNECTED");
3117
- return {
3118
- address: this._remoteAddress.address,
3119
- family: this._remoteAddress.family,
3120
- port: this._remoteAddress.port
3121
- };
3122
- }
3123
- send(...args) {
3124
- const { address, callback, length, msg, offset, port } = normalizeSendArgs(args);
3125
- this._webVPN.then((webVPN) => {
3126
- webVPN.datagramWriter.write(
3127
- packPacket({
3128
- type: "send",
3129
- msg,
3130
- offset,
3131
- length,
3132
- port,
3133
- address
3134
- })
3135
- );
3136
- if (typeof callback === "function") {
3137
- callback(null, 0);
3138
- }
3139
- });
3140
- }
3141
- setBroadcast(flag) {
3142
- this._webVPN.then((webVPN) => {
3143
- webVPN.writer.write(
3144
- packPacket({
3145
- type: "setBroadcast",
3146
- flag
3147
- })
3148
- );
3149
- });
3150
- }
3151
- setMulticastInterface(multicastInterface) {
3152
- this._webVPN.then((webVPN) => {
3153
- webVPN.writer.write(
3154
- packPacket({
3155
- type: "setMulticastInterface",
3156
- multicastInterface
3157
- })
3158
- );
3159
- });
3160
- }
3161
- setMulticastLoopback(flag) {
3162
- this._webVPN.then((webVPN) => {
3163
- webVPN.writer.write(
3164
- packPacket({
3165
- type: "setMulticastLoopback",
3166
- flag
3167
- })
3168
- );
3169
- });
3170
- return true;
3171
- }
3172
- setMulticastTTL(ttl) {
3173
- this._webVPN.then((webVPN) => {
3174
- webVPN.writer.write(
3175
- packPacket({
3176
- type: "setMulticastTTL",
3177
- ttl
3178
- })
3179
- );
3180
- });
3181
- return ttl;
3182
- }
3183
- setRecvBufferSize(size) {
3184
- this._webVPN.then((webVPN) => {
3185
- webVPN.writer.write(
3186
- packPacket({
3187
- type: "setRecvBufferSize",
3188
- size
3189
- })
3190
- );
3191
- });
3192
- }
3193
- setSendBufferSize(size) {
3194
- this._webVPN.then((webVPN) => {
3195
- webVPN.writer.write(
3196
- packPacket({
3197
- type: "setSendBufferSize",
3198
- size
3199
- })
3200
- );
3201
- });
3202
- }
3203
- setTTL(ttl) {
3204
- this._webVPN.then((webVPN) => {
3205
- webVPN.writer.write(
3206
- packPacket({
3207
- type: "setTTL",
3208
- ttl
3209
- })
3210
- );
3211
- });
3212
- return ttl;
3213
- }
3214
- unref() {
3215
- return this;
3216
- }
3217
- addSourceSpecificMembership(sourceAddress, groupAddress, multicastInterface) {
3218
- this._webVPN.then((webVPN) => {
3219
- webVPN.writer.write(
3220
- packPacket({
3221
- type: "addSourceSpecificMembership",
3222
- sourceAddress,
3223
- groupAddress,
3224
- multicastInterface
3225
- })
3226
- );
3227
- });
3228
- }
3229
- dropSourceSpecificMembership(sourceAddress, groupAddress, multicastInterface) {
3230
- this._webVPN.then((webVPN) => {
3231
- webVPN.writer.write(
3232
- packPacket({
3233
- type: "dropSourceSpecificMembership",
3234
- sourceAddress,
3235
- groupAddress,
3236
- multicastInterface
3237
- })
3238
- );
3239
- });
3240
- }
3241
- }
3242
- const createSocket = (options, callback) => {
3243
- const socket = new Socket(
3244
- typeof options === "string" ? { type: options } : options
3245
- );
3246
- if (callback)
3247
- socket.on("message", callback);
3248
- return socket;
3249
- };
3250
-
3251
- export { Socket, createSocket };
3252
- //# sourceMappingURL=index.mjs.map