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