@powersync/common 1.44.0 → 1.46.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 (49) hide show
  1. package/dist/bundle.cjs +442 -2057
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +439 -2058
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +341 -127
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +338 -128
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +263 -164
  10. package/lib/client/AbstractPowerSyncDatabase.d.ts +9 -2
  11. package/lib/client/AbstractPowerSyncDatabase.js +18 -5
  12. package/lib/client/AbstractPowerSyncDatabase.js.map +1 -1
  13. package/lib/client/ConnectionManager.d.ts +1 -1
  14. package/lib/client/ConnectionManager.js.map +1 -1
  15. package/lib/client/sync/stream/AbstractRemote.js +41 -32
  16. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  17. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +7 -12
  18. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +10 -12
  19. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  20. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  21. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  22. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  23. package/lib/client/triggers/TriggerManager.d.ts +37 -0
  24. package/lib/client/triggers/TriggerManagerImpl.d.ts +24 -3
  25. package/lib/client/triggers/TriggerManagerImpl.js +133 -11
  26. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -1
  27. package/lib/db/ConnectionClosedError.d.ts +10 -0
  28. package/lib/db/ConnectionClosedError.js +21 -0
  29. package/lib/db/ConnectionClosedError.js.map +1 -0
  30. package/lib/db/crud/SyncStatus.d.ts +11 -2
  31. package/lib/db/crud/SyncStatus.js +19 -1
  32. package/lib/db/crud/SyncStatus.js.map +1 -1
  33. package/lib/index.d.ts +4 -0
  34. package/lib/index.js +4 -0
  35. package/lib/index.js.map +1 -1
  36. package/lib/utils/DataStream.js +11 -2
  37. package/lib/utils/DataStream.js.map +1 -1
  38. package/package.json +4 -3
  39. package/src/client/AbstractPowerSyncDatabase.ts +21 -6
  40. package/src/client/ConnectionManager.ts +1 -1
  41. package/src/client/sync/stream/AbstractRemote.ts +47 -35
  42. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +11 -15
  43. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  44. package/src/client/triggers/TriggerManager.ts +50 -6
  45. package/src/client/triggers/TriggerManagerImpl.ts +177 -13
  46. package/src/db/ConnectionClosedError.ts +23 -0
  47. package/src/db/crud/SyncStatus.ts +22 -3
  48. package/src/index.ts +4 -0
  49. package/src/utils/DataStream.ts +13 -2
package/dist/bundle.cjs CHANGED
@@ -722,12 +722,30 @@ class SyncStatus {
722
722
  return {
723
723
  connected: this.connected,
724
724
  connecting: this.connecting,
725
- dataFlow: this.dataFlowStatus,
725
+ dataFlow: {
726
+ ...this.dataFlowStatus,
727
+ uploadError: this.serializeError(this.dataFlowStatus.uploadError),
728
+ downloadError: this.serializeError(this.dataFlowStatus.downloadError)
729
+ },
726
730
  lastSyncedAt: this.lastSyncedAt,
727
731
  hasSynced: this.hasSynced,
728
732
  priorityStatusEntries: this.priorityStatusEntries
729
733
  };
730
734
  }
735
+ /**
736
+ * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
737
+ * This explicitly serializes errors in the SyncStatus.
738
+ */
739
+ serializeError(error) {
740
+ if (typeof error == 'undefined') {
741
+ return undefined;
742
+ }
743
+ return {
744
+ name: error.name,
745
+ message: error.message,
746
+ stack: error.stack
747
+ };
748
+ }
731
749
  static comparePriorities(a, b) {
732
750
  return b.priority - a.priority; // Reverse because higher priorities have lower numbers
733
751
  }
@@ -2071,7 +2089,7 @@ class SyncDataBucket {
2071
2089
  }
2072
2090
  }
2073
2091
 
2074
- var buffer$1 = {};
2092
+ var buffer = {};
2075
2093
 
2076
2094
  var base64Js = {};
2077
2095
 
@@ -2335,12 +2353,12 @@ function requireIeee754 () {
2335
2353
  * @license MIT
2336
2354
  */
2337
2355
 
2338
- var hasRequiredBuffer$1;
2356
+ var hasRequiredBuffer;
2339
2357
 
2340
- function requireBuffer$1 () {
2341
- if (hasRequiredBuffer$1) return buffer$1;
2342
- hasRequiredBuffer$1 = 1;
2343
- (function (exports) {
2358
+ function requireBuffer () {
2359
+ if (hasRequiredBuffer) return buffer;
2360
+ hasRequiredBuffer = 1;
2361
+ (function (exports$1) {
2344
2362
 
2345
2363
  const base64 = requireBase64Js();
2346
2364
  const ieee754 = requireIeee754();
@@ -2349,12 +2367,12 @@ function requireBuffer$1 () {
2349
2367
  ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
2350
2368
  : null;
2351
2369
 
2352
- exports.Buffer = Buffer;
2353
- exports.SlowBuffer = SlowBuffer;
2354
- exports.INSPECT_MAX_BYTES = 50;
2370
+ exports$1.Buffer = Buffer;
2371
+ exports$1.SlowBuffer = SlowBuffer;
2372
+ exports$1.INSPECT_MAX_BYTES = 50;
2355
2373
 
2356
2374
  const K_MAX_LENGTH = 0x7fffffff;
2357
- exports.kMaxLength = K_MAX_LENGTH;
2375
+ exports$1.kMaxLength = K_MAX_LENGTH;
2358
2376
 
2359
2377
  /**
2360
2378
  * If `Buffer.TYPED_ARRAY_SUPPORT`:
@@ -2950,7 +2968,7 @@ function requireBuffer$1 () {
2950
2968
 
2951
2969
  Buffer.prototype.inspect = function inspect () {
2952
2970
  let str = '';
2953
- const max = exports.INSPECT_MAX_BYTES;
2971
+ const max = exports$1.INSPECT_MAX_BYTES;
2954
2972
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
2955
2973
  if (this.length > max) str += ' ... ';
2956
2974
  return '<Buffer ' + str + '>'
@@ -4189,1926 +4207,85 @@ function requireBuffer$1 () {
4189
4207
  function (name, actual) {
4190
4208
  return `The "${name}" argument must be of type number. Received type ${typeof actual}`
4191
4209
  }, TypeError);
4192
- E('ERR_OUT_OF_RANGE',
4193
- function (str, range, input) {
4194
- let msg = `The value of "${str}" is out of range.`;
4195
- let received = input;
4196
- if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
4197
- received = addNumericalSeparator(String(input));
4198
- } else if (typeof input === 'bigint') {
4199
- received = String(input);
4200
- if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
4201
- received = addNumericalSeparator(received);
4202
- }
4203
- received += 'n';
4204
- }
4205
- msg += ` It must be ${range}. Received ${received}`;
4206
- return msg
4207
- }, RangeError);
4208
-
4209
- function addNumericalSeparator (val) {
4210
- let res = '';
4211
- let i = val.length;
4212
- const start = val[0] === '-' ? 1 : 0;
4213
- for (; i >= start + 4; i -= 3) {
4214
- res = `_${val.slice(i - 3, i)}${res}`;
4215
- }
4216
- return `${val.slice(0, i)}${res}`
4217
- }
4218
-
4219
- // CHECK FUNCTIONS
4220
- // ===============
4221
-
4222
- function checkBounds (buf, offset, byteLength) {
4223
- validateNumber(offset, 'offset');
4224
- if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
4225
- boundsError(offset, buf.length - (byteLength + 1));
4226
- }
4227
- }
4228
-
4229
- function checkIntBI (value, min, max, buf, offset, byteLength) {
4230
- if (value > max || value < min) {
4231
- const n = typeof min === 'bigint' ? 'n' : '';
4232
- let range;
4233
- {
4234
- if (min === 0 || min === BigInt(0)) {
4235
- range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;
4236
- } else {
4237
- range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
4238
- `${(byteLength + 1) * 8 - 1}${n}`;
4239
- }
4240
- }
4241
- throw new errors.ERR_OUT_OF_RANGE('value', range, value)
4242
- }
4243
- checkBounds(buf, offset, byteLength);
4244
- }
4245
-
4246
- function validateNumber (value, name) {
4247
- if (typeof value !== 'number') {
4248
- throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
4249
- }
4250
- }
4251
-
4252
- function boundsError (value, length, type) {
4253
- if (Math.floor(value) !== value) {
4254
- validateNumber(value, type);
4255
- throw new errors.ERR_OUT_OF_RANGE('offset', 'an integer', value)
4256
- }
4257
-
4258
- if (length < 0) {
4259
- throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
4260
- }
4261
-
4262
- throw new errors.ERR_OUT_OF_RANGE('offset',
4263
- `>= ${0} and <= ${length}`,
4264
- value)
4265
- }
4266
-
4267
- // HELPER FUNCTIONS
4268
- // ================
4269
-
4270
- const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
4271
-
4272
- function base64clean (str) {
4273
- // Node takes equal signs as end of the Base64 encoding
4274
- str = str.split('=')[0];
4275
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
4276
- str = str.trim().replace(INVALID_BASE64_RE, '');
4277
- // Node converts strings with length < 2 to ''
4278
- if (str.length < 2) return ''
4279
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
4280
- while (str.length % 4 !== 0) {
4281
- str = str + '=';
4282
- }
4283
- return str
4284
- }
4285
-
4286
- function utf8ToBytes (string, units) {
4287
- units = units || Infinity;
4288
- let codePoint;
4289
- const length = string.length;
4290
- let leadSurrogate = null;
4291
- const bytes = [];
4292
-
4293
- for (let i = 0; i < length; ++i) {
4294
- codePoint = string.charCodeAt(i);
4295
-
4296
- // is surrogate component
4297
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
4298
- // last char was a lead
4299
- if (!leadSurrogate) {
4300
- // no lead yet
4301
- if (codePoint > 0xDBFF) {
4302
- // unexpected trail
4303
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4304
- continue
4305
- } else if (i + 1 === length) {
4306
- // unpaired lead
4307
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4308
- continue
4309
- }
4310
-
4311
- // valid lead
4312
- leadSurrogate = codePoint;
4313
-
4314
- continue
4315
- }
4316
-
4317
- // 2 leads in a row
4318
- if (codePoint < 0xDC00) {
4319
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4320
- leadSurrogate = codePoint;
4321
- continue
4322
- }
4323
-
4324
- // valid surrogate pair
4325
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
4326
- } else if (leadSurrogate) {
4327
- // valid bmp char, but last char was a lead
4328
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4329
- }
4330
-
4331
- leadSurrogate = null;
4332
-
4333
- // encode utf8
4334
- if (codePoint < 0x80) {
4335
- if ((units -= 1) < 0) break
4336
- bytes.push(codePoint);
4337
- } else if (codePoint < 0x800) {
4338
- if ((units -= 2) < 0) break
4339
- bytes.push(
4340
- codePoint >> 0x6 | 0xC0,
4341
- codePoint & 0x3F | 0x80
4342
- );
4343
- } else if (codePoint < 0x10000) {
4344
- if ((units -= 3) < 0) break
4345
- bytes.push(
4346
- codePoint >> 0xC | 0xE0,
4347
- codePoint >> 0x6 & 0x3F | 0x80,
4348
- codePoint & 0x3F | 0x80
4349
- );
4350
- } else if (codePoint < 0x110000) {
4351
- if ((units -= 4) < 0) break
4352
- bytes.push(
4353
- codePoint >> 0x12 | 0xF0,
4354
- codePoint >> 0xC & 0x3F | 0x80,
4355
- codePoint >> 0x6 & 0x3F | 0x80,
4356
- codePoint & 0x3F | 0x80
4357
- );
4358
- } else {
4359
- throw new Error('Invalid code point')
4360
- }
4361
- }
4362
-
4363
- return bytes
4364
- }
4365
-
4366
- function asciiToBytes (str) {
4367
- const byteArray = [];
4368
- for (let i = 0; i < str.length; ++i) {
4369
- // Node's code seems to be doing this and not & 0x7F..
4370
- byteArray.push(str.charCodeAt(i) & 0xFF);
4371
- }
4372
- return byteArray
4373
- }
4374
-
4375
- function utf16leToBytes (str, units) {
4376
- let c, hi, lo;
4377
- const byteArray = [];
4378
- for (let i = 0; i < str.length; ++i) {
4379
- if ((units -= 2) < 0) break
4380
-
4381
- c = str.charCodeAt(i);
4382
- hi = c >> 8;
4383
- lo = c % 256;
4384
- byteArray.push(lo);
4385
- byteArray.push(hi);
4386
- }
4387
-
4388
- return byteArray
4389
- }
4390
-
4391
- function base64ToBytes (str) {
4392
- return base64.toByteArray(base64clean(str))
4393
- }
4394
-
4395
- function blitBuffer (src, dst, offset, length) {
4396
- let i;
4397
- for (i = 0; i < length; ++i) {
4398
- if ((i + offset >= dst.length) || (i >= src.length)) break
4399
- dst[i + offset] = src[i];
4400
- }
4401
- return i
4402
- }
4403
-
4404
- // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
4405
- // the `instanceof` check but they should be treated as of that type.
4406
- // See: https://github.com/feross/buffer/issues/166
4407
- function isInstance (obj, type) {
4408
- return obj instanceof type ||
4409
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
4410
- obj.constructor.name === type.name)
4411
- }
4412
- function numberIsNaN (obj) {
4413
- // For IE11 support
4414
- return obj !== obj // eslint-disable-line no-self-compare
4415
- }
4416
-
4417
- // Create lookup table for `toString('hex')`
4418
- // See: https://github.com/feross/buffer/issues/219
4419
- const hexSliceLookupTable = (function () {
4420
- const alphabet = '0123456789abcdef';
4421
- const table = new Array(256);
4422
- for (let i = 0; i < 16; ++i) {
4423
- const i16 = i * 16;
4424
- for (let j = 0; j < 16; ++j) {
4425
- table[i16 + j] = alphabet[i] + alphabet[j];
4426
- }
4427
- }
4428
- return table
4429
- })();
4430
-
4431
- // Return not function with Error if BigInt not supported
4432
- function defineBigIntMethod (fn) {
4433
- return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
4434
- }
4435
-
4436
- function BufferBigIntNotDefined () {
4437
- throw new Error('BigInt not supported')
4438
- }
4439
- } (buffer$1));
4440
- return buffer$1;
4441
- }
4442
-
4443
- var bufferExports$1 = requireBuffer$1();
4444
-
4445
- var dist = {};
4446
-
4447
- var buffer = {};
4448
-
4449
- /*!
4450
- * The buffer module from node.js, for the browser.
4451
- *
4452
- * @author Feross Aboukhadijeh <https://feross.org>
4453
- * @license MIT
4454
- */
4455
-
4456
- var hasRequiredBuffer;
4457
-
4458
- function requireBuffer () {
4459
- if (hasRequiredBuffer) return buffer;
4460
- hasRequiredBuffer = 1;
4461
- (function (exports) {
4462
-
4463
- var base64 = requireBase64Js();
4464
- var ieee754 = requireIeee754();
4465
- var customInspectSymbol =
4466
- (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
4467
- ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
4468
- : null;
4469
-
4470
- exports.Buffer = Buffer;
4471
- exports.SlowBuffer = SlowBuffer;
4472
- exports.INSPECT_MAX_BYTES = 50;
4473
-
4474
- var K_MAX_LENGTH = 0x7fffffff;
4475
- exports.kMaxLength = K_MAX_LENGTH;
4476
-
4477
- /**
4478
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
4479
- * === true Use Uint8Array implementation (fastest)
4480
- * === false Print warning and recommend using `buffer` v4.x which has an Object
4481
- * implementation (most compatible, even IE6)
4482
- *
4483
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
4484
- * Opera 11.6+, iOS 4.2+.
4485
- *
4486
- * We report that the browser does not support typed arrays if the are not subclassable
4487
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
4488
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
4489
- * for __proto__ and has a buggy typed array implementation.
4490
- */
4491
- Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
4492
-
4493
- if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
4494
- typeof console.error === 'function') {
4495
- console.error(
4496
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
4497
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
4498
- );
4499
- }
4500
-
4501
- function typedArraySupport () {
4502
- // Can typed array instances can be augmented?
4503
- try {
4504
- var arr = new Uint8Array(1);
4505
- var proto = { foo: function () { return 42 } };
4506
- Object.setPrototypeOf(proto, Uint8Array.prototype);
4507
- Object.setPrototypeOf(arr, proto);
4508
- return arr.foo() === 42
4509
- } catch (e) {
4510
- return false
4511
- }
4512
- }
4513
-
4514
- Object.defineProperty(Buffer.prototype, 'parent', {
4515
- enumerable: true,
4516
- get: function () {
4517
- if (!Buffer.isBuffer(this)) return undefined
4518
- return this.buffer
4519
- }
4520
- });
4521
-
4522
- Object.defineProperty(Buffer.prototype, 'offset', {
4523
- enumerable: true,
4524
- get: function () {
4525
- if (!Buffer.isBuffer(this)) return undefined
4526
- return this.byteOffset
4527
- }
4528
- });
4529
-
4530
- function createBuffer (length) {
4531
- if (length > K_MAX_LENGTH) {
4532
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
4533
- }
4534
- // Return an augmented `Uint8Array` instance
4535
- var buf = new Uint8Array(length);
4536
- Object.setPrototypeOf(buf, Buffer.prototype);
4537
- return buf
4538
- }
4539
-
4540
- /**
4541
- * The Buffer constructor returns instances of `Uint8Array` that have their
4542
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
4543
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
4544
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
4545
- * returns a single octet.
4546
- *
4547
- * The `Uint8Array` prototype remains unmodified.
4548
- */
4549
-
4550
- function Buffer (arg, encodingOrOffset, length) {
4551
- // Common case.
4552
- if (typeof arg === 'number') {
4553
- if (typeof encodingOrOffset === 'string') {
4554
- throw new TypeError(
4555
- 'The "string" argument must be of type string. Received type number'
4556
- )
4557
- }
4558
- return allocUnsafe(arg)
4559
- }
4560
- return from(arg, encodingOrOffset, length)
4561
- }
4562
-
4563
- Buffer.poolSize = 8192; // not used by this implementation
4564
-
4565
- function from (value, encodingOrOffset, length) {
4566
- if (typeof value === 'string') {
4567
- return fromString(value, encodingOrOffset)
4568
- }
4569
-
4570
- if (ArrayBuffer.isView(value)) {
4571
- return fromArrayView(value)
4572
- }
4573
-
4574
- if (value == null) {
4575
- throw new TypeError(
4576
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
4577
- 'or Array-like Object. Received type ' + (typeof value)
4578
- )
4579
- }
4580
-
4581
- if (isInstance(value, ArrayBuffer) ||
4582
- (value && isInstance(value.buffer, ArrayBuffer))) {
4583
- return fromArrayBuffer(value, encodingOrOffset, length)
4584
- }
4585
-
4586
- if (typeof SharedArrayBuffer !== 'undefined' &&
4587
- (isInstance(value, SharedArrayBuffer) ||
4588
- (value && isInstance(value.buffer, SharedArrayBuffer)))) {
4589
- return fromArrayBuffer(value, encodingOrOffset, length)
4590
- }
4591
-
4592
- if (typeof value === 'number') {
4593
- throw new TypeError(
4594
- 'The "value" argument must not be of type number. Received type number'
4595
- )
4596
- }
4597
-
4598
- var valueOf = value.valueOf && value.valueOf();
4599
- if (valueOf != null && valueOf !== value) {
4600
- return Buffer.from(valueOf, encodingOrOffset, length)
4601
- }
4602
-
4603
- var b = fromObject(value);
4604
- if (b) return b
4605
-
4606
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
4607
- typeof value[Symbol.toPrimitive] === 'function') {
4608
- return Buffer.from(
4609
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
4610
- )
4611
- }
4612
-
4613
- throw new TypeError(
4614
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
4615
- 'or Array-like Object. Received type ' + (typeof value)
4616
- )
4617
- }
4618
-
4619
- /**
4620
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
4621
- * if value is a number.
4622
- * Buffer.from(str[, encoding])
4623
- * Buffer.from(array)
4624
- * Buffer.from(buffer)
4625
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
4626
- **/
4627
- Buffer.from = function (value, encodingOrOffset, length) {
4628
- return from(value, encodingOrOffset, length)
4629
- };
4630
-
4631
- // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
4632
- // https://github.com/feross/buffer/pull/148
4633
- Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
4634
- Object.setPrototypeOf(Buffer, Uint8Array);
4635
-
4636
- function assertSize (size) {
4637
- if (typeof size !== 'number') {
4638
- throw new TypeError('"size" argument must be of type number')
4639
- } else if (size < 0) {
4640
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
4641
- }
4642
- }
4643
-
4644
- function alloc (size, fill, encoding) {
4645
- assertSize(size);
4646
- if (size <= 0) {
4647
- return createBuffer(size)
4648
- }
4649
- if (fill !== undefined) {
4650
- // Only pay attention to encoding if it's a string. This
4651
- // prevents accidentally sending in a number that would
4652
- // be interpreted as a start offset.
4653
- return typeof encoding === 'string'
4654
- ? createBuffer(size).fill(fill, encoding)
4655
- : createBuffer(size).fill(fill)
4656
- }
4657
- return createBuffer(size)
4658
- }
4659
-
4660
- /**
4661
- * Creates a new filled Buffer instance.
4662
- * alloc(size[, fill[, encoding]])
4663
- **/
4664
- Buffer.alloc = function (size, fill, encoding) {
4665
- return alloc(size, fill, encoding)
4666
- };
4667
-
4668
- function allocUnsafe (size) {
4669
- assertSize(size);
4670
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
4671
- }
4672
-
4673
- /**
4674
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
4675
- * */
4676
- Buffer.allocUnsafe = function (size) {
4677
- return allocUnsafe(size)
4678
- };
4679
- /**
4680
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
4681
- */
4682
- Buffer.allocUnsafeSlow = function (size) {
4683
- return allocUnsafe(size)
4684
- };
4685
-
4686
- function fromString (string, encoding) {
4687
- if (typeof encoding !== 'string' || encoding === '') {
4688
- encoding = 'utf8';
4689
- }
4690
-
4691
- if (!Buffer.isEncoding(encoding)) {
4692
- throw new TypeError('Unknown encoding: ' + encoding)
4693
- }
4694
-
4695
- var length = byteLength(string, encoding) | 0;
4696
- var buf = createBuffer(length);
4697
-
4698
- var actual = buf.write(string, encoding);
4699
-
4700
- if (actual !== length) {
4701
- // Writing a hex string, for example, that contains invalid characters will
4702
- // cause everything after the first invalid character to be ignored. (e.g.
4703
- // 'abxxcd' will be treated as 'ab')
4704
- buf = buf.slice(0, actual);
4705
- }
4706
-
4707
- return buf
4708
- }
4709
-
4710
- function fromArrayLike (array) {
4711
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
4712
- var buf = createBuffer(length);
4713
- for (var i = 0; i < length; i += 1) {
4714
- buf[i] = array[i] & 255;
4715
- }
4716
- return buf
4717
- }
4718
-
4719
- function fromArrayView (arrayView) {
4720
- if (isInstance(arrayView, Uint8Array)) {
4721
- var copy = new Uint8Array(arrayView);
4722
- return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
4723
- }
4724
- return fromArrayLike(arrayView)
4725
- }
4726
-
4727
- function fromArrayBuffer (array, byteOffset, length) {
4728
- if (byteOffset < 0 || array.byteLength < byteOffset) {
4729
- throw new RangeError('"offset" is outside of buffer bounds')
4730
- }
4731
-
4732
- if (array.byteLength < byteOffset + (length || 0)) {
4733
- throw new RangeError('"length" is outside of buffer bounds')
4734
- }
4735
-
4736
- var buf;
4737
- if (byteOffset === undefined && length === undefined) {
4738
- buf = new Uint8Array(array);
4739
- } else if (length === undefined) {
4740
- buf = new Uint8Array(array, byteOffset);
4741
- } else {
4742
- buf = new Uint8Array(array, byteOffset, length);
4743
- }
4744
-
4745
- // Return an augmented `Uint8Array` instance
4746
- Object.setPrototypeOf(buf, Buffer.prototype);
4747
-
4748
- return buf
4749
- }
4750
-
4751
- function fromObject (obj) {
4752
- if (Buffer.isBuffer(obj)) {
4753
- var len = checked(obj.length) | 0;
4754
- var buf = createBuffer(len);
4755
-
4756
- if (buf.length === 0) {
4757
- return buf
4758
- }
4759
-
4760
- obj.copy(buf, 0, 0, len);
4761
- return buf
4762
- }
4763
-
4764
- if (obj.length !== undefined) {
4765
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
4766
- return createBuffer(0)
4767
- }
4768
- return fromArrayLike(obj)
4769
- }
4770
-
4771
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
4772
- return fromArrayLike(obj.data)
4773
- }
4774
- }
4775
-
4776
- function checked (length) {
4777
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
4778
- // length is NaN (which is otherwise coerced to zero.)
4779
- if (length >= K_MAX_LENGTH) {
4780
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
4781
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
4782
- }
4783
- return length | 0
4784
- }
4785
-
4786
- function SlowBuffer (length) {
4787
- if (+length != length) { // eslint-disable-line eqeqeq
4788
- length = 0;
4789
- }
4790
- return Buffer.alloc(+length)
4791
- }
4792
-
4793
- Buffer.isBuffer = function isBuffer (b) {
4794
- return b != null && b._isBuffer === true &&
4795
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
4796
- };
4797
-
4798
- Buffer.compare = function compare (a, b) {
4799
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
4800
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
4801
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
4802
- throw new TypeError(
4803
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
4804
- )
4805
- }
4806
-
4807
- if (a === b) return 0
4808
-
4809
- var x = a.length;
4810
- var y = b.length;
4811
-
4812
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
4813
- if (a[i] !== b[i]) {
4814
- x = a[i];
4815
- y = b[i];
4816
- break
4817
- }
4818
- }
4819
-
4820
- if (x < y) return -1
4821
- if (y < x) return 1
4822
- return 0
4823
- };
4824
-
4825
- Buffer.isEncoding = function isEncoding (encoding) {
4826
- switch (String(encoding).toLowerCase()) {
4827
- case 'hex':
4828
- case 'utf8':
4829
- case 'utf-8':
4830
- case 'ascii':
4831
- case 'latin1':
4832
- case 'binary':
4833
- case 'base64':
4834
- case 'ucs2':
4835
- case 'ucs-2':
4836
- case 'utf16le':
4837
- case 'utf-16le':
4838
- return true
4839
- default:
4840
- return false
4841
- }
4842
- };
4843
-
4844
- Buffer.concat = function concat (list, length) {
4845
- if (!Array.isArray(list)) {
4846
- throw new TypeError('"list" argument must be an Array of Buffers')
4847
- }
4848
-
4849
- if (list.length === 0) {
4850
- return Buffer.alloc(0)
4851
- }
4852
-
4853
- var i;
4854
- if (length === undefined) {
4855
- length = 0;
4856
- for (i = 0; i < list.length; ++i) {
4857
- length += list[i].length;
4858
- }
4859
- }
4860
-
4861
- var buffer = Buffer.allocUnsafe(length);
4862
- var pos = 0;
4863
- for (i = 0; i < list.length; ++i) {
4864
- var buf = list[i];
4865
- if (isInstance(buf, Uint8Array)) {
4866
- if (pos + buf.length > buffer.length) {
4867
- Buffer.from(buf).copy(buffer, pos);
4868
- } else {
4869
- Uint8Array.prototype.set.call(
4870
- buffer,
4871
- buf,
4872
- pos
4873
- );
4874
- }
4875
- } else if (!Buffer.isBuffer(buf)) {
4876
- throw new TypeError('"list" argument must be an Array of Buffers')
4877
- } else {
4878
- buf.copy(buffer, pos);
4879
- }
4880
- pos += buf.length;
4881
- }
4882
- return buffer
4883
- };
4884
-
4885
- function byteLength (string, encoding) {
4886
- if (Buffer.isBuffer(string)) {
4887
- return string.length
4888
- }
4889
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
4890
- return string.byteLength
4891
- }
4892
- if (typeof string !== 'string') {
4893
- throw new TypeError(
4894
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
4895
- 'Received type ' + typeof string
4896
- )
4897
- }
4898
-
4899
- var len = string.length;
4900
- var mustMatch = (arguments.length > 2 && arguments[2] === true);
4901
- if (!mustMatch && len === 0) return 0
4902
-
4903
- // Use a for loop to avoid recursion
4904
- var loweredCase = false;
4905
- for (;;) {
4906
- switch (encoding) {
4907
- case 'ascii':
4908
- case 'latin1':
4909
- case 'binary':
4910
- return len
4911
- case 'utf8':
4912
- case 'utf-8':
4913
- return utf8ToBytes(string).length
4914
- case 'ucs2':
4915
- case 'ucs-2':
4916
- case 'utf16le':
4917
- case 'utf-16le':
4918
- return len * 2
4919
- case 'hex':
4920
- return len >>> 1
4921
- case 'base64':
4922
- return base64ToBytes(string).length
4923
- default:
4924
- if (loweredCase) {
4925
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
4926
- }
4927
- encoding = ('' + encoding).toLowerCase();
4928
- loweredCase = true;
4929
- }
4930
- }
4931
- }
4932
- Buffer.byteLength = byteLength;
4933
-
4934
- function slowToString (encoding, start, end) {
4935
- var loweredCase = false;
4936
-
4937
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
4938
- // property of a typed array.
4939
-
4940
- // This behaves neither like String nor Uint8Array in that we set start/end
4941
- // to their upper/lower bounds if the value passed is out of range.
4942
- // undefined is handled specially as per ECMA-262 6th Edition,
4943
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
4944
- if (start === undefined || start < 0) {
4945
- start = 0;
4946
- }
4947
- // Return early if start > this.length. Done here to prevent potential uint32
4948
- // coercion fail below.
4949
- if (start > this.length) {
4950
- return ''
4951
- }
4952
-
4953
- if (end === undefined || end > this.length) {
4954
- end = this.length;
4955
- }
4956
-
4957
- if (end <= 0) {
4958
- return ''
4959
- }
4960
-
4961
- // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
4962
- end >>>= 0;
4963
- start >>>= 0;
4964
-
4965
- if (end <= start) {
4966
- return ''
4967
- }
4968
-
4969
- if (!encoding) encoding = 'utf8';
4970
-
4971
- while (true) {
4972
- switch (encoding) {
4973
- case 'hex':
4974
- return hexSlice(this, start, end)
4975
-
4976
- case 'utf8':
4977
- case 'utf-8':
4978
- return utf8Slice(this, start, end)
4979
-
4980
- case 'ascii':
4981
- return asciiSlice(this, start, end)
4982
-
4983
- case 'latin1':
4984
- case 'binary':
4985
- return latin1Slice(this, start, end)
4986
-
4987
- case 'base64':
4988
- return base64Slice(this, start, end)
4989
-
4990
- case 'ucs2':
4991
- case 'ucs-2':
4992
- case 'utf16le':
4993
- case 'utf-16le':
4994
- return utf16leSlice(this, start, end)
4995
-
4996
- default:
4997
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
4998
- encoding = (encoding + '').toLowerCase();
4999
- loweredCase = true;
5000
- }
5001
- }
5002
- }
5003
-
5004
- // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
5005
- // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
5006
- // reliably in a browserify context because there could be multiple different
5007
- // copies of the 'buffer' package in use. This method works even for Buffer
5008
- // instances that were created from another copy of the `buffer` package.
5009
- // See: https://github.com/feross/buffer/issues/154
5010
- Buffer.prototype._isBuffer = true;
5011
-
5012
- function swap (b, n, m) {
5013
- var i = b[n];
5014
- b[n] = b[m];
5015
- b[m] = i;
5016
- }
5017
-
5018
- Buffer.prototype.swap16 = function swap16 () {
5019
- var len = this.length;
5020
- if (len % 2 !== 0) {
5021
- throw new RangeError('Buffer size must be a multiple of 16-bits')
5022
- }
5023
- for (var i = 0; i < len; i += 2) {
5024
- swap(this, i, i + 1);
5025
- }
5026
- return this
5027
- };
5028
-
5029
- Buffer.prototype.swap32 = function swap32 () {
5030
- var len = this.length;
5031
- if (len % 4 !== 0) {
5032
- throw new RangeError('Buffer size must be a multiple of 32-bits')
5033
- }
5034
- for (var i = 0; i < len; i += 4) {
5035
- swap(this, i, i + 3);
5036
- swap(this, i + 1, i + 2);
5037
- }
5038
- return this
5039
- };
5040
-
5041
- Buffer.prototype.swap64 = function swap64 () {
5042
- var len = this.length;
5043
- if (len % 8 !== 0) {
5044
- throw new RangeError('Buffer size must be a multiple of 64-bits')
5045
- }
5046
- for (var i = 0; i < len; i += 8) {
5047
- swap(this, i, i + 7);
5048
- swap(this, i + 1, i + 6);
5049
- swap(this, i + 2, i + 5);
5050
- swap(this, i + 3, i + 4);
5051
- }
5052
- return this
5053
- };
5054
-
5055
- Buffer.prototype.toString = function toString () {
5056
- var length = this.length;
5057
- if (length === 0) return ''
5058
- if (arguments.length === 0) return utf8Slice(this, 0, length)
5059
- return slowToString.apply(this, arguments)
5060
- };
5061
-
5062
- Buffer.prototype.toLocaleString = Buffer.prototype.toString;
5063
-
5064
- Buffer.prototype.equals = function equals (b) {
5065
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
5066
- if (this === b) return true
5067
- return Buffer.compare(this, b) === 0
5068
- };
5069
-
5070
- Buffer.prototype.inspect = function inspect () {
5071
- var str = '';
5072
- var max = exports.INSPECT_MAX_BYTES;
5073
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
5074
- if (this.length > max) str += ' ... ';
5075
- return '<Buffer ' + str + '>'
5076
- };
5077
- if (customInspectSymbol) {
5078
- Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
5079
- }
5080
-
5081
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
5082
- if (isInstance(target, Uint8Array)) {
5083
- target = Buffer.from(target, target.offset, target.byteLength);
5084
- }
5085
- if (!Buffer.isBuffer(target)) {
5086
- throw new TypeError(
5087
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
5088
- 'Received type ' + (typeof target)
5089
- )
5090
- }
5091
-
5092
- if (start === undefined) {
5093
- start = 0;
5094
- }
5095
- if (end === undefined) {
5096
- end = target ? target.length : 0;
5097
- }
5098
- if (thisStart === undefined) {
5099
- thisStart = 0;
5100
- }
5101
- if (thisEnd === undefined) {
5102
- thisEnd = this.length;
5103
- }
5104
-
5105
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
5106
- throw new RangeError('out of range index')
5107
- }
5108
-
5109
- if (thisStart >= thisEnd && start >= end) {
5110
- return 0
5111
- }
5112
- if (thisStart >= thisEnd) {
5113
- return -1
5114
- }
5115
- if (start >= end) {
5116
- return 1
5117
- }
5118
-
5119
- start >>>= 0;
5120
- end >>>= 0;
5121
- thisStart >>>= 0;
5122
- thisEnd >>>= 0;
5123
-
5124
- if (this === target) return 0
5125
-
5126
- var x = thisEnd - thisStart;
5127
- var y = end - start;
5128
- var len = Math.min(x, y);
5129
-
5130
- var thisCopy = this.slice(thisStart, thisEnd);
5131
- var targetCopy = target.slice(start, end);
5132
-
5133
- for (var i = 0; i < len; ++i) {
5134
- if (thisCopy[i] !== targetCopy[i]) {
5135
- x = thisCopy[i];
5136
- y = targetCopy[i];
5137
- break
5138
- }
5139
- }
5140
-
5141
- if (x < y) return -1
5142
- if (y < x) return 1
5143
- return 0
5144
- };
5145
-
5146
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
5147
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
5148
- //
5149
- // Arguments:
5150
- // - buffer - a Buffer to search
5151
- // - val - a string, Buffer, or number
5152
- // - byteOffset - an index into `buffer`; will be clamped to an int32
5153
- // - encoding - an optional encoding, relevant is val is a string
5154
- // - dir - true for indexOf, false for lastIndexOf
5155
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
5156
- // Empty buffer means no match
5157
- if (buffer.length === 0) return -1
5158
-
5159
- // Normalize byteOffset
5160
- if (typeof byteOffset === 'string') {
5161
- encoding = byteOffset;
5162
- byteOffset = 0;
5163
- } else if (byteOffset > 0x7fffffff) {
5164
- byteOffset = 0x7fffffff;
5165
- } else if (byteOffset < -2147483648) {
5166
- byteOffset = -2147483648;
5167
- }
5168
- byteOffset = +byteOffset; // Coerce to Number.
5169
- if (numberIsNaN(byteOffset)) {
5170
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
5171
- byteOffset = dir ? 0 : (buffer.length - 1);
5172
- }
5173
-
5174
- // Normalize byteOffset: negative offsets start from the end of the buffer
5175
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
5176
- if (byteOffset >= buffer.length) {
5177
- if (dir) return -1
5178
- else byteOffset = buffer.length - 1;
5179
- } else if (byteOffset < 0) {
5180
- if (dir) byteOffset = 0;
5181
- else return -1
5182
- }
5183
-
5184
- // Normalize val
5185
- if (typeof val === 'string') {
5186
- val = Buffer.from(val, encoding);
5187
- }
5188
-
5189
- // Finally, search either indexOf (if dir is true) or lastIndexOf
5190
- if (Buffer.isBuffer(val)) {
5191
- // Special case: looking for empty string/buffer always fails
5192
- if (val.length === 0) {
5193
- return -1
5194
- }
5195
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
5196
- } else if (typeof val === 'number') {
5197
- val = val & 0xFF; // Search for a byte value [0-255]
5198
- if (typeof Uint8Array.prototype.indexOf === 'function') {
5199
- if (dir) {
5200
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
5201
- } else {
5202
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
5203
- }
5204
- }
5205
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
5206
- }
5207
-
5208
- throw new TypeError('val must be string, number or Buffer')
5209
- }
5210
-
5211
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
5212
- var indexSize = 1;
5213
- var arrLength = arr.length;
5214
- var valLength = val.length;
5215
-
5216
- if (encoding !== undefined) {
5217
- encoding = String(encoding).toLowerCase();
5218
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
5219
- encoding === 'utf16le' || encoding === 'utf-16le') {
5220
- if (arr.length < 2 || val.length < 2) {
5221
- return -1
5222
- }
5223
- indexSize = 2;
5224
- arrLength /= 2;
5225
- valLength /= 2;
5226
- byteOffset /= 2;
5227
- }
5228
- }
5229
-
5230
- function read (buf, i) {
5231
- if (indexSize === 1) {
5232
- return buf[i]
5233
- } else {
5234
- return buf.readUInt16BE(i * indexSize)
5235
- }
5236
- }
5237
-
5238
- var i;
5239
- if (dir) {
5240
- var foundIndex = -1;
5241
- for (i = byteOffset; i < arrLength; i++) {
5242
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
5243
- if (foundIndex === -1) foundIndex = i;
5244
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
5245
- } else {
5246
- if (foundIndex !== -1) i -= i - foundIndex;
5247
- foundIndex = -1;
5248
- }
5249
- }
5250
- } else {
5251
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
5252
- for (i = byteOffset; i >= 0; i--) {
5253
- var found = true;
5254
- for (var j = 0; j < valLength; j++) {
5255
- if (read(arr, i + j) !== read(val, j)) {
5256
- found = false;
5257
- break
5258
- }
5259
- }
5260
- if (found) return i
5261
- }
5262
- }
5263
-
5264
- return -1
5265
- }
5266
-
5267
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
5268
- return this.indexOf(val, byteOffset, encoding) !== -1
5269
- };
5270
-
5271
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
5272
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
5273
- };
5274
-
5275
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
5276
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
5277
- };
5278
-
5279
- function hexWrite (buf, string, offset, length) {
5280
- offset = Number(offset) || 0;
5281
- var remaining = buf.length - offset;
5282
- if (!length) {
5283
- length = remaining;
5284
- } else {
5285
- length = Number(length);
5286
- if (length > remaining) {
5287
- length = remaining;
5288
- }
5289
- }
5290
-
5291
- var strLen = string.length;
5292
-
5293
- if (length > strLen / 2) {
5294
- length = strLen / 2;
5295
- }
5296
- for (var i = 0; i < length; ++i) {
5297
- var parsed = parseInt(string.substr(i * 2, 2), 16);
5298
- if (numberIsNaN(parsed)) return i
5299
- buf[offset + i] = parsed;
5300
- }
5301
- return i
5302
- }
5303
-
5304
- function utf8Write (buf, string, offset, length) {
5305
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
5306
- }
5307
-
5308
- function asciiWrite (buf, string, offset, length) {
5309
- return blitBuffer(asciiToBytes(string), buf, offset, length)
5310
- }
5311
-
5312
- function base64Write (buf, string, offset, length) {
5313
- return blitBuffer(base64ToBytes(string), buf, offset, length)
5314
- }
5315
-
5316
- function ucs2Write (buf, string, offset, length) {
5317
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
5318
- }
5319
-
5320
- Buffer.prototype.write = function write (string, offset, length, encoding) {
5321
- // Buffer#write(string)
5322
- if (offset === undefined) {
5323
- encoding = 'utf8';
5324
- length = this.length;
5325
- offset = 0;
5326
- // Buffer#write(string, encoding)
5327
- } else if (length === undefined && typeof offset === 'string') {
5328
- encoding = offset;
5329
- length = this.length;
5330
- offset = 0;
5331
- // Buffer#write(string, offset[, length][, encoding])
5332
- } else if (isFinite(offset)) {
5333
- offset = offset >>> 0;
5334
- if (isFinite(length)) {
5335
- length = length >>> 0;
5336
- if (encoding === undefined) encoding = 'utf8';
5337
- } else {
5338
- encoding = length;
5339
- length = undefined;
5340
- }
5341
- } else {
5342
- throw new Error(
5343
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
5344
- )
5345
- }
5346
-
5347
- var remaining = this.length - offset;
5348
- if (length === undefined || length > remaining) length = remaining;
5349
-
5350
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
5351
- throw new RangeError('Attempt to write outside buffer bounds')
5352
- }
5353
-
5354
- if (!encoding) encoding = 'utf8';
5355
-
5356
- var loweredCase = false;
5357
- for (;;) {
5358
- switch (encoding) {
5359
- case 'hex':
5360
- return hexWrite(this, string, offset, length)
5361
-
5362
- case 'utf8':
5363
- case 'utf-8':
5364
- return utf8Write(this, string, offset, length)
5365
-
5366
- case 'ascii':
5367
- case 'latin1':
5368
- case 'binary':
5369
- return asciiWrite(this, string, offset, length)
5370
-
5371
- case 'base64':
5372
- // Warning: maxLength not taken into account in base64Write
5373
- return base64Write(this, string, offset, length)
5374
-
5375
- case 'ucs2':
5376
- case 'ucs-2':
5377
- case 'utf16le':
5378
- case 'utf-16le':
5379
- return ucs2Write(this, string, offset, length)
5380
-
5381
- default:
5382
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5383
- encoding = ('' + encoding).toLowerCase();
5384
- loweredCase = true;
5385
- }
5386
- }
5387
- };
5388
-
5389
- Buffer.prototype.toJSON = function toJSON () {
5390
- return {
5391
- type: 'Buffer',
5392
- data: Array.prototype.slice.call(this._arr || this, 0)
5393
- }
5394
- };
5395
-
5396
- function base64Slice (buf, start, end) {
5397
- if (start === 0 && end === buf.length) {
5398
- return base64.fromByteArray(buf)
5399
- } else {
5400
- return base64.fromByteArray(buf.slice(start, end))
5401
- }
5402
- }
5403
-
5404
- function utf8Slice (buf, start, end) {
5405
- end = Math.min(buf.length, end);
5406
- var res = [];
5407
-
5408
- var i = start;
5409
- while (i < end) {
5410
- var firstByte = buf[i];
5411
- var codePoint = null;
5412
- var bytesPerSequence = (firstByte > 0xEF)
5413
- ? 4
5414
- : (firstByte > 0xDF)
5415
- ? 3
5416
- : (firstByte > 0xBF)
5417
- ? 2
5418
- : 1;
5419
-
5420
- if (i + bytesPerSequence <= end) {
5421
- var secondByte, thirdByte, fourthByte, tempCodePoint;
5422
-
5423
- switch (bytesPerSequence) {
5424
- case 1:
5425
- if (firstByte < 0x80) {
5426
- codePoint = firstByte;
5427
- }
5428
- break
5429
- case 2:
5430
- secondByte = buf[i + 1];
5431
- if ((secondByte & 0xC0) === 0x80) {
5432
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
5433
- if (tempCodePoint > 0x7F) {
5434
- codePoint = tempCodePoint;
5435
- }
5436
- }
5437
- break
5438
- case 3:
5439
- secondByte = buf[i + 1];
5440
- thirdByte = buf[i + 2];
5441
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
5442
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
5443
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
5444
- codePoint = tempCodePoint;
5445
- }
5446
- }
5447
- break
5448
- case 4:
5449
- secondByte = buf[i + 1];
5450
- thirdByte = buf[i + 2];
5451
- fourthByte = buf[i + 3];
5452
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
5453
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
5454
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
5455
- codePoint = tempCodePoint;
5456
- }
5457
- }
5458
- }
5459
- }
5460
-
5461
- if (codePoint === null) {
5462
- // we did not generate a valid codePoint so insert a
5463
- // replacement char (U+FFFD) and advance only 1 byte
5464
- codePoint = 0xFFFD;
5465
- bytesPerSequence = 1;
5466
- } else if (codePoint > 0xFFFF) {
5467
- // encode to utf16 (surrogate pair dance)
5468
- codePoint -= 0x10000;
5469
- res.push(codePoint >>> 10 & 0x3FF | 0xD800);
5470
- codePoint = 0xDC00 | codePoint & 0x3FF;
5471
- }
5472
-
5473
- res.push(codePoint);
5474
- i += bytesPerSequence;
5475
- }
5476
-
5477
- return decodeCodePointsArray(res)
5478
- }
5479
-
5480
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
5481
- // the lowest limit is Chrome, with 0x10000 args.
5482
- // We go 1 magnitude less, for safety
5483
- var MAX_ARGUMENTS_LENGTH = 0x1000;
5484
-
5485
- function decodeCodePointsArray (codePoints) {
5486
- var len = codePoints.length;
5487
- if (len <= MAX_ARGUMENTS_LENGTH) {
5488
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
5489
- }
5490
-
5491
- // Decode in chunks to avoid "call stack size exceeded".
5492
- var res = '';
5493
- var i = 0;
5494
- while (i < len) {
5495
- res += String.fromCharCode.apply(
5496
- String,
5497
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
5498
- );
5499
- }
5500
- return res
5501
- }
5502
-
5503
- function asciiSlice (buf, start, end) {
5504
- var ret = '';
5505
- end = Math.min(buf.length, end);
5506
-
5507
- for (var i = start; i < end; ++i) {
5508
- ret += String.fromCharCode(buf[i] & 0x7F);
5509
- }
5510
- return ret
5511
- }
5512
-
5513
- function latin1Slice (buf, start, end) {
5514
- var ret = '';
5515
- end = Math.min(buf.length, end);
5516
-
5517
- for (var i = start; i < end; ++i) {
5518
- ret += String.fromCharCode(buf[i]);
5519
- }
5520
- return ret
5521
- }
5522
-
5523
- function hexSlice (buf, start, end) {
5524
- var len = buf.length;
5525
-
5526
- if (!start || start < 0) start = 0;
5527
- if (!end || end < 0 || end > len) end = len;
5528
-
5529
- var out = '';
5530
- for (var i = start; i < end; ++i) {
5531
- out += hexSliceLookupTable[buf[i]];
5532
- }
5533
- return out
5534
- }
5535
-
5536
- function utf16leSlice (buf, start, end) {
5537
- var bytes = buf.slice(start, end);
5538
- var res = '';
5539
- // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
5540
- for (var i = 0; i < bytes.length - 1; i += 2) {
5541
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
5542
- }
5543
- return res
5544
- }
5545
-
5546
- Buffer.prototype.slice = function slice (start, end) {
5547
- var len = this.length;
5548
- start = ~~start;
5549
- end = end === undefined ? len : ~~end;
5550
-
5551
- if (start < 0) {
5552
- start += len;
5553
- if (start < 0) start = 0;
5554
- } else if (start > len) {
5555
- start = len;
5556
- }
5557
-
5558
- if (end < 0) {
5559
- end += len;
5560
- if (end < 0) end = 0;
5561
- } else if (end > len) {
5562
- end = len;
5563
- }
5564
-
5565
- if (end < start) end = start;
5566
-
5567
- var newBuf = this.subarray(start, end);
5568
- // Return an augmented `Uint8Array` instance
5569
- Object.setPrototypeOf(newBuf, Buffer.prototype);
5570
-
5571
- return newBuf
5572
- };
5573
-
5574
- /*
5575
- * Need to make sure that buffer isn't trying to write out of bounds.
5576
- */
5577
- function checkOffset (offset, ext, length) {
5578
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
5579
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
5580
- }
5581
-
5582
- Buffer.prototype.readUintLE =
5583
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
5584
- offset = offset >>> 0;
5585
- byteLength = byteLength >>> 0;
5586
- if (!noAssert) checkOffset(offset, byteLength, this.length);
5587
-
5588
- var val = this[offset];
5589
- var mul = 1;
5590
- var i = 0;
5591
- while (++i < byteLength && (mul *= 0x100)) {
5592
- val += this[offset + i] * mul;
5593
- }
5594
-
5595
- return val
5596
- };
5597
-
5598
- Buffer.prototype.readUintBE =
5599
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
5600
- offset = offset >>> 0;
5601
- byteLength = byteLength >>> 0;
5602
- if (!noAssert) {
5603
- checkOffset(offset, byteLength, this.length);
5604
- }
5605
-
5606
- var val = this[offset + --byteLength];
5607
- var mul = 1;
5608
- while (byteLength > 0 && (mul *= 0x100)) {
5609
- val += this[offset + --byteLength] * mul;
5610
- }
5611
-
5612
- return val
5613
- };
5614
-
5615
- Buffer.prototype.readUint8 =
5616
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
5617
- offset = offset >>> 0;
5618
- if (!noAssert) checkOffset(offset, 1, this.length);
5619
- return this[offset]
5620
- };
5621
-
5622
- Buffer.prototype.readUint16LE =
5623
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
5624
- offset = offset >>> 0;
5625
- if (!noAssert) checkOffset(offset, 2, this.length);
5626
- return this[offset] | (this[offset + 1] << 8)
5627
- };
5628
-
5629
- Buffer.prototype.readUint16BE =
5630
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
5631
- offset = offset >>> 0;
5632
- if (!noAssert) checkOffset(offset, 2, this.length);
5633
- return (this[offset] << 8) | this[offset + 1]
5634
- };
5635
-
5636
- Buffer.prototype.readUint32LE =
5637
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
5638
- offset = offset >>> 0;
5639
- if (!noAssert) checkOffset(offset, 4, this.length);
5640
-
5641
- return ((this[offset]) |
5642
- (this[offset + 1] << 8) |
5643
- (this[offset + 2] << 16)) +
5644
- (this[offset + 3] * 0x1000000)
5645
- };
5646
-
5647
- Buffer.prototype.readUint32BE =
5648
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
5649
- offset = offset >>> 0;
5650
- if (!noAssert) checkOffset(offset, 4, this.length);
5651
-
5652
- return (this[offset] * 0x1000000) +
5653
- ((this[offset + 1] << 16) |
5654
- (this[offset + 2] << 8) |
5655
- this[offset + 3])
5656
- };
5657
-
5658
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
5659
- offset = offset >>> 0;
5660
- byteLength = byteLength >>> 0;
5661
- if (!noAssert) checkOffset(offset, byteLength, this.length);
5662
-
5663
- var val = this[offset];
5664
- var mul = 1;
5665
- var i = 0;
5666
- while (++i < byteLength && (mul *= 0x100)) {
5667
- val += this[offset + i] * mul;
5668
- }
5669
- mul *= 0x80;
5670
-
5671
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
5672
-
5673
- return val
5674
- };
5675
-
5676
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
5677
- offset = offset >>> 0;
5678
- byteLength = byteLength >>> 0;
5679
- if (!noAssert) checkOffset(offset, byteLength, this.length);
5680
-
5681
- var i = byteLength;
5682
- var mul = 1;
5683
- var val = this[offset + --i];
5684
- while (i > 0 && (mul *= 0x100)) {
5685
- val += this[offset + --i] * mul;
5686
- }
5687
- mul *= 0x80;
5688
-
5689
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
5690
-
5691
- return val
5692
- };
5693
-
5694
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
5695
- offset = offset >>> 0;
5696
- if (!noAssert) checkOffset(offset, 1, this.length);
5697
- if (!(this[offset] & 0x80)) return (this[offset])
5698
- return ((0xff - this[offset] + 1) * -1)
5699
- };
5700
-
5701
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
5702
- offset = offset >>> 0;
5703
- if (!noAssert) checkOffset(offset, 2, this.length);
5704
- var val = this[offset] | (this[offset + 1] << 8);
5705
- return (val & 0x8000) ? val | 0xFFFF0000 : val
5706
- };
5707
-
5708
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
5709
- offset = offset >>> 0;
5710
- if (!noAssert) checkOffset(offset, 2, this.length);
5711
- var val = this[offset + 1] | (this[offset] << 8);
5712
- return (val & 0x8000) ? val | 0xFFFF0000 : val
5713
- };
5714
-
5715
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
5716
- offset = offset >>> 0;
5717
- if (!noAssert) checkOffset(offset, 4, this.length);
5718
-
5719
- return (this[offset]) |
5720
- (this[offset + 1] << 8) |
5721
- (this[offset + 2] << 16) |
5722
- (this[offset + 3] << 24)
5723
- };
5724
-
5725
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
5726
- offset = offset >>> 0;
5727
- if (!noAssert) checkOffset(offset, 4, this.length);
5728
-
5729
- return (this[offset] << 24) |
5730
- (this[offset + 1] << 16) |
5731
- (this[offset + 2] << 8) |
5732
- (this[offset + 3])
5733
- };
5734
-
5735
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
5736
- offset = offset >>> 0;
5737
- if (!noAssert) checkOffset(offset, 4, this.length);
5738
- return ieee754.read(this, offset, true, 23, 4)
5739
- };
5740
-
5741
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
5742
- offset = offset >>> 0;
5743
- if (!noAssert) checkOffset(offset, 4, this.length);
5744
- return ieee754.read(this, offset, false, 23, 4)
5745
- };
5746
-
5747
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
5748
- offset = offset >>> 0;
5749
- if (!noAssert) checkOffset(offset, 8, this.length);
5750
- return ieee754.read(this, offset, true, 52, 8)
5751
- };
5752
-
5753
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
5754
- offset = offset >>> 0;
5755
- if (!noAssert) checkOffset(offset, 8, this.length);
5756
- return ieee754.read(this, offset, false, 52, 8)
5757
- };
5758
-
5759
- function checkInt (buf, value, offset, ext, max, min) {
5760
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
5761
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
5762
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
5763
- }
5764
-
5765
- Buffer.prototype.writeUintLE =
5766
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
5767
- value = +value;
5768
- offset = offset >>> 0;
5769
- byteLength = byteLength >>> 0;
5770
- if (!noAssert) {
5771
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
5772
- checkInt(this, value, offset, byteLength, maxBytes, 0);
5773
- }
5774
-
5775
- var mul = 1;
5776
- var i = 0;
5777
- this[offset] = value & 0xFF;
5778
- while (++i < byteLength && (mul *= 0x100)) {
5779
- this[offset + i] = (value / mul) & 0xFF;
5780
- }
5781
-
5782
- return offset + byteLength
5783
- };
5784
-
5785
- Buffer.prototype.writeUintBE =
5786
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
5787
- value = +value;
5788
- offset = offset >>> 0;
5789
- byteLength = byteLength >>> 0;
5790
- if (!noAssert) {
5791
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
5792
- checkInt(this, value, offset, byteLength, maxBytes, 0);
5793
- }
5794
-
5795
- var i = byteLength - 1;
5796
- var mul = 1;
5797
- this[offset + i] = value & 0xFF;
5798
- while (--i >= 0 && (mul *= 0x100)) {
5799
- this[offset + i] = (value / mul) & 0xFF;
5800
- }
5801
-
5802
- return offset + byteLength
5803
- };
5804
-
5805
- Buffer.prototype.writeUint8 =
5806
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
5807
- value = +value;
5808
- offset = offset >>> 0;
5809
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
5810
- this[offset] = (value & 0xff);
5811
- return offset + 1
5812
- };
5813
-
5814
- Buffer.prototype.writeUint16LE =
5815
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
5816
- value = +value;
5817
- offset = offset >>> 0;
5818
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
5819
- this[offset] = (value & 0xff);
5820
- this[offset + 1] = (value >>> 8);
5821
- return offset + 2
5822
- };
5823
-
5824
- Buffer.prototype.writeUint16BE =
5825
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
5826
- value = +value;
5827
- offset = offset >>> 0;
5828
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
5829
- this[offset] = (value >>> 8);
5830
- this[offset + 1] = (value & 0xff);
5831
- return offset + 2
5832
- };
5833
-
5834
- Buffer.prototype.writeUint32LE =
5835
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
5836
- value = +value;
5837
- offset = offset >>> 0;
5838
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
5839
- this[offset + 3] = (value >>> 24);
5840
- this[offset + 2] = (value >>> 16);
5841
- this[offset + 1] = (value >>> 8);
5842
- this[offset] = (value & 0xff);
5843
- return offset + 4
5844
- };
5845
-
5846
- Buffer.prototype.writeUint32BE =
5847
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
5848
- value = +value;
5849
- offset = offset >>> 0;
5850
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
5851
- this[offset] = (value >>> 24);
5852
- this[offset + 1] = (value >>> 16);
5853
- this[offset + 2] = (value >>> 8);
5854
- this[offset + 3] = (value & 0xff);
5855
- return offset + 4
5856
- };
5857
-
5858
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
5859
- value = +value;
5860
- offset = offset >>> 0;
5861
- if (!noAssert) {
5862
- var limit = Math.pow(2, (8 * byteLength) - 1);
5863
-
5864
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
5865
- }
5866
-
5867
- var i = 0;
5868
- var mul = 1;
5869
- var sub = 0;
5870
- this[offset] = value & 0xFF;
5871
- while (++i < byteLength && (mul *= 0x100)) {
5872
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
5873
- sub = 1;
5874
- }
5875
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
5876
- }
5877
-
5878
- return offset + byteLength
5879
- };
5880
-
5881
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
5882
- value = +value;
5883
- offset = offset >>> 0;
5884
- if (!noAssert) {
5885
- var limit = Math.pow(2, (8 * byteLength) - 1);
5886
-
5887
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
5888
- }
5889
-
5890
- var i = byteLength - 1;
5891
- var mul = 1;
5892
- var sub = 0;
5893
- this[offset + i] = value & 0xFF;
5894
- while (--i >= 0 && (mul *= 0x100)) {
5895
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
5896
- sub = 1;
5897
- }
5898
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
5899
- }
5900
-
5901
- return offset + byteLength
5902
- };
5903
-
5904
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
5905
- value = +value;
5906
- offset = offset >>> 0;
5907
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
5908
- if (value < 0) value = 0xff + value + 1;
5909
- this[offset] = (value & 0xff);
5910
- return offset + 1
5911
- };
5912
-
5913
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
5914
- value = +value;
5915
- offset = offset >>> 0;
5916
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
5917
- this[offset] = (value & 0xff);
5918
- this[offset + 1] = (value >>> 8);
5919
- return offset + 2
5920
- };
5921
-
5922
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
5923
- value = +value;
5924
- offset = offset >>> 0;
5925
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
5926
- this[offset] = (value >>> 8);
5927
- this[offset + 1] = (value & 0xff);
5928
- return offset + 2
5929
- };
5930
-
5931
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
5932
- value = +value;
5933
- offset = offset >>> 0;
5934
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
5935
- this[offset] = (value & 0xff);
5936
- this[offset + 1] = (value >>> 8);
5937
- this[offset + 2] = (value >>> 16);
5938
- this[offset + 3] = (value >>> 24);
5939
- return offset + 4
5940
- };
5941
-
5942
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
5943
- value = +value;
5944
- offset = offset >>> 0;
5945
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
5946
- if (value < 0) value = 0xffffffff + value + 1;
5947
- this[offset] = (value >>> 24);
5948
- this[offset + 1] = (value >>> 16);
5949
- this[offset + 2] = (value >>> 8);
5950
- this[offset + 3] = (value & 0xff);
5951
- return offset + 4
5952
- };
5953
-
5954
- function checkIEEE754 (buf, value, offset, ext, max, min) {
5955
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
5956
- if (offset < 0) throw new RangeError('Index out of range')
5957
- }
5958
-
5959
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
5960
- value = +value;
5961
- offset = offset >>> 0;
5962
- if (!noAssert) {
5963
- checkIEEE754(buf, value, offset, 4);
5964
- }
5965
- ieee754.write(buf, value, offset, littleEndian, 23, 4);
5966
- return offset + 4
5967
- }
5968
-
5969
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
5970
- return writeFloat(this, value, offset, true, noAssert)
5971
- };
5972
-
5973
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
5974
- return writeFloat(this, value, offset, false, noAssert)
5975
- };
5976
-
5977
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
5978
- value = +value;
5979
- offset = offset >>> 0;
5980
- if (!noAssert) {
5981
- checkIEEE754(buf, value, offset, 8);
5982
- }
5983
- ieee754.write(buf, value, offset, littleEndian, 52, 8);
5984
- return offset + 8
5985
- }
5986
-
5987
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
5988
- return writeDouble(this, value, offset, true, noAssert)
5989
- };
5990
-
5991
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
5992
- return writeDouble(this, value, offset, false, noAssert)
5993
- };
5994
-
5995
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
5996
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
5997
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
5998
- if (!start) start = 0;
5999
- if (!end && end !== 0) end = this.length;
6000
- if (targetStart >= target.length) targetStart = target.length;
6001
- if (!targetStart) targetStart = 0;
6002
- if (end > 0 && end < start) end = start;
6003
-
6004
- // Copy 0 bytes; we're done
6005
- if (end === start) return 0
6006
- if (target.length === 0 || this.length === 0) return 0
6007
-
6008
- // Fatal error conditions
6009
- if (targetStart < 0) {
6010
- throw new RangeError('targetStart out of bounds')
6011
- }
6012
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
6013
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
4210
+ E('ERR_OUT_OF_RANGE',
4211
+ function (str, range, input) {
4212
+ let msg = `The value of "${str}" is out of range.`;
4213
+ let received = input;
4214
+ if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
4215
+ received = addNumericalSeparator(String(input));
4216
+ } else if (typeof input === 'bigint') {
4217
+ received = String(input);
4218
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
4219
+ received = addNumericalSeparator(received);
4220
+ }
4221
+ received += 'n';
4222
+ }
4223
+ msg += ` It must be ${range}. Received ${received}`;
4224
+ return msg
4225
+ }, RangeError);
6014
4226
 
6015
- // Are we oob?
6016
- if (end > this.length) end = this.length;
6017
- if (target.length - targetStart < end - start) {
6018
- end = target.length - targetStart + start;
4227
+ function addNumericalSeparator (val) {
4228
+ let res = '';
4229
+ let i = val.length;
4230
+ const start = val[0] === '-' ? 1 : 0;
4231
+ for (; i >= start + 4; i -= 3) {
4232
+ res = `_${val.slice(i - 3, i)}${res}`;
6019
4233
  }
4234
+ return `${val.slice(0, i)}${res}`
4235
+ }
6020
4236
 
6021
- var len = end - start;
4237
+ // CHECK FUNCTIONS
4238
+ // ===============
6022
4239
 
6023
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
6024
- // Use built-in when available, missing from IE11
6025
- this.copyWithin(targetStart, start, end);
6026
- } else {
6027
- Uint8Array.prototype.set.call(
6028
- target,
6029
- this.subarray(start, end),
6030
- targetStart
6031
- );
4240
+ function checkBounds (buf, offset, byteLength) {
4241
+ validateNumber(offset, 'offset');
4242
+ if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
4243
+ boundsError(offset, buf.length - (byteLength + 1));
6032
4244
  }
4245
+ }
6033
4246
 
6034
- return len
6035
- };
6036
-
6037
- // Usage:
6038
- // buffer.fill(number[, offset[, end]])
6039
- // buffer.fill(buffer[, offset[, end]])
6040
- // buffer.fill(string[, offset[, end]][, encoding])
6041
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
6042
- // Handle string cases:
6043
- if (typeof val === 'string') {
6044
- if (typeof start === 'string') {
6045
- encoding = start;
6046
- start = 0;
6047
- end = this.length;
6048
- } else if (typeof end === 'string') {
6049
- encoding = end;
6050
- end = this.length;
6051
- }
6052
- if (encoding !== undefined && typeof encoding !== 'string') {
6053
- throw new TypeError('encoding must be a string')
6054
- }
6055
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
6056
- throw new TypeError('Unknown encoding: ' + encoding)
6057
- }
6058
- if (val.length === 1) {
6059
- var code = val.charCodeAt(0);
6060
- if ((encoding === 'utf8' && code < 128) ||
6061
- encoding === 'latin1') {
6062
- // Fast path: If `val` fits into a single byte, use that numeric value.
6063
- val = code;
4247
+ function checkIntBI (value, min, max, buf, offset, byteLength) {
4248
+ if (value > max || value < min) {
4249
+ const n = typeof min === 'bigint' ? 'n' : '';
4250
+ let range;
4251
+ {
4252
+ if (min === 0 || min === BigInt(0)) {
4253
+ range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;
4254
+ } else {
4255
+ range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
4256
+ `${(byteLength + 1) * 8 - 1}${n}`;
6064
4257
  }
6065
4258
  }
6066
- } else if (typeof val === 'number') {
6067
- val = val & 255;
6068
- } else if (typeof val === 'boolean') {
6069
- val = Number(val);
4259
+ throw new errors.ERR_OUT_OF_RANGE('value', range, value)
6070
4260
  }
4261
+ checkBounds(buf, offset, byteLength);
4262
+ }
6071
4263
 
6072
- // Invalid ranges are not set to a default, so can range check early.
6073
- if (start < 0 || this.length < start || this.length < end) {
6074
- throw new RangeError('Out of range index')
4264
+ function validateNumber (value, name) {
4265
+ if (typeof value !== 'number') {
4266
+ throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
6075
4267
  }
4268
+ }
6076
4269
 
6077
- if (end <= start) {
6078
- return this
4270
+ function boundsError (value, length, type) {
4271
+ if (Math.floor(value) !== value) {
4272
+ validateNumber(value, type);
4273
+ throw new errors.ERR_OUT_OF_RANGE('offset', 'an integer', value)
6079
4274
  }
6080
4275
 
6081
- start = start >>> 0;
6082
- end = end === undefined ? this.length : end >>> 0;
6083
-
6084
- if (!val) val = 0;
6085
-
6086
- var i;
6087
- if (typeof val === 'number') {
6088
- for (i = start; i < end; ++i) {
6089
- this[i] = val;
6090
- }
6091
- } else {
6092
- var bytes = Buffer.isBuffer(val)
6093
- ? val
6094
- : Buffer.from(val, encoding);
6095
- var len = bytes.length;
6096
- if (len === 0) {
6097
- throw new TypeError('The value "' + val +
6098
- '" is invalid for argument "value"')
6099
- }
6100
- for (i = 0; i < end - start; ++i) {
6101
- this[i + start] = bytes[i % len];
6102
- }
4276
+ if (length < 0) {
4277
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
6103
4278
  }
6104
4279
 
6105
- return this
6106
- };
4280
+ throw new errors.ERR_OUT_OF_RANGE('offset',
4281
+ `>= ${0} and <= ${length}`,
4282
+ value)
4283
+ }
6107
4284
 
6108
4285
  // HELPER FUNCTIONS
6109
4286
  // ================
6110
4287
 
6111
- var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
4288
+ const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
6112
4289
 
6113
4290
  function base64clean (str) {
6114
4291
  // Node takes equal signs as end of the Base64 encoding
@@ -6126,12 +4303,12 @@ function requireBuffer () {
6126
4303
 
6127
4304
  function utf8ToBytes (string, units) {
6128
4305
  units = units || Infinity;
6129
- var codePoint;
6130
- var length = string.length;
6131
- var leadSurrogate = null;
6132
- var bytes = [];
4306
+ let codePoint;
4307
+ const length = string.length;
4308
+ let leadSurrogate = null;
4309
+ const bytes = [];
6133
4310
 
6134
- for (var i = 0; i < length; ++i) {
4311
+ for (let i = 0; i < length; ++i) {
6135
4312
  codePoint = string.charCodeAt(i);
6136
4313
 
6137
4314
  // is surrogate component
@@ -6205,8 +4382,8 @@ function requireBuffer () {
6205
4382
  }
6206
4383
 
6207
4384
  function asciiToBytes (str) {
6208
- var byteArray = [];
6209
- for (var i = 0; i < str.length; ++i) {
4385
+ const byteArray = [];
4386
+ for (let i = 0; i < str.length; ++i) {
6210
4387
  // Node's code seems to be doing this and not & 0x7F..
6211
4388
  byteArray.push(str.charCodeAt(i) & 0xFF);
6212
4389
  }
@@ -6214,9 +4391,9 @@ function requireBuffer () {
6214
4391
  }
6215
4392
 
6216
4393
  function utf16leToBytes (str, units) {
6217
- var c, hi, lo;
6218
- var byteArray = [];
6219
- for (var i = 0; i < str.length; ++i) {
4394
+ let c, hi, lo;
4395
+ const byteArray = [];
4396
+ for (let i = 0; i < str.length; ++i) {
6220
4397
  if ((units -= 2) < 0) break
6221
4398
 
6222
4399
  c = str.charCodeAt(i);
@@ -6234,7 +4411,8 @@ function requireBuffer () {
6234
4411
  }
6235
4412
 
6236
4413
  function blitBuffer (src, dst, offset, length) {
6237
- for (var i = 0; i < length; ++i) {
4414
+ let i;
4415
+ for (i = 0; i < length; ++i) {
6238
4416
  if ((i + offset >= dst.length) || (i >= src.length)) break
6239
4417
  dst[i + offset] = src[i];
6240
4418
  }
@@ -6256,23 +4434,34 @@ function requireBuffer () {
6256
4434
 
6257
4435
  // Create lookup table for `toString('hex')`
6258
4436
  // See: https://github.com/feross/buffer/issues/219
6259
- var hexSliceLookupTable = (function () {
6260
- var alphabet = '0123456789abcdef';
6261
- var table = new Array(256);
6262
- for (var i = 0; i < 16; ++i) {
6263
- var i16 = i * 16;
6264
- for (var j = 0; j < 16; ++j) {
4437
+ const hexSliceLookupTable = (function () {
4438
+ const alphabet = '0123456789abcdef';
4439
+ const table = new Array(256);
4440
+ for (let i = 0; i < 16; ++i) {
4441
+ const i16 = i * 16;
4442
+ for (let j = 0; j < 16; ++j) {
6265
4443
  table[i16 + j] = alphabet[i] + alphabet[j];
6266
4444
  }
6267
4445
  }
6268
4446
  return table
6269
- })();
4447
+ })();
4448
+
4449
+ // Return not function with Error if BigInt not supported
4450
+ function defineBigIntMethod (fn) {
4451
+ return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
4452
+ }
4453
+
4454
+ function BufferBigIntNotDefined () {
4455
+ throw new Error('BigInt not supported')
4456
+ }
6270
4457
  } (buffer));
6271
4458
  return buffer;
6272
4459
  }
6273
4460
 
6274
4461
  var bufferExports = requireBuffer();
6275
4462
 
4463
+ var dist = {};
4464
+
6276
4465
  var Codecs = {};
6277
4466
 
6278
4467
  var Frames = {};
@@ -6282,7 +4471,7 @@ var hasRequiredFrames;
6282
4471
  function requireFrames () {
6283
4472
  if (hasRequiredFrames) return Frames;
6284
4473
  hasRequiredFrames = 1;
6285
- (function (exports) {
4474
+ (function (exports$1) {
6286
4475
  /*
6287
4476
  * Copyright 2021-2022 the original author or authors.
6288
4477
  *
@@ -6298,8 +4487,8 @@ function requireFrames () {
6298
4487
  * See the License for the specific language governing permissions and
6299
4488
  * limitations under the License.
6300
4489
  */
6301
- Object.defineProperty(exports, "__esModule", { value: true });
6302
- exports.Frame = exports.Lengths = exports.Flags = exports.FrameTypes = void 0;
4490
+ Object.defineProperty(exports$1, "__esModule", { value: true });
4491
+ exports$1.Frame = exports$1.Lengths = exports$1.Flags = exports$1.FrameTypes = void 0;
6303
4492
  var FrameTypes;
6304
4493
  (function (FrameTypes) {
6305
4494
  FrameTypes[FrameTypes["RESERVED"] = 0] = "RESERVED";
@@ -6318,7 +4507,7 @@ function requireFrames () {
6318
4507
  FrameTypes[FrameTypes["RESUME"] = 13] = "RESUME";
6319
4508
  FrameTypes[FrameTypes["RESUME_OK"] = 14] = "RESUME_OK";
6320
4509
  FrameTypes[FrameTypes["EXT"] = 63] = "EXT";
6321
- })(FrameTypes = exports.FrameTypes || (exports.FrameTypes = {}));
4510
+ })(FrameTypes = exports$1.FrameTypes || (exports$1.FrameTypes = {}));
6322
4511
  (function (Flags) {
6323
4512
  Flags[Flags["NONE"] = 0] = "NONE";
6324
4513
  Flags[Flags["COMPLETE"] = 64] = "COMPLETE";
@@ -6329,7 +4518,7 @@ function requireFrames () {
6329
4518
  Flags[Flags["NEXT"] = 32] = "NEXT";
6330
4519
  Flags[Flags["RESPOND"] = 128] = "RESPOND";
6331
4520
  Flags[Flags["RESUME_ENABLE"] = 128] = "RESUME_ENABLE";
6332
- })(exports.Flags || (exports.Flags = {}));
4521
+ })(exports$1.Flags || (exports$1.Flags = {}));
6333
4522
  (function (Flags) {
6334
4523
  function hasMetadata(flags) {
6335
4524
  return (flags & Flags.METADATA) === Flags.METADATA;
@@ -6363,13 +4552,13 @@ function requireFrames () {
6363
4552
  return (flags & Flags.RESUME_ENABLE) === Flags.RESUME_ENABLE;
6364
4553
  }
6365
4554
  Flags.hasResume = hasResume;
6366
- })(exports.Flags || (exports.Flags = {}));
4555
+ })(exports$1.Flags || (exports$1.Flags = {}));
6367
4556
  (function (Lengths) {
6368
4557
  Lengths[Lengths["FRAME"] = 3] = "FRAME";
6369
4558
  Lengths[Lengths["HEADER"] = 6] = "HEADER";
6370
4559
  Lengths[Lengths["METADATA"] = 3] = "METADATA";
6371
4560
  Lengths[Lengths["REQUEST"] = 3] = "REQUEST";
6372
- })(exports.Lengths || (exports.Lengths = {}));
4561
+ })(exports$1.Lengths || (exports$1.Lengths = {}));
6373
4562
  (function (Frame) {
6374
4563
  function isConnection(frame) {
6375
4564
  return frame.streamId === 0;
@@ -6380,7 +4569,7 @@ function requireFrames () {
6380
4569
  frame.type <= FrameTypes.REQUEST_CHANNEL);
6381
4570
  }
6382
4571
  Frame.isRequest = isRequest;
6383
- })(exports.Frame || (exports.Frame = {}));
4572
+ })(exports$1.Frame || (exports$1.Frame = {}));
6384
4573
 
6385
4574
  } (Frames));
6386
4575
  return Frames;
@@ -6391,7 +4580,7 @@ var hasRequiredCodecs;
6391
4580
  function requireCodecs () {
6392
4581
  if (hasRequiredCodecs) return Codecs;
6393
4582
  hasRequiredCodecs = 1;
6394
- (function (exports) {
4583
+ (function (exports$1) {
6395
4584
  var __generator = (Codecs && Codecs.__generator) || function (thisArg, body) {
6396
4585
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
6397
4586
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
@@ -6419,22 +4608,22 @@ function requireCodecs () {
6419
4608
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
6420
4609
  }
6421
4610
  };
6422
- Object.defineProperty(exports, "__esModule", { value: true });
6423
- exports.Deserializer = exports.sizeOfFrame = exports.serializeFrame = exports.deserializeFrame = exports.serializeFrameWithLength = exports.deserializeFrames = exports.deserializeFrameWithLength = exports.writeUInt64BE = exports.readUInt64BE = exports.writeUInt24BE = exports.readUInt24BE = exports.MAX_VERSION = exports.MAX_TTL = exports.MAX_STREAM_ID = exports.MAX_RESUME_LENGTH = exports.MAX_REQUEST_N = exports.MAX_REQUEST_COUNT = exports.MAX_MIME_LENGTH = exports.MAX_METADATA_LENGTH = exports.MAX_LIFETIME = exports.MAX_KEEPALIVE = exports.MAX_CODE = exports.FRAME_TYPE_OFFFSET = exports.FLAGS_MASK = void 0;
4611
+ Object.defineProperty(exports$1, "__esModule", { value: true });
4612
+ exports$1.Deserializer = exports$1.sizeOfFrame = exports$1.serializeFrame = exports$1.deserializeFrame = exports$1.serializeFrameWithLength = exports$1.deserializeFrames = exports$1.deserializeFrameWithLength = exports$1.writeUInt64BE = exports$1.readUInt64BE = exports$1.writeUInt24BE = exports$1.readUInt24BE = exports$1.MAX_VERSION = exports$1.MAX_TTL = exports$1.MAX_STREAM_ID = exports$1.MAX_RESUME_LENGTH = exports$1.MAX_REQUEST_N = exports$1.MAX_REQUEST_COUNT = exports$1.MAX_MIME_LENGTH = exports$1.MAX_METADATA_LENGTH = exports$1.MAX_LIFETIME = exports$1.MAX_KEEPALIVE = exports$1.MAX_CODE = exports$1.FRAME_TYPE_OFFFSET = exports$1.FLAGS_MASK = void 0;
6424
4613
  var Frames_1 = requireFrames();
6425
- exports.FLAGS_MASK = 0x3ff; // low 10 bits
6426
- exports.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags
6427
- exports.MAX_CODE = 0x7fffffff; // uint31
6428
- exports.MAX_KEEPALIVE = 0x7fffffff; // uint31
6429
- exports.MAX_LIFETIME = 0x7fffffff; // uint31
6430
- exports.MAX_METADATA_LENGTH = 0xffffff; // uint24
6431
- exports.MAX_MIME_LENGTH = 0xff; // int8
6432
- exports.MAX_REQUEST_COUNT = 0x7fffffff; // uint31
6433
- exports.MAX_REQUEST_N = 0x7fffffff; // uint31
6434
- exports.MAX_RESUME_LENGTH = 0xffff; // uint16
6435
- exports.MAX_STREAM_ID = 0x7fffffff; // uint31
6436
- exports.MAX_TTL = 0x7fffffff; // uint31
6437
- exports.MAX_VERSION = 0xffff; // uint16
4614
+ exports$1.FLAGS_MASK = 0x3ff; // low 10 bits
4615
+ exports$1.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags
4616
+ exports$1.MAX_CODE = 0x7fffffff; // uint31
4617
+ exports$1.MAX_KEEPALIVE = 0x7fffffff; // uint31
4618
+ exports$1.MAX_LIFETIME = 0x7fffffff; // uint31
4619
+ exports$1.MAX_METADATA_LENGTH = 0xffffff; // uint24
4620
+ exports$1.MAX_MIME_LENGTH = 0xff; // int8
4621
+ exports$1.MAX_REQUEST_COUNT = 0x7fffffff; // uint31
4622
+ exports$1.MAX_REQUEST_N = 0x7fffffff; // uint31
4623
+ exports$1.MAX_RESUME_LENGTH = 0xffff; // uint16
4624
+ exports$1.MAX_STREAM_ID = 0x7fffffff; // uint31
4625
+ exports$1.MAX_TTL = 0x7fffffff; // uint31
4626
+ exports$1.MAX_VERSION = 0xffff; // uint16
6438
4627
  /**
6439
4628
  * Mimimum value that would overflow bitwise operators (2^32).
6440
4629
  */
@@ -6448,7 +4637,7 @@ function requireCodecs () {
6448
4637
  var val3 = buffer.readUInt8(offset + 2);
6449
4638
  return val1 | val2 | val3;
6450
4639
  }
6451
- exports.readUInt24BE = readUInt24BE;
4640
+ exports$1.readUInt24BE = readUInt24BE;
6452
4641
  /**
6453
4642
  * Writes a uint24 to a buffer starting at the given offset, returning the
6454
4643
  * offset of the next byte.
@@ -6458,7 +4647,7 @@ function requireCodecs () {
6458
4647
  offset = buffer.writeUInt8((value >>> 8) & 0xff, offset); // 2nd byte
6459
4648
  return buffer.writeUInt8(value & 0xff, offset); // 1st byte
6460
4649
  }
6461
- exports.writeUInt24BE = writeUInt24BE;
4650
+ exports$1.writeUInt24BE = writeUInt24BE;
6462
4651
  /**
6463
4652
  * Read a uint64 (technically supports up to 53 bits per JS number
6464
4653
  * representation).
@@ -6468,7 +4657,7 @@ function requireCodecs () {
6468
4657
  var low = buffer.readUInt32BE(offset + 4);
6469
4658
  return high * BITWISE_OVERFLOW + low;
6470
4659
  }
6471
- exports.readUInt64BE = readUInt64BE;
4660
+ exports$1.readUInt64BE = readUInt64BE;
6472
4661
  /**
6473
4662
  * Write a uint64 (technically supports up to 53 bits per JS number
6474
4663
  * representation).
@@ -6479,7 +4668,7 @@ function requireCodecs () {
6479
4668
  offset = buffer.writeUInt32BE(high, offset); // first half of uint64
6480
4669
  return buffer.writeUInt32BE(low, offset); // second half of uint64
6481
4670
  }
6482
- exports.writeUInt64BE = writeUInt64BE;
4671
+ exports$1.writeUInt64BE = writeUInt64BE;
6483
4672
  /**
6484
4673
  * Frame header is:
6485
4674
  * - stream id (uint32 = 4)
@@ -6497,7 +4686,7 @@ function requireCodecs () {
6497
4686
  var frameLength = readUInt24BE(buffer, 0);
6498
4687
  return deserializeFrame(buffer.slice(UINT24_SIZE, UINT24_SIZE + frameLength));
6499
4688
  }
6500
- exports.deserializeFrameWithLength = deserializeFrameWithLength;
4689
+ exports$1.deserializeFrameWithLength = deserializeFrameWithLength;
6501
4690
  /**
6502
4691
  * Given a buffer that may contain zero or more length-prefixed frames followed
6503
4692
  * by zero or more bytes of a (partial) subsequent frame, returns an array of
@@ -6530,7 +4719,7 @@ function requireCodecs () {
6530
4719
  }
6531
4720
  });
6532
4721
  }
6533
- exports.deserializeFrames = deserializeFrames;
4722
+ exports$1.deserializeFrames = deserializeFrames;
6534
4723
  /**
6535
4724
  * Writes a frame to a buffer with a length prefix.
6536
4725
  */
@@ -6541,7 +4730,7 @@ function requireCodecs () {
6541
4730
  buffer.copy(lengthPrefixed, UINT24_SIZE);
6542
4731
  return lengthPrefixed;
6543
4732
  }
6544
- exports.serializeFrameWithLength = serializeFrameWithLength;
4733
+ exports$1.serializeFrameWithLength = serializeFrameWithLength;
6545
4734
  /**
6546
4735
  * Read a frame from the buffer.
6547
4736
  */
@@ -6556,8 +4745,8 @@ function requireCodecs () {
6556
4745
  // );
6557
4746
  var typeAndFlags = buffer.readUInt16BE(offset);
6558
4747
  offset += 2;
6559
- var type = typeAndFlags >>> exports.FRAME_TYPE_OFFFSET; // keep highest 6 bits
6560
- var flags = typeAndFlags & exports.FLAGS_MASK; // keep lowest 10 bits
4748
+ var type = typeAndFlags >>> exports$1.FRAME_TYPE_OFFFSET; // keep highest 6 bits
4749
+ var flags = typeAndFlags & exports$1.FLAGS_MASK; // keep lowest 10 bits
6561
4750
  switch (type) {
6562
4751
  case Frames_1.FrameTypes.SETUP:
6563
4752
  return deserializeSetupFrame(buffer, streamId, flags);
@@ -6594,7 +4783,7 @@ function requireCodecs () {
6594
4783
  // );
6595
4784
  }
6596
4785
  }
6597
- exports.deserializeFrame = deserializeFrame;
4786
+ exports$1.deserializeFrame = deserializeFrame;
6598
4787
  /**
6599
4788
  * Convert the frame to a (binary) buffer.
6600
4789
  */
@@ -6633,7 +4822,7 @@ function requireCodecs () {
6633
4822
  // );
6634
4823
  }
6635
4824
  }
6636
- exports.serializeFrame = serializeFrame;
4825
+ exports$1.serializeFrame = serializeFrame;
6637
4826
  /**
6638
4827
  * Byte size of frame without size prefix
6639
4828
  */
@@ -6672,7 +4861,7 @@ function requireCodecs () {
6672
4861
  // );
6673
4862
  }
6674
4863
  }
6675
- exports.sizeOfFrame = sizeOfFrame;
4864
+ exports$1.sizeOfFrame = sizeOfFrame;
6676
4865
  /**
6677
4866
  * Writes a SETUP frame into a new buffer and returns it.
6678
4867
  *
@@ -7307,7 +5496,7 @@ function requireCodecs () {
7307
5496
  function writeHeader(frame, buffer) {
7308
5497
  var offset = buffer.writeInt32BE(frame.streamId, 0);
7309
5498
  // shift frame to high 6 bits, extract lowest 10 bits from flags
7310
- return buffer.writeUInt16BE((frame.type << exports.FRAME_TYPE_OFFFSET) | (frame.flags & exports.FLAGS_MASK), offset);
5499
+ return buffer.writeUInt16BE((frame.type << exports$1.FRAME_TYPE_OFFFSET) | (frame.flags & exports$1.FLAGS_MASK), offset);
7311
5500
  }
7312
5501
  /**
7313
5502
  * Determine the length of the payload section of a frame. Only applies to
@@ -7388,7 +5577,7 @@ function requireCodecs () {
7388
5577
  };
7389
5578
  return Deserializer;
7390
5579
  }());
7391
- exports.Deserializer = Deserializer;
5580
+ exports$1.Deserializer = Deserializer;
7392
5581
 
7393
5582
  } (Codecs));
7394
5583
  return Codecs;
@@ -7534,7 +5723,7 @@ var hasRequiredErrors;
7534
5723
  function requireErrors () {
7535
5724
  if (hasRequiredErrors) return Errors;
7536
5725
  hasRequiredErrors = 1;
7537
- (function (exports) {
5726
+ (function (exports$1) {
7538
5727
  /*
7539
5728
  * Copyright 2021-2022 the original author or authors.
7540
5729
  *
@@ -7565,8 +5754,8 @@ function requireErrors () {
7565
5754
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7566
5755
  };
7567
5756
  })();
7568
- Object.defineProperty(exports, "__esModule", { value: true });
7569
- exports.ErrorCodes = exports.RSocketError = void 0;
5757
+ Object.defineProperty(exports$1, "__esModule", { value: true });
5758
+ exports$1.ErrorCodes = exports$1.RSocketError = void 0;
7570
5759
  var RSocketError = /** @class */ (function (_super) {
7571
5760
  __extends(RSocketError, _super);
7572
5761
  function RSocketError(code, message) {
@@ -7576,7 +5765,7 @@ function requireErrors () {
7576
5765
  }
7577
5766
  return RSocketError;
7578
5767
  }(Error));
7579
- exports.RSocketError = RSocketError;
5768
+ exports$1.RSocketError = RSocketError;
7580
5769
  (function (ErrorCodes) {
7581
5770
  ErrorCodes[ErrorCodes["RESERVED"] = 0] = "RESERVED";
7582
5771
  ErrorCodes[ErrorCodes["INVALID_SETUP"] = 1] = "INVALID_SETUP";
@@ -7590,7 +5779,7 @@ function requireErrors () {
7590
5779
  ErrorCodes[ErrorCodes["CANCELED"] = 515] = "CANCELED";
7591
5780
  ErrorCodes[ErrorCodes["INVALID"] = 516] = "INVALID";
7592
5781
  ErrorCodes[ErrorCodes["RESERVED_EXTENSION"] = 4294967295] = "RESERVED_EXTENSION";
7593
- })(exports.ErrorCodes || (exports.ErrorCodes = {}));
5782
+ })(exports$1.ErrorCodes || (exports$1.ErrorCodes = {}));
7594
5783
 
7595
5784
  } (Errors));
7596
5785
  return Errors;
@@ -7632,7 +5821,7 @@ var hasRequiredClientServerMultiplexerDemultiplexer;
7632
5821
  function requireClientServerMultiplexerDemultiplexer () {
7633
5822
  if (hasRequiredClientServerMultiplexerDemultiplexer) return ClientServerMultiplexerDemultiplexer;
7634
5823
  hasRequiredClientServerMultiplexerDemultiplexer = 1;
7635
- (function (exports) {
5824
+ (function (exports$1) {
7636
5825
  /*
7637
5826
  * Copyright 2021-2022 the original author or authors.
7638
5827
  *
@@ -7699,8 +5888,8 @@ function requireClientServerMultiplexerDemultiplexer () {
7699
5888
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
7700
5889
  }
7701
5890
  };
7702
- Object.defineProperty(exports, "__esModule", { value: true });
7703
- exports.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports.ResumableClientServerInputMultiplexerDemultiplexer = exports.ClientServerInputMultiplexerDemultiplexer = exports.StreamIdGenerator = void 0;
5891
+ Object.defineProperty(exports$1, "__esModule", { value: true });
5892
+ exports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports$1.ResumableClientServerInputMultiplexerDemultiplexer = exports$1.ClientServerInputMultiplexerDemultiplexer = exports$1.StreamIdGenerator = void 0;
7704
5893
  var _1 = requireDist();
7705
5894
  var Deferred_1 = requireDeferred();
7706
5895
  var Errors_1 = requireErrors();
@@ -7723,7 +5912,7 @@ function requireClientServerMultiplexerDemultiplexer () {
7723
5912
  };
7724
5913
  return StreamIdGeneratorImpl;
7725
5914
  }());
7726
- })(exports.StreamIdGenerator || (exports.StreamIdGenerator = {}));
5915
+ })(exports$1.StreamIdGenerator || (exports$1.StreamIdGenerator = {}));
7727
5916
  var ClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {
7728
5917
  __extends(ClientServerInputMultiplexerDemultiplexer, _super);
7729
5918
  function ClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable) {
@@ -7812,7 +6001,7 @@ function requireClientServerMultiplexerDemultiplexer () {
7812
6001
  };
7813
6002
  return ClientServerInputMultiplexerDemultiplexer;
7814
6003
  }(Deferred_1.Deferred));
7815
- exports.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;
6004
+ exports$1.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;
7816
6005
  var ResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {
7817
6006
  __extends(ResumableClientServerInputMultiplexerDemultiplexer, _super);
7818
6007
  function ResumableClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable, frameStore, token, sessionStoreOrReconnector, sessionTimeout) {
@@ -7969,7 +6158,7 @@ function requireClientServerMultiplexerDemultiplexer () {
7969
6158
  };
7970
6159
  return ResumableClientServerInputMultiplexerDemultiplexer;
7971
6160
  }(ClientServerInputMultiplexerDemultiplexer));
7972
- exports.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;
6161
+ exports$1.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;
7973
6162
  var ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function () {
7974
6163
  function ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, closeable, delegate) {
7975
6164
  this.outbound = outbound;
@@ -8026,7 +6215,7 @@ function requireClientServerMultiplexerDemultiplexer () {
8026
6215
  };
8027
6216
  return ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
8028
6217
  }());
8029
- exports.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
6218
+ exports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
8030
6219
 
8031
6220
  } (ClientServerMultiplexerDemultiplexer));
8032
6221
  return ClientServerMultiplexerDemultiplexer;
@@ -11012,7 +9201,7 @@ var hasRequiredDist;
11012
9201
  function requireDist () {
11013
9202
  if (hasRequiredDist) return dist;
11014
9203
  hasRequiredDist = 1;
11015
- (function (exports) {
9204
+ (function (exports$1) {
11016
9205
  /*
11017
9206
  * Copyright 2021-2022 the original author or authors.
11018
9207
  *
@@ -11035,19 +9224,19 @@ function requireDist () {
11035
9224
  if (k2 === undefined) k2 = k;
11036
9225
  o[k2] = m[k];
11037
9226
  }));
11038
- var __exportStar = (dist && dist.__exportStar) || function(m, exports) {
11039
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
9227
+ var __exportStar = (dist && dist.__exportStar) || function(m, exports$1) {
9228
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
11040
9229
  };
11041
- Object.defineProperty(exports, "__esModule", { value: true });
11042
- __exportStar(requireCodecs(), exports);
11043
- __exportStar(requireCommon(), exports);
11044
- __exportStar(requireDeferred(), exports);
11045
- __exportStar(requireErrors(), exports);
11046
- __exportStar(requireFrames(), exports);
11047
- __exportStar(requireRSocket(), exports);
11048
- __exportStar(requireRSocketConnector(), exports);
11049
- __exportStar(requireRSocketServer(), exports);
11050
- __exportStar(requireTransport(), exports);
9230
+ Object.defineProperty(exports$1, "__esModule", { value: true });
9231
+ __exportStar(requireCodecs(), exports$1);
9232
+ __exportStar(requireCommon(), exports$1);
9233
+ __exportStar(requireDeferred(), exports$1);
9234
+ __exportStar(requireErrors(), exports$1);
9235
+ __exportStar(requireFrames(), exports$1);
9236
+ __exportStar(requireRSocket(), exports$1);
9237
+ __exportStar(requireRSocketConnector(), exports$1);
9238
+ __exportStar(requireRSocketServer(), exports$1);
9239
+ __exportStar(requireTransport(), exports$1);
11051
9240
 
11052
9241
  } (dist));
11053
9242
  return dist;
@@ -11055,7 +9244,7 @@ function requireDist () {
11055
9244
 
11056
9245
  var distExports = requireDist();
11057
9246
 
11058
- var version = "1.44.0";
9247
+ var version = "1.46.0";
11059
9248
  var PACKAGE = {
11060
9249
  version: version};
11061
9250
 
@@ -11126,6 +9315,16 @@ class DataStream extends BaseObserver {
11126
9315
  * @returns a Data payload or Null if the stream closed.
11127
9316
  */
11128
9317
  async read() {
9318
+ if (this.closed) {
9319
+ return null;
9320
+ }
9321
+ // Wait for any pending processing to complete first.
9322
+ // This ensures we register our listener before calling processQueue(),
9323
+ // avoiding a race where processQueue() sees no reader and returns early.
9324
+ if (this.processingPromise) {
9325
+ await this.processingPromise;
9326
+ }
9327
+ // Re-check after await - stream may have closed while we were waiting
11129
9328
  if (this.closed) {
11130
9329
  return null;
11131
9330
  }
@@ -11165,7 +9364,7 @@ class DataStream extends BaseObserver {
11165
9364
  }
11166
9365
  const promise = (this.processingPromise = this._processQueue());
11167
9366
  promise.finally(() => {
11168
- return (this.processingPromise = null);
9367
+ this.processingPromise = null;
11169
9368
  });
11170
9369
  return promise;
11171
9370
  }
@@ -11197,7 +9396,6 @@ class DataStream extends BaseObserver {
11197
9396
  this.notifyDataAdded = null;
11198
9397
  }
11199
9398
  if (this.dataQueue.length > 0) {
11200
- // Next tick
11201
9399
  setTimeout(() => this.processQueue());
11202
9400
  }
11203
9401
  }
@@ -11577,7 +9775,7 @@ class AbstractRemote {
11577
9775
  else {
11578
9776
  contents = JSON.stringify(js);
11579
9777
  }
11580
- return bufferExports$1.Buffer.from(contents);
9778
+ return bufferExports.Buffer.from(contents);
11581
9779
  }
11582
9780
  const syncQueueRequestSize = fetchStrategy == exports.FetchStrategy.Buffered ? 10 : 1;
11583
9781
  const request = await this.buildRequest(path);
@@ -11817,7 +10015,11 @@ class AbstractRemote {
11817
10015
  };
11818
10016
  const stream = new DataStream({
11819
10017
  logger: this.logger,
11820
- mapLine: mapLine
10018
+ mapLine: mapLine,
10019
+ pressure: {
10020
+ highWaterMark: 20,
10021
+ lowWaterMark: 10
10022
+ }
11821
10023
  });
11822
10024
  abortSignal?.addEventListener('abort', () => {
11823
10025
  closeReader();
@@ -11825,42 +10027,47 @@ class AbstractRemote {
11825
10027
  });
11826
10028
  const decoder = this.createTextDecoder();
11827
10029
  let buffer = '';
11828
- const l = stream.registerListener({
11829
- lowWater: async () => {
11830
- if (stream.closed || abortSignal?.aborted || readerReleased) {
10030
+ const consumeStream = async () => {
10031
+ while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
10032
+ const { done, value } = await reader.read();
10033
+ if (done) {
10034
+ const remaining = buffer.trim();
10035
+ if (remaining.length != 0) {
10036
+ stream.enqueueData(remaining);
10037
+ }
10038
+ stream.close();
10039
+ await closeReader();
11831
10040
  return;
11832
10041
  }
11833
- try {
11834
- let didCompleteLine = false;
11835
- while (!didCompleteLine) {
11836
- const { done, value } = await reader.read();
11837
- if (done) {
11838
- const remaining = buffer.trim();
11839
- if (remaining.length != 0) {
11840
- stream.enqueueData(remaining);
11841
- }
11842
- stream.close();
11843
- await closeReader();
11844
- return;
11845
- }
11846
- const data = decoder.decode(value, { stream: true });
11847
- buffer += data;
11848
- const lines = buffer.split('\n');
11849
- for (var i = 0; i < lines.length - 1; i++) {
11850
- var l = lines[i].trim();
11851
- if (l.length > 0) {
11852
- stream.enqueueData(l);
11853
- didCompleteLine = true;
11854
- }
11855
- }
11856
- buffer = lines[lines.length - 1];
10042
+ const data = decoder.decode(value, { stream: true });
10043
+ buffer += data;
10044
+ const lines = buffer.split('\n');
10045
+ for (var i = 0; i < lines.length - 1; i++) {
10046
+ var l = lines[i].trim();
10047
+ if (l.length > 0) {
10048
+ stream.enqueueData(l);
11857
10049
  }
11858
10050
  }
11859
- catch (ex) {
11860
- stream.close();
11861
- throw ex;
10051
+ buffer = lines[lines.length - 1];
10052
+ // Implement backpressure by waiting for the low water mark to be reached
10053
+ if (stream.dataQueue.length > stream.highWatermark) {
10054
+ await new Promise((resolve) => {
10055
+ const dispose = stream.registerListener({
10056
+ lowWater: async () => {
10057
+ resolve();
10058
+ dispose();
10059
+ },
10060
+ closed: () => {
10061
+ resolve();
10062
+ dispose();
10063
+ }
10064
+ });
10065
+ });
11862
10066
  }
11863
- },
10067
+ }
10068
+ };
10069
+ consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
10070
+ const l = stream.registerListener({
11864
10071
  closed: () => {
11865
10072
  closeReader();
11866
10073
  l?.();
@@ -11939,18 +10146,17 @@ exports.SyncClientImplementation = void 0;
11939
10146
  *
11940
10147
  * This is the default option.
11941
10148
  *
11942
- * @deprecated Don't use {@link SyncClientImplementation.JAVASCRIPT} directly. Instead, use
11943
- * {@link DEFAULT_SYNC_CLIENT_IMPLEMENTATION} or omit the option. The explicit choice to use
11944
- * the JavaScript-based sync implementation will be removed from a future version of the SDK.
10149
+ * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
10150
+ * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
10151
+ * version of the PowerSync SDK.
11945
10152
  */
11946
10153
  SyncClientImplementation["JAVASCRIPT"] = "js";
11947
10154
  /**
11948
10155
  * This implementation offloads the sync line decoding and handling into the PowerSync
11949
10156
  * core extension.
11950
10157
  *
11951
- * @experimental
11952
- * While this implementation is more performant than {@link SyncClientImplementation.JAVASCRIPT},
11953
- * it has seen less real-world testing and is marked as __experimental__ at the moment.
10158
+ * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
10159
+ * recommended client implementation for all apps.
11954
10160
  *
11955
10161
  * ## Compatibility warning
11956
10162
  *
@@ -11968,13 +10174,9 @@ exports.SyncClientImplementation = void 0;
11968
10174
  SyncClientImplementation["RUST"] = "rust";
11969
10175
  })(exports.SyncClientImplementation || (exports.SyncClientImplementation = {}));
11970
10176
  /**
11971
- * The default {@link SyncClientImplementation} to use.
11972
- *
11973
- * Please use this field instead of {@link SyncClientImplementation.JAVASCRIPT} directly. A future version
11974
- * of the PowerSync SDK will enable {@link SyncClientImplementation.RUST} by default and remove the JavaScript
11975
- * option.
10177
+ * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
11976
10178
  */
11977
- const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = exports.SyncClientImplementation.JAVASCRIPT;
10179
+ const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = exports.SyncClientImplementation.RUST;
11978
10180
  const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
11979
10181
  const DEFAULT_RETRY_DELAY_MS = 5000;
11980
10182
  const DEFAULT_STREAMING_SYNC_OPTIONS = {
@@ -12384,6 +10586,9 @@ The next upload iteration will be delayed.`);
12384
10586
  if (rawTables != null && rawTables.length) {
12385
10587
  this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
12386
10588
  }
10589
+ if (this.activeStreams.length) {
10590
+ this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
10591
+ }
12387
10592
  this.logger.debug('Streaming sync iteration started');
12388
10593
  this.options.adapter.startSession();
12389
10594
  let [req, bucketMap] = await this.collectLocalBucketState();
@@ -12899,6 +11104,27 @@ The next upload iteration will be delayed.`);
12899
11104
  }
12900
11105
  }
12901
11106
 
11107
+ const CLAIM_STORE = new Map();
11108
+ /**
11109
+ * @internal
11110
+ * @experimental
11111
+ */
11112
+ const MEMORY_TRIGGER_CLAIM_MANAGER = {
11113
+ async obtainClaim(identifier) {
11114
+ if (CLAIM_STORE.has(identifier)) {
11115
+ throw new Error(`A claim is already present for ${identifier}`);
11116
+ }
11117
+ const release = async () => {
11118
+ CLAIM_STORE.delete(identifier);
11119
+ };
11120
+ CLAIM_STORE.set(identifier, release);
11121
+ return release;
11122
+ },
11123
+ async checkClaim(identifier) {
11124
+ return CLAIM_STORE.has(identifier);
11125
+ }
11126
+ };
11127
+
12902
11128
  /**
12903
11129
  * SQLite operations to track changes for with {@link TriggerManager}
12904
11130
  * @experimental
@@ -12910,9 +11136,20 @@ exports.DiffTriggerOperation = void 0;
12910
11136
  DiffTriggerOperation["DELETE"] = "DELETE";
12911
11137
  })(exports.DiffTriggerOperation || (exports.DiffTriggerOperation = {}));
12912
11138
 
11139
+ const DEFAULT_TRIGGER_MANAGER_CONFIGURATION = {
11140
+ useStorageByDefault: false
11141
+ };
11142
+ const TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes
11143
+ /**
11144
+ * @internal
11145
+ * @experimental
11146
+ */
12913
11147
  class TriggerManagerImpl {
12914
11148
  options;
12915
11149
  schema;
11150
+ defaultConfig;
11151
+ cleanupTimeout;
11152
+ isDisposed;
12916
11153
  constructor(options) {
12917
11154
  this.options = options;
12918
11155
  this.schema = options.schema;
@@ -12921,6 +11158,33 @@ class TriggerManagerImpl {
12921
11158
  this.schema = schema;
12922
11159
  }
12923
11160
  });
11161
+ this.isDisposed = false;
11162
+ /**
11163
+ * Configure a cleanup to run on an interval.
11164
+ * The interval is configured using setTimeout to take the async
11165
+ * execution time of the callback into account.
11166
+ */
11167
+ this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;
11168
+ const cleanupCallback = async () => {
11169
+ this.cleanupTimeout = null;
11170
+ if (this.isDisposed) {
11171
+ return;
11172
+ }
11173
+ try {
11174
+ await this.cleanupResources();
11175
+ }
11176
+ catch (ex) {
11177
+ this.db.logger.error(`Caught error while attempting to cleanup triggers`, ex);
11178
+ }
11179
+ finally {
11180
+ // if not closed, set another timeout
11181
+ if (this.isDisposed) {
11182
+ return;
11183
+ }
11184
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
11185
+ }
11186
+ };
11187
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
12924
11188
  }
12925
11189
  get db() {
12926
11190
  return this.options.db;
@@ -12938,13 +11202,95 @@ class TriggerManagerImpl {
12938
11202
  await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);
12939
11203
  }
12940
11204
  }
11205
+ dispose() {
11206
+ this.isDisposed = true;
11207
+ if (this.cleanupTimeout) {
11208
+ clearTimeout(this.cleanupTimeout);
11209
+ }
11210
+ }
11211
+ /**
11212
+ * Updates default config settings for platform specific use-cases.
11213
+ */
11214
+ updateDefaults(config) {
11215
+ this.defaultConfig = {
11216
+ ...this.defaultConfig,
11217
+ ...config
11218
+ };
11219
+ }
11220
+ generateTriggerName(operation, destinationTable, triggerId) {
11221
+ return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;
11222
+ }
11223
+ /**
11224
+ * Cleanup any SQLite triggers or tables that are no longer in use.
11225
+ */
11226
+ async cleanupResources() {
11227
+ // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization
11228
+ await this.db.database.writeLock(async (ctx) => {
11229
+ /**
11230
+ * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.
11231
+ * temporary triggers will not be affected by this.
11232
+ * Query all triggers that match our naming pattern
11233
+ */
11234
+ const triggers = await ctx.getAll(/* sql */ `
11235
+ SELECT
11236
+ name
11237
+ FROM
11238
+ sqlite_master
11239
+ WHERE
11240
+ type = 'trigger'
11241
+ AND name LIKE '__ps_temp_trigger_%'
11242
+ `);
11243
+ /** Use regex to extract table names and IDs from trigger names
11244
+ * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>
11245
+ */
11246
+ const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;
11247
+ const trackedItems = new Map();
11248
+ for (const trigger of triggers) {
11249
+ const match = trigger.name.match(triggerPattern);
11250
+ if (match) {
11251
+ const [, table, id] = match;
11252
+ // Collect all trigger names for each id combo
11253
+ const existing = trackedItems.get(id);
11254
+ if (existing) {
11255
+ existing.triggerNames.push(trigger.name);
11256
+ }
11257
+ else {
11258
+ trackedItems.set(id, { table, id, triggerNames: [trigger.name] });
11259
+ }
11260
+ }
11261
+ }
11262
+ for (const trackedItem of trackedItems.values()) {
11263
+ // check if there is anything holding on to this item
11264
+ const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);
11265
+ if (hasClaim) {
11266
+ // This does not require cleanup
11267
+ continue;
11268
+ }
11269
+ this.db.logger.debug(`Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`);
11270
+ // We need to delete the triggers and table
11271
+ for (const triggerName of trackedItem.triggerNames) {
11272
+ await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);
11273
+ }
11274
+ await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);
11275
+ }
11276
+ });
11277
+ }
12941
11278
  async createDiffTrigger(options) {
12942
11279
  await this.db.waitForReady();
12943
- const { source, destination, columns, when, hooks } = options;
11280
+ const { source, destination, columns, when, hooks,
11281
+ // Fall back to the provided default if not given on this level
11282
+ useStorage = this.defaultConfig.useStorageByDefault } = options;
12944
11283
  const operations = Object.keys(when);
12945
11284
  if (operations.length == 0) {
12946
11285
  throw new Error('At least one WHEN operation must be specified for the trigger.');
12947
11286
  }
11287
+ /**
11288
+ * The clause to use when executing
11289
+ * CREATE ${tableTriggerTypeClause} TABLE
11290
+ * OR
11291
+ * CREATE ${tableTriggerTypeClause} TRIGGER
11292
+ */
11293
+ const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';
12948
11294
  const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));
12949
11295
  /**
12950
11296
  * Allow specifying the View name as the source.
@@ -12958,6 +11304,7 @@ class TriggerManagerImpl {
12958
11304
  const internalSource = sourceDefinition.internalName;
12959
11305
  const triggerIds = [];
12960
11306
  const id = await this.getUUID();
11307
+ const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;
12961
11308
  /**
12962
11309
  * We default to replicating all columns if no columns array is provided.
12963
11310
  */
@@ -12990,26 +11337,27 @@ class TriggerManagerImpl {
12990
11337
  return this.db.writeLock(async (tx) => {
12991
11338
  await this.removeTriggers(tx, triggerIds);
12992
11339
  await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
11340
+ await releaseStorageClaim?.();
12993
11341
  });
12994
11342
  };
12995
11343
  const setup = async (tx) => {
12996
11344
  // Allow user code to execute in this lock context before the trigger is created.
12997
11345
  await hooks?.beforeCreate?.(tx);
12998
11346
  await tx.execute(/* sql */ `
12999
- CREATE TEMP TABLE ${destination} (
11347
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
13000
11348
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
13001
11349
  id TEXT,
13002
11350
  operation TEXT,
13003
11351
  timestamp TEXT,
13004
11352
  value TEXT,
13005
11353
  previous_value TEXT
13006
- );
11354
+ )
13007
11355
  `);
13008
11356
  if (operations.includes(exports.DiffTriggerOperation.INSERT)) {
13009
- const insertTriggerId = `ps_temp_trigger_insert_${id}`;
11357
+ const insertTriggerId = this.generateTriggerName(exports.DiffTriggerOperation.INSERT, destination, id);
13010
11358
  triggerIds.push(insertTriggerId);
13011
11359
  await tx.execute(/* sql */ `
13012
- CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.INSERT]} BEGIN
11360
+ CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.INSERT]} BEGIN
13013
11361
  INSERT INTO
13014
11362
  ${destination} (id, operation, timestamp, value)
13015
11363
  VALUES
@@ -13020,14 +11368,14 @@ class TriggerManagerImpl {
13020
11368
  ${jsonFragment('NEW')}
13021
11369
  );
13022
11370
 
13023
- END;
11371
+ END
13024
11372
  `);
13025
11373
  }
13026
11374
  if (operations.includes(exports.DiffTriggerOperation.UPDATE)) {
13027
- const updateTriggerId = `ps_temp_trigger_update_${id}`;
11375
+ const updateTriggerId = this.generateTriggerName(exports.DiffTriggerOperation.UPDATE, destination, id);
13028
11376
  triggerIds.push(updateTriggerId);
13029
11377
  await tx.execute(/* sql */ `
13030
- CREATE TEMP TRIGGER ${updateTriggerId} AFTER
11378
+ CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER
13031
11379
  UPDATE ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.UPDATE]} BEGIN
13032
11380
  INSERT INTO
13033
11381
  ${destination} (id, operation, timestamp, value, previous_value)
@@ -13044,11 +11392,11 @@ class TriggerManagerImpl {
13044
11392
  `);
13045
11393
  }
13046
11394
  if (operations.includes(exports.DiffTriggerOperation.DELETE)) {
13047
- const deleteTriggerId = `ps_temp_trigger_delete_${id}`;
11395
+ const deleteTriggerId = this.generateTriggerName(exports.DiffTriggerOperation.DELETE, destination, id);
13048
11396
  triggerIds.push(deleteTriggerId);
13049
11397
  // Create delete trigger for basic JSON
13050
11398
  await tx.execute(/* sql */ `
13051
- CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.DELETE]} BEGIN
11399
+ CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[exports.DiffTriggerOperation.DELETE]} BEGIN
13052
11400
  INSERT INTO
13053
11401
  ${destination} (id, operation, timestamp, value)
13054
11402
  VALUES
@@ -13092,7 +11440,7 @@ class TriggerManagerImpl {
13092
11440
  // If no array is provided, we use all columns from the source table.
13093
11441
  const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
13094
11442
  const id = await this.getUUID();
13095
- const destination = `ps_temp_track_${source}_${id}`;
11443
+ const destination = `__ps_temp_track_${source}_${id}`;
13096
11444
  // register an onChange before the trigger is created
13097
11445
  const abortController = new AbortController();
13098
11446
  const abortOnChange = () => abortController.abort();
@@ -13247,6 +11595,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13247
11595
  * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
13248
11596
  */
13249
11597
  triggers;
11598
+ triggersImpl;
13250
11599
  logger;
13251
11600
  constructor(options) {
13252
11601
  super();
@@ -13310,9 +11659,10 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13310
11659
  logger: this.logger
13311
11660
  });
13312
11661
  this._isReadyPromise = this.initialize();
13313
- this.triggers = new TriggerManagerImpl({
11662
+ this.triggers = this.triggersImpl = new TriggerManagerImpl({
13314
11663
  db: this,
13315
- schema: this.schema
11664
+ schema: this.schema,
11665
+ ...this.generateTriggerManagerConfig()
13316
11666
  });
13317
11667
  }
13318
11668
  /**
@@ -13338,6 +11688,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13338
11688
  get connecting() {
13339
11689
  return this.currentStatus?.connecting || false;
13340
11690
  }
11691
+ /**
11692
+ * Generates a base configuration for {@link TriggerManagerImpl}.
11693
+ * Implementations should override this if necessary.
11694
+ */
11695
+ generateTriggerManagerConfig() {
11696
+ return {
11697
+ claimManager: MEMORY_TRIGGER_CLAIM_MANAGER
11698
+ };
11699
+ }
13341
11700
  /**
13342
11701
  * @returns A promise which will resolve once initialization is completed.
13343
11702
  */
@@ -13398,14 +11757,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13398
11757
  async initialize() {
13399
11758
  await this._initialize();
13400
11759
  await this.bucketStorageAdapter.init();
13401
- await this._loadVersion();
11760
+ await this.loadVersion();
13402
11761
  await this.updateSchema(this.options.schema);
13403
11762
  await this.resolveOfflineSyncStatus();
13404
11763
  await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
11764
+ await this.triggersImpl.cleanupResources();
13405
11765
  this.ready = true;
13406
11766
  this.iterateListeners((cb) => cb.initialized?.());
13407
11767
  }
13408
- async _loadVersion() {
11768
+ async loadVersion() {
13409
11769
  try {
13410
11770
  const { version } = await this.database.get('SELECT powersync_rs_version() as version');
13411
11771
  this.sdkVersion = version;
@@ -13521,7 +11881,6 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13521
11881
  await this.disconnect();
13522
11882
  await this.waitForReady();
13523
11883
  const { clearLocal } = options;
13524
- // TODO DB name, verify this is necessary with extension
13525
11884
  await this.database.writeTransaction(async (tx) => {
13526
11885
  await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
13527
11886
  });
@@ -13553,6 +11912,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13553
11912
  if (this.closed) {
13554
11913
  return;
13555
11914
  }
11915
+ this.triggersImpl.dispose();
13556
11916
  await this.iterateAsyncListeners(async (cb) => cb.closing?.());
13557
11917
  const { disconnect } = options;
13558
11918
  if (disconnect) {
@@ -14544,6 +12904,27 @@ class SyncDataBatch {
14544
12904
  }
14545
12905
  }
14546
12906
 
12907
+ /**
12908
+ * Thrown when an underlying database connection is closed.
12909
+ * This is particularly relevant when worker connections are marked as closed while
12910
+ * operations are still in progress.
12911
+ */
12912
+ class ConnectionClosedError extends Error {
12913
+ static NAME = 'ConnectionClosedError';
12914
+ static MATCHES(input) {
12915
+ /**
12916
+ * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
12917
+ * check might fail. This also performs a failsafe check.
12918
+ * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
12919
+ */
12920
+ return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
12921
+ }
12922
+ constructor(message) {
12923
+ super(message);
12924
+ this.name = ConnectionClosedError.NAME;
12925
+ }
12926
+ }
12927
+
14547
12928
  // https://www.sqlite.org/lang_expr.html#castexpr
14548
12929
  exports.ColumnType = void 0;
14549
12930
  (function (ColumnType) {
@@ -15107,6 +13488,7 @@ exports.AbstractStreamingSyncImplementation = AbstractStreamingSyncImplementatio
15107
13488
  exports.ArrayComparator = ArrayComparator;
15108
13489
  exports.BaseObserver = BaseObserver;
15109
13490
  exports.Column = Column;
13491
+ exports.ConnectionClosedError = ConnectionClosedError;
15110
13492
  exports.ConnectionManager = ConnectionManager;
15111
13493
  exports.ControlledExecutor = ControlledExecutor;
15112
13494
  exports.CrudBatch = CrudBatch;
@@ -15142,9 +13524,11 @@ exports.InvalidSQLCharacters = InvalidSQLCharacters;
15142
13524
  exports.LogLevel = LogLevel;
15143
13525
  exports.MAX_AMOUNT_OF_COLUMNS = MAX_AMOUNT_OF_COLUMNS;
15144
13526
  exports.MAX_OP_ID = MAX_OP_ID;
13527
+ exports.MEMORY_TRIGGER_CLAIM_MANAGER = MEMORY_TRIGGER_CLAIM_MANAGER;
15145
13528
  exports.OnChangeQueryProcessor = OnChangeQueryProcessor;
15146
13529
  exports.OpType = OpType;
15147
13530
  exports.OplogEntry = OplogEntry;
13531
+ exports.RawTable = RawTable;
15148
13532
  exports.Schema = Schema;
15149
13533
  exports.SqliteBucketStorage = SqliteBucketStorage;
15150
13534
  exports.SyncDataBatch = SyncDataBatch;
@@ -15153,6 +13537,7 @@ exports.SyncProgress = SyncProgress;
15153
13537
  exports.SyncStatus = SyncStatus;
15154
13538
  exports.Table = Table;
15155
13539
  exports.TableV2 = TableV2;
13540
+ exports.TriggerManagerImpl = TriggerManagerImpl;
15156
13541
  exports.UploadQueueStats = UploadQueueStats;
15157
13542
  exports.column = column;
15158
13543
  exports.compilableQueryWatch = compilableQueryWatch;