@powersync/common 1.45.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 (38) hide show
  1. package/dist/bundle.cjs +412 -2067
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +410 -2068
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +237 -63
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +235 -64
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +94 -15
  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/sync/stream/AbstractRemote.js +41 -32
  14. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  15. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +7 -12
  16. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +10 -12
  17. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  18. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  19. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  20. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  21. package/lib/client/triggers/TriggerManager.d.ts +37 -0
  22. package/lib/client/triggers/TriggerManagerImpl.d.ts +24 -3
  23. package/lib/client/triggers/TriggerManagerImpl.js +133 -11
  24. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -1
  25. package/lib/index.d.ts +3 -0
  26. package/lib/index.js +3 -0
  27. package/lib/index.js.map +1 -1
  28. package/lib/utils/DataStream.js +11 -2
  29. package/lib/utils/DataStream.js.map +1 -1
  30. package/package.json +4 -3
  31. package/src/client/AbstractPowerSyncDatabase.ts +21 -6
  32. package/src/client/sync/stream/AbstractRemote.ts +47 -35
  33. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +11 -14
  34. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  35. package/src/client/triggers/TriggerManager.ts +50 -6
  36. package/src/client/triggers/TriggerManagerImpl.ts +177 -13
  37. package/src/index.ts +3 -0
  38. package/src/utils/DataStream.ts +13 -2
package/dist/bundle.mjs CHANGED
@@ -2087,7 +2087,7 @@ class SyncDataBucket {
2087
2087
  }
2088
2088
  }
2089
2089
 
2090
- var buffer$1 = {};
2090
+ var buffer = {};
2091
2091
 
2092
2092
  var base64Js = {};
2093
2093
 
@@ -2351,11 +2351,11 @@ function requireIeee754 () {
2351
2351
  * @license MIT
2352
2352
  */
2353
2353
 
2354
- var hasRequiredBuffer$1;
2354
+ var hasRequiredBuffer;
2355
2355
 
2356
- function requireBuffer$1 () {
2357
- if (hasRequiredBuffer$1) return buffer$1;
2358
- hasRequiredBuffer$1 = 1;
2356
+ function requireBuffer () {
2357
+ if (hasRequiredBuffer) return buffer;
2358
+ hasRequiredBuffer = 1;
2359
2359
  (function (exports$1) {
2360
2360
 
2361
2361
  const base64 = requireBase64Js();
@@ -3992,1980 +3992,8 @@ function requireBuffer$1 () {
3992
3992
  });
3993
3993
 
3994
3994
  Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {
3995
- return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
3996
- });
3997
-
3998
- function checkIEEE754 (buf, value, offset, ext, max, min) {
3999
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
4000
- if (offset < 0) throw new RangeError('Index out of range')
4001
- }
4002
-
4003
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
4004
- value = +value;
4005
- offset = offset >>> 0;
4006
- if (!noAssert) {
4007
- checkIEEE754(buf, value, offset, 4);
4008
- }
4009
- ieee754.write(buf, value, offset, littleEndian, 23, 4);
4010
- return offset + 4
4011
- }
4012
-
4013
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
4014
- return writeFloat(this, value, offset, true, noAssert)
4015
- };
4016
-
4017
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
4018
- return writeFloat(this, value, offset, false, noAssert)
4019
- };
4020
-
4021
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
4022
- value = +value;
4023
- offset = offset >>> 0;
4024
- if (!noAssert) {
4025
- checkIEEE754(buf, value, offset, 8);
4026
- }
4027
- ieee754.write(buf, value, offset, littleEndian, 52, 8);
4028
- return offset + 8
4029
- }
4030
-
4031
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
4032
- return writeDouble(this, value, offset, true, noAssert)
4033
- };
4034
-
4035
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
4036
- return writeDouble(this, value, offset, false, noAssert)
4037
- };
4038
-
4039
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
4040
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
4041
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
4042
- if (!start) start = 0;
4043
- if (!end && end !== 0) end = this.length;
4044
- if (targetStart >= target.length) targetStart = target.length;
4045
- if (!targetStart) targetStart = 0;
4046
- if (end > 0 && end < start) end = start;
4047
-
4048
- // Copy 0 bytes; we're done
4049
- if (end === start) return 0
4050
- if (target.length === 0 || this.length === 0) return 0
4051
-
4052
- // Fatal error conditions
4053
- if (targetStart < 0) {
4054
- throw new RangeError('targetStart out of bounds')
4055
- }
4056
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
4057
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
4058
-
4059
- // Are we oob?
4060
- if (end > this.length) end = this.length;
4061
- if (target.length - targetStart < end - start) {
4062
- end = target.length - targetStart + start;
4063
- }
4064
-
4065
- const len = end - start;
4066
-
4067
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
4068
- // Use built-in when available, missing from IE11
4069
- this.copyWithin(targetStart, start, end);
4070
- } else {
4071
- Uint8Array.prototype.set.call(
4072
- target,
4073
- this.subarray(start, end),
4074
- targetStart
4075
- );
4076
- }
4077
-
4078
- return len
4079
- };
4080
-
4081
- // Usage:
4082
- // buffer.fill(number[, offset[, end]])
4083
- // buffer.fill(buffer[, offset[, end]])
4084
- // buffer.fill(string[, offset[, end]][, encoding])
4085
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
4086
- // Handle string cases:
4087
- if (typeof val === 'string') {
4088
- if (typeof start === 'string') {
4089
- encoding = start;
4090
- start = 0;
4091
- end = this.length;
4092
- } else if (typeof end === 'string') {
4093
- encoding = end;
4094
- end = this.length;
4095
- }
4096
- if (encoding !== undefined && typeof encoding !== 'string') {
4097
- throw new TypeError('encoding must be a string')
4098
- }
4099
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
4100
- throw new TypeError('Unknown encoding: ' + encoding)
4101
- }
4102
- if (val.length === 1) {
4103
- const code = val.charCodeAt(0);
4104
- if ((encoding === 'utf8' && code < 128) ||
4105
- encoding === 'latin1') {
4106
- // Fast path: If `val` fits into a single byte, use that numeric value.
4107
- val = code;
4108
- }
4109
- }
4110
- } else if (typeof val === 'number') {
4111
- val = val & 255;
4112
- } else if (typeof val === 'boolean') {
4113
- val = Number(val);
4114
- }
4115
-
4116
- // Invalid ranges are not set to a default, so can range check early.
4117
- if (start < 0 || this.length < start || this.length < end) {
4118
- throw new RangeError('Out of range index')
4119
- }
4120
-
4121
- if (end <= start) {
4122
- return this
4123
- }
4124
-
4125
- start = start >>> 0;
4126
- end = end === undefined ? this.length : end >>> 0;
4127
-
4128
- if (!val) val = 0;
4129
-
4130
- let i;
4131
- if (typeof val === 'number') {
4132
- for (i = start; i < end; ++i) {
4133
- this[i] = val;
4134
- }
4135
- } else {
4136
- const bytes = Buffer.isBuffer(val)
4137
- ? val
4138
- : Buffer.from(val, encoding);
4139
- const len = bytes.length;
4140
- if (len === 0) {
4141
- throw new TypeError('The value "' + val +
4142
- '" is invalid for argument "value"')
4143
- }
4144
- for (i = 0; i < end - start; ++i) {
4145
- this[i + start] = bytes[i % len];
4146
- }
4147
- }
4148
-
4149
- return this
4150
- };
4151
-
4152
- // CUSTOM ERRORS
4153
- // =============
4154
-
4155
- // Simplified versions from Node, changed for Buffer-only usage
4156
- const errors = {};
4157
- function E (sym, getMessage, Base) {
4158
- errors[sym] = class NodeError extends Base {
4159
- constructor () {
4160
- super();
4161
-
4162
- Object.defineProperty(this, 'message', {
4163
- value: getMessage.apply(this, arguments),
4164
- writable: true,
4165
- configurable: true
4166
- });
4167
-
4168
- // Add the error code to the name to include it in the stack trace.
4169
- this.name = `${this.name} [${sym}]`;
4170
- // Access the stack to generate the error message including the error code
4171
- // from the name.
4172
- this.stack; // eslint-disable-line no-unused-expressions
4173
- // Reset the name to the actual name.
4174
- delete this.name;
4175
- }
4176
-
4177
- get code () {
4178
- return sym
4179
- }
4180
-
4181
- set code (value) {
4182
- Object.defineProperty(this, 'code', {
4183
- configurable: true,
4184
- enumerable: true,
4185
- value,
4186
- writable: true
4187
- });
4188
- }
4189
-
4190
- toString () {
4191
- return `${this.name} [${sym}]: ${this.message}`
4192
- }
4193
- };
4194
- }
4195
-
4196
- E('ERR_BUFFER_OUT_OF_BOUNDS',
4197
- function (name) {
4198
- if (name) {
4199
- return `${name} is outside of buffer bounds`
4200
- }
4201
-
4202
- return 'Attempt to access memory outside buffer bounds'
4203
- }, RangeError);
4204
- E('ERR_INVALID_ARG_TYPE',
4205
- function (name, actual) {
4206
- return `The "${name}" argument must be of type number. Received type ${typeof actual}`
4207
- }, TypeError);
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);
4224
-
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}`;
4231
- }
4232
- return `${val.slice(0, i)}${res}`
4233
- }
4234
-
4235
- // CHECK FUNCTIONS
4236
- // ===============
4237
-
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));
4242
- }
4243
- }
4244
-
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}`;
4255
- }
4256
- }
4257
- throw new errors.ERR_OUT_OF_RANGE('value', range, value)
4258
- }
4259
- checkBounds(buf, offset, byteLength);
4260
- }
4261
-
4262
- function validateNumber (value, name) {
4263
- if (typeof value !== 'number') {
4264
- throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
4265
- }
4266
- }
4267
-
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)
4272
- }
4273
-
4274
- if (length < 0) {
4275
- throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
4276
- }
4277
-
4278
- throw new errors.ERR_OUT_OF_RANGE('offset',
4279
- `>= ${0} and <= ${length}`,
4280
- value)
4281
- }
4282
-
4283
- // HELPER FUNCTIONS
4284
- // ================
4285
-
4286
- const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
4287
-
4288
- function base64clean (str) {
4289
- // Node takes equal signs as end of the Base64 encoding
4290
- str = str.split('=')[0];
4291
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
4292
- str = str.trim().replace(INVALID_BASE64_RE, '');
4293
- // Node converts strings with length < 2 to ''
4294
- if (str.length < 2) return ''
4295
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
4296
- while (str.length % 4 !== 0) {
4297
- str = str + '=';
4298
- }
4299
- return str
4300
- }
4301
-
4302
- function utf8ToBytes (string, units) {
4303
- units = units || Infinity;
4304
- let codePoint;
4305
- const length = string.length;
4306
- let leadSurrogate = null;
4307
- const bytes = [];
4308
-
4309
- for (let i = 0; i < length; ++i) {
4310
- codePoint = string.charCodeAt(i);
4311
-
4312
- // is surrogate component
4313
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
4314
- // last char was a lead
4315
- if (!leadSurrogate) {
4316
- // no lead yet
4317
- if (codePoint > 0xDBFF) {
4318
- // unexpected trail
4319
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4320
- continue
4321
- } else if (i + 1 === length) {
4322
- // unpaired lead
4323
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4324
- continue
4325
- }
4326
-
4327
- // valid lead
4328
- leadSurrogate = codePoint;
4329
-
4330
- continue
4331
- }
4332
-
4333
- // 2 leads in a row
4334
- if (codePoint < 0xDC00) {
4335
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4336
- leadSurrogate = codePoint;
4337
- continue
4338
- }
4339
-
4340
- // valid surrogate pair
4341
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
4342
- } else if (leadSurrogate) {
4343
- // valid bmp char, but last char was a lead
4344
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
4345
- }
4346
-
4347
- leadSurrogate = null;
4348
-
4349
- // encode utf8
4350
- if (codePoint < 0x80) {
4351
- if ((units -= 1) < 0) break
4352
- bytes.push(codePoint);
4353
- } else if (codePoint < 0x800) {
4354
- if ((units -= 2) < 0) break
4355
- bytes.push(
4356
- codePoint >> 0x6 | 0xC0,
4357
- codePoint & 0x3F | 0x80
4358
- );
4359
- } else if (codePoint < 0x10000) {
4360
- if ((units -= 3) < 0) break
4361
- bytes.push(
4362
- codePoint >> 0xC | 0xE0,
4363
- codePoint >> 0x6 & 0x3F | 0x80,
4364
- codePoint & 0x3F | 0x80
4365
- );
4366
- } else if (codePoint < 0x110000) {
4367
- if ((units -= 4) < 0) break
4368
- bytes.push(
4369
- codePoint >> 0x12 | 0xF0,
4370
- codePoint >> 0xC & 0x3F | 0x80,
4371
- codePoint >> 0x6 & 0x3F | 0x80,
4372
- codePoint & 0x3F | 0x80
4373
- );
4374
- } else {
4375
- throw new Error('Invalid code point')
4376
- }
4377
- }
4378
-
4379
- return bytes
4380
- }
4381
-
4382
- function asciiToBytes (str) {
4383
- const byteArray = [];
4384
- for (let i = 0; i < str.length; ++i) {
4385
- // Node's code seems to be doing this and not & 0x7F..
4386
- byteArray.push(str.charCodeAt(i) & 0xFF);
4387
- }
4388
- return byteArray
4389
- }
4390
-
4391
- function utf16leToBytes (str, units) {
4392
- let c, hi, lo;
4393
- const byteArray = [];
4394
- for (let i = 0; i < str.length; ++i) {
4395
- if ((units -= 2) < 0) break
4396
-
4397
- c = str.charCodeAt(i);
4398
- hi = c >> 8;
4399
- lo = c % 256;
4400
- byteArray.push(lo);
4401
- byteArray.push(hi);
4402
- }
4403
-
4404
- return byteArray
4405
- }
4406
-
4407
- function base64ToBytes (str) {
4408
- return base64.toByteArray(base64clean(str))
4409
- }
4410
-
4411
- function blitBuffer (src, dst, offset, length) {
4412
- let i;
4413
- for (i = 0; i < length; ++i) {
4414
- if ((i + offset >= dst.length) || (i >= src.length)) break
4415
- dst[i + offset] = src[i];
4416
- }
4417
- return i
4418
- }
4419
-
4420
- // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
4421
- // the `instanceof` check but they should be treated as of that type.
4422
- // See: https://github.com/feross/buffer/issues/166
4423
- function isInstance (obj, type) {
4424
- return obj instanceof type ||
4425
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
4426
- obj.constructor.name === type.name)
4427
- }
4428
- function numberIsNaN (obj) {
4429
- // For IE11 support
4430
- return obj !== obj // eslint-disable-line no-self-compare
4431
- }
4432
-
4433
- // Create lookup table for `toString('hex')`
4434
- // See: https://github.com/feross/buffer/issues/219
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) {
4441
- table[i16 + j] = alphabet[i] + alphabet[j];
4442
- }
4443
- }
4444
- return table
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
- }
4455
- } (buffer$1));
4456
- return buffer$1;
4457
- }
4458
-
4459
- var bufferExports$1 = requireBuffer$1();
4460
-
4461
- var dist = {};
4462
-
4463
- var buffer = {};
4464
-
4465
- /*!
4466
- * The buffer module from node.js, for the browser.
4467
- *
4468
- * @author Feross Aboukhadijeh <https://feross.org>
4469
- * @license MIT
4470
- */
4471
-
4472
- var hasRequiredBuffer;
4473
-
4474
- function requireBuffer () {
4475
- if (hasRequiredBuffer) return buffer;
4476
- hasRequiredBuffer = 1;
4477
- (function (exports$1) {
4478
-
4479
- var base64 = requireBase64Js();
4480
- var ieee754 = requireIeee754();
4481
- var customInspectSymbol =
4482
- (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
4483
- ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
4484
- : null;
4485
-
4486
- exports$1.Buffer = Buffer;
4487
- exports$1.SlowBuffer = SlowBuffer;
4488
- exports$1.INSPECT_MAX_BYTES = 50;
4489
-
4490
- var K_MAX_LENGTH = 0x7fffffff;
4491
- exports$1.kMaxLength = K_MAX_LENGTH;
4492
-
4493
- /**
4494
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
4495
- * === true Use Uint8Array implementation (fastest)
4496
- * === false Print warning and recommend using `buffer` v4.x which has an Object
4497
- * implementation (most compatible, even IE6)
4498
- *
4499
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
4500
- * Opera 11.6+, iOS 4.2+.
4501
- *
4502
- * We report that the browser does not support typed arrays if the are not subclassable
4503
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
4504
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
4505
- * for __proto__ and has a buggy typed array implementation.
4506
- */
4507
- Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
4508
-
4509
- if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
4510
- typeof console.error === 'function') {
4511
- console.error(
4512
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
4513
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
4514
- );
4515
- }
4516
-
4517
- function typedArraySupport () {
4518
- // Can typed array instances can be augmented?
4519
- try {
4520
- var arr = new Uint8Array(1);
4521
- var proto = { foo: function () { return 42 } };
4522
- Object.setPrototypeOf(proto, Uint8Array.prototype);
4523
- Object.setPrototypeOf(arr, proto);
4524
- return arr.foo() === 42
4525
- } catch (e) {
4526
- return false
4527
- }
4528
- }
4529
-
4530
- Object.defineProperty(Buffer.prototype, 'parent', {
4531
- enumerable: true,
4532
- get: function () {
4533
- if (!Buffer.isBuffer(this)) return undefined
4534
- return this.buffer
4535
- }
4536
- });
4537
-
4538
- Object.defineProperty(Buffer.prototype, 'offset', {
4539
- enumerable: true,
4540
- get: function () {
4541
- if (!Buffer.isBuffer(this)) return undefined
4542
- return this.byteOffset
4543
- }
4544
- });
4545
-
4546
- function createBuffer (length) {
4547
- if (length > K_MAX_LENGTH) {
4548
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
4549
- }
4550
- // Return an augmented `Uint8Array` instance
4551
- var buf = new Uint8Array(length);
4552
- Object.setPrototypeOf(buf, Buffer.prototype);
4553
- return buf
4554
- }
4555
-
4556
- /**
4557
- * The Buffer constructor returns instances of `Uint8Array` that have their
4558
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
4559
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
4560
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
4561
- * returns a single octet.
4562
- *
4563
- * The `Uint8Array` prototype remains unmodified.
4564
- */
4565
-
4566
- function Buffer (arg, encodingOrOffset, length) {
4567
- // Common case.
4568
- if (typeof arg === 'number') {
4569
- if (typeof encodingOrOffset === 'string') {
4570
- throw new TypeError(
4571
- 'The "string" argument must be of type string. Received type number'
4572
- )
4573
- }
4574
- return allocUnsafe(arg)
4575
- }
4576
- return from(arg, encodingOrOffset, length)
4577
- }
4578
-
4579
- Buffer.poolSize = 8192; // not used by this implementation
4580
-
4581
- function from (value, encodingOrOffset, length) {
4582
- if (typeof value === 'string') {
4583
- return fromString(value, encodingOrOffset)
4584
- }
4585
-
4586
- if (ArrayBuffer.isView(value)) {
4587
- return fromArrayView(value)
4588
- }
4589
-
4590
- if (value == null) {
4591
- throw new TypeError(
4592
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
4593
- 'or Array-like Object. Received type ' + (typeof value)
4594
- )
4595
- }
4596
-
4597
- if (isInstance(value, ArrayBuffer) ||
4598
- (value && isInstance(value.buffer, ArrayBuffer))) {
4599
- return fromArrayBuffer(value, encodingOrOffset, length)
4600
- }
4601
-
4602
- if (typeof SharedArrayBuffer !== 'undefined' &&
4603
- (isInstance(value, SharedArrayBuffer) ||
4604
- (value && isInstance(value.buffer, SharedArrayBuffer)))) {
4605
- return fromArrayBuffer(value, encodingOrOffset, length)
4606
- }
4607
-
4608
- if (typeof value === 'number') {
4609
- throw new TypeError(
4610
- 'The "value" argument must not be of type number. Received type number'
4611
- )
4612
- }
4613
-
4614
- var valueOf = value.valueOf && value.valueOf();
4615
- if (valueOf != null && valueOf !== value) {
4616
- return Buffer.from(valueOf, encodingOrOffset, length)
4617
- }
4618
-
4619
- var b = fromObject(value);
4620
- if (b) return b
4621
-
4622
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
4623
- typeof value[Symbol.toPrimitive] === 'function') {
4624
- return Buffer.from(
4625
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
4626
- )
4627
- }
4628
-
4629
- throw new TypeError(
4630
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
4631
- 'or Array-like Object. Received type ' + (typeof value)
4632
- )
4633
- }
4634
-
4635
- /**
4636
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
4637
- * if value is a number.
4638
- * Buffer.from(str[, encoding])
4639
- * Buffer.from(array)
4640
- * Buffer.from(buffer)
4641
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
4642
- **/
4643
- Buffer.from = function (value, encodingOrOffset, length) {
4644
- return from(value, encodingOrOffset, length)
4645
- };
4646
-
4647
- // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
4648
- // https://github.com/feross/buffer/pull/148
4649
- Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
4650
- Object.setPrototypeOf(Buffer, Uint8Array);
4651
-
4652
- function assertSize (size) {
4653
- if (typeof size !== 'number') {
4654
- throw new TypeError('"size" argument must be of type number')
4655
- } else if (size < 0) {
4656
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
4657
- }
4658
- }
4659
-
4660
- function alloc (size, fill, encoding) {
4661
- assertSize(size);
4662
- if (size <= 0) {
4663
- return createBuffer(size)
4664
- }
4665
- if (fill !== undefined) {
4666
- // Only pay attention to encoding if it's a string. This
4667
- // prevents accidentally sending in a number that would
4668
- // be interpreted as a start offset.
4669
- return typeof encoding === 'string'
4670
- ? createBuffer(size).fill(fill, encoding)
4671
- : createBuffer(size).fill(fill)
4672
- }
4673
- return createBuffer(size)
4674
- }
4675
-
4676
- /**
4677
- * Creates a new filled Buffer instance.
4678
- * alloc(size[, fill[, encoding]])
4679
- **/
4680
- Buffer.alloc = function (size, fill, encoding) {
4681
- return alloc(size, fill, encoding)
4682
- };
4683
-
4684
- function allocUnsafe (size) {
4685
- assertSize(size);
4686
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
4687
- }
4688
-
4689
- /**
4690
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
4691
- * */
4692
- Buffer.allocUnsafe = function (size) {
4693
- return allocUnsafe(size)
4694
- };
4695
- /**
4696
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
4697
- */
4698
- Buffer.allocUnsafeSlow = function (size) {
4699
- return allocUnsafe(size)
4700
- };
4701
-
4702
- function fromString (string, encoding) {
4703
- if (typeof encoding !== 'string' || encoding === '') {
4704
- encoding = 'utf8';
4705
- }
4706
-
4707
- if (!Buffer.isEncoding(encoding)) {
4708
- throw new TypeError('Unknown encoding: ' + encoding)
4709
- }
4710
-
4711
- var length = byteLength(string, encoding) | 0;
4712
- var buf = createBuffer(length);
4713
-
4714
- var actual = buf.write(string, encoding);
4715
-
4716
- if (actual !== length) {
4717
- // Writing a hex string, for example, that contains invalid characters will
4718
- // cause everything after the first invalid character to be ignored. (e.g.
4719
- // 'abxxcd' will be treated as 'ab')
4720
- buf = buf.slice(0, actual);
4721
- }
4722
-
4723
- return buf
4724
- }
4725
-
4726
- function fromArrayLike (array) {
4727
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
4728
- var buf = createBuffer(length);
4729
- for (var i = 0; i < length; i += 1) {
4730
- buf[i] = array[i] & 255;
4731
- }
4732
- return buf
4733
- }
4734
-
4735
- function fromArrayView (arrayView) {
4736
- if (isInstance(arrayView, Uint8Array)) {
4737
- var copy = new Uint8Array(arrayView);
4738
- return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
4739
- }
4740
- return fromArrayLike(arrayView)
4741
- }
4742
-
4743
- function fromArrayBuffer (array, byteOffset, length) {
4744
- if (byteOffset < 0 || array.byteLength < byteOffset) {
4745
- throw new RangeError('"offset" is outside of buffer bounds')
4746
- }
4747
-
4748
- if (array.byteLength < byteOffset + (length || 0)) {
4749
- throw new RangeError('"length" is outside of buffer bounds')
4750
- }
4751
-
4752
- var buf;
4753
- if (byteOffset === undefined && length === undefined) {
4754
- buf = new Uint8Array(array);
4755
- } else if (length === undefined) {
4756
- buf = new Uint8Array(array, byteOffset);
4757
- } else {
4758
- buf = new Uint8Array(array, byteOffset, length);
4759
- }
4760
-
4761
- // Return an augmented `Uint8Array` instance
4762
- Object.setPrototypeOf(buf, Buffer.prototype);
4763
-
4764
- return buf
4765
- }
4766
-
4767
- function fromObject (obj) {
4768
- if (Buffer.isBuffer(obj)) {
4769
- var len = checked(obj.length) | 0;
4770
- var buf = createBuffer(len);
4771
-
4772
- if (buf.length === 0) {
4773
- return buf
4774
- }
4775
-
4776
- obj.copy(buf, 0, 0, len);
4777
- return buf
4778
- }
4779
-
4780
- if (obj.length !== undefined) {
4781
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
4782
- return createBuffer(0)
4783
- }
4784
- return fromArrayLike(obj)
4785
- }
4786
-
4787
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
4788
- return fromArrayLike(obj.data)
4789
- }
4790
- }
4791
-
4792
- function checked (length) {
4793
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
4794
- // length is NaN (which is otherwise coerced to zero.)
4795
- if (length >= K_MAX_LENGTH) {
4796
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
4797
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
4798
- }
4799
- return length | 0
4800
- }
4801
-
4802
- function SlowBuffer (length) {
4803
- if (+length != length) { // eslint-disable-line eqeqeq
4804
- length = 0;
4805
- }
4806
- return Buffer.alloc(+length)
4807
- }
4808
-
4809
- Buffer.isBuffer = function isBuffer (b) {
4810
- return b != null && b._isBuffer === true &&
4811
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
4812
- };
4813
-
4814
- Buffer.compare = function compare (a, b) {
4815
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
4816
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
4817
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
4818
- throw new TypeError(
4819
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
4820
- )
4821
- }
4822
-
4823
- if (a === b) return 0
4824
-
4825
- var x = a.length;
4826
- var y = b.length;
4827
-
4828
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
4829
- if (a[i] !== b[i]) {
4830
- x = a[i];
4831
- y = b[i];
4832
- break
4833
- }
4834
- }
4835
-
4836
- if (x < y) return -1
4837
- if (y < x) return 1
4838
- return 0
4839
- };
4840
-
4841
- Buffer.isEncoding = function isEncoding (encoding) {
4842
- switch (String(encoding).toLowerCase()) {
4843
- case 'hex':
4844
- case 'utf8':
4845
- case 'utf-8':
4846
- case 'ascii':
4847
- case 'latin1':
4848
- case 'binary':
4849
- case 'base64':
4850
- case 'ucs2':
4851
- case 'ucs-2':
4852
- case 'utf16le':
4853
- case 'utf-16le':
4854
- return true
4855
- default:
4856
- return false
4857
- }
4858
- };
4859
-
4860
- Buffer.concat = function concat (list, length) {
4861
- if (!Array.isArray(list)) {
4862
- throw new TypeError('"list" argument must be an Array of Buffers')
4863
- }
4864
-
4865
- if (list.length === 0) {
4866
- return Buffer.alloc(0)
4867
- }
4868
-
4869
- var i;
4870
- if (length === undefined) {
4871
- length = 0;
4872
- for (i = 0; i < list.length; ++i) {
4873
- length += list[i].length;
4874
- }
4875
- }
4876
-
4877
- var buffer = Buffer.allocUnsafe(length);
4878
- var pos = 0;
4879
- for (i = 0; i < list.length; ++i) {
4880
- var buf = list[i];
4881
- if (isInstance(buf, Uint8Array)) {
4882
- if (pos + buf.length > buffer.length) {
4883
- Buffer.from(buf).copy(buffer, pos);
4884
- } else {
4885
- Uint8Array.prototype.set.call(
4886
- buffer,
4887
- buf,
4888
- pos
4889
- );
4890
- }
4891
- } else if (!Buffer.isBuffer(buf)) {
4892
- throw new TypeError('"list" argument must be an Array of Buffers')
4893
- } else {
4894
- buf.copy(buffer, pos);
4895
- }
4896
- pos += buf.length;
4897
- }
4898
- return buffer
4899
- };
4900
-
4901
- function byteLength (string, encoding) {
4902
- if (Buffer.isBuffer(string)) {
4903
- return string.length
4904
- }
4905
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
4906
- return string.byteLength
4907
- }
4908
- if (typeof string !== 'string') {
4909
- throw new TypeError(
4910
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
4911
- 'Received type ' + typeof string
4912
- )
4913
- }
4914
-
4915
- var len = string.length;
4916
- var mustMatch = (arguments.length > 2 && arguments[2] === true);
4917
- if (!mustMatch && len === 0) return 0
4918
-
4919
- // Use a for loop to avoid recursion
4920
- var loweredCase = false;
4921
- for (;;) {
4922
- switch (encoding) {
4923
- case 'ascii':
4924
- case 'latin1':
4925
- case 'binary':
4926
- return len
4927
- case 'utf8':
4928
- case 'utf-8':
4929
- return utf8ToBytes(string).length
4930
- case 'ucs2':
4931
- case 'ucs-2':
4932
- case 'utf16le':
4933
- case 'utf-16le':
4934
- return len * 2
4935
- case 'hex':
4936
- return len >>> 1
4937
- case 'base64':
4938
- return base64ToBytes(string).length
4939
- default:
4940
- if (loweredCase) {
4941
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
4942
- }
4943
- encoding = ('' + encoding).toLowerCase();
4944
- loweredCase = true;
4945
- }
4946
- }
4947
- }
4948
- Buffer.byteLength = byteLength;
4949
-
4950
- function slowToString (encoding, start, end) {
4951
- var loweredCase = false;
4952
-
4953
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
4954
- // property of a typed array.
4955
-
4956
- // This behaves neither like String nor Uint8Array in that we set start/end
4957
- // to their upper/lower bounds if the value passed is out of range.
4958
- // undefined is handled specially as per ECMA-262 6th Edition,
4959
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
4960
- if (start === undefined || start < 0) {
4961
- start = 0;
4962
- }
4963
- // Return early if start > this.length. Done here to prevent potential uint32
4964
- // coercion fail below.
4965
- if (start > this.length) {
4966
- return ''
4967
- }
4968
-
4969
- if (end === undefined || end > this.length) {
4970
- end = this.length;
4971
- }
4972
-
4973
- if (end <= 0) {
4974
- return ''
4975
- }
4976
-
4977
- // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
4978
- end >>>= 0;
4979
- start >>>= 0;
4980
-
4981
- if (end <= start) {
4982
- return ''
4983
- }
4984
-
4985
- if (!encoding) encoding = 'utf8';
4986
-
4987
- while (true) {
4988
- switch (encoding) {
4989
- case 'hex':
4990
- return hexSlice(this, start, end)
4991
-
4992
- case 'utf8':
4993
- case 'utf-8':
4994
- return utf8Slice(this, start, end)
4995
-
4996
- case 'ascii':
4997
- return asciiSlice(this, start, end)
4998
-
4999
- case 'latin1':
5000
- case 'binary':
5001
- return latin1Slice(this, start, end)
5002
-
5003
- case 'base64':
5004
- return base64Slice(this, start, end)
5005
-
5006
- case 'ucs2':
5007
- case 'ucs-2':
5008
- case 'utf16le':
5009
- case 'utf-16le':
5010
- return utf16leSlice(this, start, end)
5011
-
5012
- default:
5013
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5014
- encoding = (encoding + '').toLowerCase();
5015
- loweredCase = true;
5016
- }
5017
- }
5018
- }
5019
-
5020
- // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
5021
- // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
5022
- // reliably in a browserify context because there could be multiple different
5023
- // copies of the 'buffer' package in use. This method works even for Buffer
5024
- // instances that were created from another copy of the `buffer` package.
5025
- // See: https://github.com/feross/buffer/issues/154
5026
- Buffer.prototype._isBuffer = true;
5027
-
5028
- function swap (b, n, m) {
5029
- var i = b[n];
5030
- b[n] = b[m];
5031
- b[m] = i;
5032
- }
5033
-
5034
- Buffer.prototype.swap16 = function swap16 () {
5035
- var len = this.length;
5036
- if (len % 2 !== 0) {
5037
- throw new RangeError('Buffer size must be a multiple of 16-bits')
5038
- }
5039
- for (var i = 0; i < len; i += 2) {
5040
- swap(this, i, i + 1);
5041
- }
5042
- return this
5043
- };
5044
-
5045
- Buffer.prototype.swap32 = function swap32 () {
5046
- var len = this.length;
5047
- if (len % 4 !== 0) {
5048
- throw new RangeError('Buffer size must be a multiple of 32-bits')
5049
- }
5050
- for (var i = 0; i < len; i += 4) {
5051
- swap(this, i, i + 3);
5052
- swap(this, i + 1, i + 2);
5053
- }
5054
- return this
5055
- };
5056
-
5057
- Buffer.prototype.swap64 = function swap64 () {
5058
- var len = this.length;
5059
- if (len % 8 !== 0) {
5060
- throw new RangeError('Buffer size must be a multiple of 64-bits')
5061
- }
5062
- for (var i = 0; i < len; i += 8) {
5063
- swap(this, i, i + 7);
5064
- swap(this, i + 1, i + 6);
5065
- swap(this, i + 2, i + 5);
5066
- swap(this, i + 3, i + 4);
5067
- }
5068
- return this
5069
- };
5070
-
5071
- Buffer.prototype.toString = function toString () {
5072
- var length = this.length;
5073
- if (length === 0) return ''
5074
- if (arguments.length === 0) return utf8Slice(this, 0, length)
5075
- return slowToString.apply(this, arguments)
5076
- };
5077
-
5078
- Buffer.prototype.toLocaleString = Buffer.prototype.toString;
5079
-
5080
- Buffer.prototype.equals = function equals (b) {
5081
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
5082
- if (this === b) return true
5083
- return Buffer.compare(this, b) === 0
5084
- };
5085
-
5086
- Buffer.prototype.inspect = function inspect () {
5087
- var str = '';
5088
- var max = exports$1.INSPECT_MAX_BYTES;
5089
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
5090
- if (this.length > max) str += ' ... ';
5091
- return '<Buffer ' + str + '>'
5092
- };
5093
- if (customInspectSymbol) {
5094
- Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
5095
- }
5096
-
5097
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
5098
- if (isInstance(target, Uint8Array)) {
5099
- target = Buffer.from(target, target.offset, target.byteLength);
5100
- }
5101
- if (!Buffer.isBuffer(target)) {
5102
- throw new TypeError(
5103
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
5104
- 'Received type ' + (typeof target)
5105
- )
5106
- }
5107
-
5108
- if (start === undefined) {
5109
- start = 0;
5110
- }
5111
- if (end === undefined) {
5112
- end = target ? target.length : 0;
5113
- }
5114
- if (thisStart === undefined) {
5115
- thisStart = 0;
5116
- }
5117
- if (thisEnd === undefined) {
5118
- thisEnd = this.length;
5119
- }
5120
-
5121
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
5122
- throw new RangeError('out of range index')
5123
- }
5124
-
5125
- if (thisStart >= thisEnd && start >= end) {
5126
- return 0
5127
- }
5128
- if (thisStart >= thisEnd) {
5129
- return -1
5130
- }
5131
- if (start >= end) {
5132
- return 1
5133
- }
5134
-
5135
- start >>>= 0;
5136
- end >>>= 0;
5137
- thisStart >>>= 0;
5138
- thisEnd >>>= 0;
5139
-
5140
- if (this === target) return 0
5141
-
5142
- var x = thisEnd - thisStart;
5143
- var y = end - start;
5144
- var len = Math.min(x, y);
5145
-
5146
- var thisCopy = this.slice(thisStart, thisEnd);
5147
- var targetCopy = target.slice(start, end);
5148
-
5149
- for (var i = 0; i < len; ++i) {
5150
- if (thisCopy[i] !== targetCopy[i]) {
5151
- x = thisCopy[i];
5152
- y = targetCopy[i];
5153
- break
5154
- }
5155
- }
5156
-
5157
- if (x < y) return -1
5158
- if (y < x) return 1
5159
- return 0
5160
- };
5161
-
5162
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
5163
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
5164
- //
5165
- // Arguments:
5166
- // - buffer - a Buffer to search
5167
- // - val - a string, Buffer, or number
5168
- // - byteOffset - an index into `buffer`; will be clamped to an int32
5169
- // - encoding - an optional encoding, relevant is val is a string
5170
- // - dir - true for indexOf, false for lastIndexOf
5171
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
5172
- // Empty buffer means no match
5173
- if (buffer.length === 0) return -1
5174
-
5175
- // Normalize byteOffset
5176
- if (typeof byteOffset === 'string') {
5177
- encoding = byteOffset;
5178
- byteOffset = 0;
5179
- } else if (byteOffset > 0x7fffffff) {
5180
- byteOffset = 0x7fffffff;
5181
- } else if (byteOffset < -2147483648) {
5182
- byteOffset = -2147483648;
5183
- }
5184
- byteOffset = +byteOffset; // Coerce to Number.
5185
- if (numberIsNaN(byteOffset)) {
5186
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
5187
- byteOffset = dir ? 0 : (buffer.length - 1);
5188
- }
5189
-
5190
- // Normalize byteOffset: negative offsets start from the end of the buffer
5191
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
5192
- if (byteOffset >= buffer.length) {
5193
- if (dir) return -1
5194
- else byteOffset = buffer.length - 1;
5195
- } else if (byteOffset < 0) {
5196
- if (dir) byteOffset = 0;
5197
- else return -1
5198
- }
5199
-
5200
- // Normalize val
5201
- if (typeof val === 'string') {
5202
- val = Buffer.from(val, encoding);
5203
- }
5204
-
5205
- // Finally, search either indexOf (if dir is true) or lastIndexOf
5206
- if (Buffer.isBuffer(val)) {
5207
- // Special case: looking for empty string/buffer always fails
5208
- if (val.length === 0) {
5209
- return -1
5210
- }
5211
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
5212
- } else if (typeof val === 'number') {
5213
- val = val & 0xFF; // Search for a byte value [0-255]
5214
- if (typeof Uint8Array.prototype.indexOf === 'function') {
5215
- if (dir) {
5216
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
5217
- } else {
5218
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
5219
- }
5220
- }
5221
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
5222
- }
5223
-
5224
- throw new TypeError('val must be string, number or Buffer')
5225
- }
5226
-
5227
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
5228
- var indexSize = 1;
5229
- var arrLength = arr.length;
5230
- var valLength = val.length;
5231
-
5232
- if (encoding !== undefined) {
5233
- encoding = String(encoding).toLowerCase();
5234
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
5235
- encoding === 'utf16le' || encoding === 'utf-16le') {
5236
- if (arr.length < 2 || val.length < 2) {
5237
- return -1
5238
- }
5239
- indexSize = 2;
5240
- arrLength /= 2;
5241
- valLength /= 2;
5242
- byteOffset /= 2;
5243
- }
5244
- }
5245
-
5246
- function read (buf, i) {
5247
- if (indexSize === 1) {
5248
- return buf[i]
5249
- } else {
5250
- return buf.readUInt16BE(i * indexSize)
5251
- }
5252
- }
5253
-
5254
- var i;
5255
- if (dir) {
5256
- var foundIndex = -1;
5257
- for (i = byteOffset; i < arrLength; i++) {
5258
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
5259
- if (foundIndex === -1) foundIndex = i;
5260
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
5261
- } else {
5262
- if (foundIndex !== -1) i -= i - foundIndex;
5263
- foundIndex = -1;
5264
- }
5265
- }
5266
- } else {
5267
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
5268
- for (i = byteOffset; i >= 0; i--) {
5269
- var found = true;
5270
- for (var j = 0; j < valLength; j++) {
5271
- if (read(arr, i + j) !== read(val, j)) {
5272
- found = false;
5273
- break
5274
- }
5275
- }
5276
- if (found) return i
5277
- }
5278
- }
5279
-
5280
- return -1
5281
- }
5282
-
5283
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
5284
- return this.indexOf(val, byteOffset, encoding) !== -1
5285
- };
5286
-
5287
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
5288
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
5289
- };
5290
-
5291
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
5292
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
5293
- };
5294
-
5295
- function hexWrite (buf, string, offset, length) {
5296
- offset = Number(offset) || 0;
5297
- var remaining = buf.length - offset;
5298
- if (!length) {
5299
- length = remaining;
5300
- } else {
5301
- length = Number(length);
5302
- if (length > remaining) {
5303
- length = remaining;
5304
- }
5305
- }
5306
-
5307
- var strLen = string.length;
5308
-
5309
- if (length > strLen / 2) {
5310
- length = strLen / 2;
5311
- }
5312
- for (var i = 0; i < length; ++i) {
5313
- var parsed = parseInt(string.substr(i * 2, 2), 16);
5314
- if (numberIsNaN(parsed)) return i
5315
- buf[offset + i] = parsed;
5316
- }
5317
- return i
5318
- }
5319
-
5320
- function utf8Write (buf, string, offset, length) {
5321
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
5322
- }
5323
-
5324
- function asciiWrite (buf, string, offset, length) {
5325
- return blitBuffer(asciiToBytes(string), buf, offset, length)
5326
- }
5327
-
5328
- function base64Write (buf, string, offset, length) {
5329
- return blitBuffer(base64ToBytes(string), buf, offset, length)
5330
- }
5331
-
5332
- function ucs2Write (buf, string, offset, length) {
5333
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
5334
- }
5335
-
5336
- Buffer.prototype.write = function write (string, offset, length, encoding) {
5337
- // Buffer#write(string)
5338
- if (offset === undefined) {
5339
- encoding = 'utf8';
5340
- length = this.length;
5341
- offset = 0;
5342
- // Buffer#write(string, encoding)
5343
- } else if (length === undefined && typeof offset === 'string') {
5344
- encoding = offset;
5345
- length = this.length;
5346
- offset = 0;
5347
- // Buffer#write(string, offset[, length][, encoding])
5348
- } else if (isFinite(offset)) {
5349
- offset = offset >>> 0;
5350
- if (isFinite(length)) {
5351
- length = length >>> 0;
5352
- if (encoding === undefined) encoding = 'utf8';
5353
- } else {
5354
- encoding = length;
5355
- length = undefined;
5356
- }
5357
- } else {
5358
- throw new Error(
5359
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
5360
- )
5361
- }
5362
-
5363
- var remaining = this.length - offset;
5364
- if (length === undefined || length > remaining) length = remaining;
5365
-
5366
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
5367
- throw new RangeError('Attempt to write outside buffer bounds')
5368
- }
5369
-
5370
- if (!encoding) encoding = 'utf8';
5371
-
5372
- var loweredCase = false;
5373
- for (;;) {
5374
- switch (encoding) {
5375
- case 'hex':
5376
- return hexWrite(this, string, offset, length)
5377
-
5378
- case 'utf8':
5379
- case 'utf-8':
5380
- return utf8Write(this, string, offset, length)
5381
-
5382
- case 'ascii':
5383
- case 'latin1':
5384
- case 'binary':
5385
- return asciiWrite(this, string, offset, length)
5386
-
5387
- case 'base64':
5388
- // Warning: maxLength not taken into account in base64Write
5389
- return base64Write(this, string, offset, length)
5390
-
5391
- case 'ucs2':
5392
- case 'ucs-2':
5393
- case 'utf16le':
5394
- case 'utf-16le':
5395
- return ucs2Write(this, string, offset, length)
5396
-
5397
- default:
5398
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
5399
- encoding = ('' + encoding).toLowerCase();
5400
- loweredCase = true;
5401
- }
5402
- }
5403
- };
5404
-
5405
- Buffer.prototype.toJSON = function toJSON () {
5406
- return {
5407
- type: 'Buffer',
5408
- data: Array.prototype.slice.call(this._arr || this, 0)
5409
- }
5410
- };
5411
-
5412
- function base64Slice (buf, start, end) {
5413
- if (start === 0 && end === buf.length) {
5414
- return base64.fromByteArray(buf)
5415
- } else {
5416
- return base64.fromByteArray(buf.slice(start, end))
5417
- }
5418
- }
5419
-
5420
- function utf8Slice (buf, start, end) {
5421
- end = Math.min(buf.length, end);
5422
- var res = [];
5423
-
5424
- var i = start;
5425
- while (i < end) {
5426
- var firstByte = buf[i];
5427
- var codePoint = null;
5428
- var bytesPerSequence = (firstByte > 0xEF)
5429
- ? 4
5430
- : (firstByte > 0xDF)
5431
- ? 3
5432
- : (firstByte > 0xBF)
5433
- ? 2
5434
- : 1;
5435
-
5436
- if (i + bytesPerSequence <= end) {
5437
- var secondByte, thirdByte, fourthByte, tempCodePoint;
5438
-
5439
- switch (bytesPerSequence) {
5440
- case 1:
5441
- if (firstByte < 0x80) {
5442
- codePoint = firstByte;
5443
- }
5444
- break
5445
- case 2:
5446
- secondByte = buf[i + 1];
5447
- if ((secondByte & 0xC0) === 0x80) {
5448
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
5449
- if (tempCodePoint > 0x7F) {
5450
- codePoint = tempCodePoint;
5451
- }
5452
- }
5453
- break
5454
- case 3:
5455
- secondByte = buf[i + 1];
5456
- thirdByte = buf[i + 2];
5457
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
5458
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
5459
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
5460
- codePoint = tempCodePoint;
5461
- }
5462
- }
5463
- break
5464
- case 4:
5465
- secondByte = buf[i + 1];
5466
- thirdByte = buf[i + 2];
5467
- fourthByte = buf[i + 3];
5468
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
5469
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
5470
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
5471
- codePoint = tempCodePoint;
5472
- }
5473
- }
5474
- }
5475
- }
5476
-
5477
- if (codePoint === null) {
5478
- // we did not generate a valid codePoint so insert a
5479
- // replacement char (U+FFFD) and advance only 1 byte
5480
- codePoint = 0xFFFD;
5481
- bytesPerSequence = 1;
5482
- } else if (codePoint > 0xFFFF) {
5483
- // encode to utf16 (surrogate pair dance)
5484
- codePoint -= 0x10000;
5485
- res.push(codePoint >>> 10 & 0x3FF | 0xD800);
5486
- codePoint = 0xDC00 | codePoint & 0x3FF;
5487
- }
5488
-
5489
- res.push(codePoint);
5490
- i += bytesPerSequence;
5491
- }
5492
-
5493
- return decodeCodePointsArray(res)
5494
- }
5495
-
5496
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
5497
- // the lowest limit is Chrome, with 0x10000 args.
5498
- // We go 1 magnitude less, for safety
5499
- var MAX_ARGUMENTS_LENGTH = 0x1000;
5500
-
5501
- function decodeCodePointsArray (codePoints) {
5502
- var len = codePoints.length;
5503
- if (len <= MAX_ARGUMENTS_LENGTH) {
5504
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
5505
- }
5506
-
5507
- // Decode in chunks to avoid "call stack size exceeded".
5508
- var res = '';
5509
- var i = 0;
5510
- while (i < len) {
5511
- res += String.fromCharCode.apply(
5512
- String,
5513
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
5514
- );
5515
- }
5516
- return res
5517
- }
5518
-
5519
- function asciiSlice (buf, start, end) {
5520
- var ret = '';
5521
- end = Math.min(buf.length, end);
5522
-
5523
- for (var i = start; i < end; ++i) {
5524
- ret += String.fromCharCode(buf[i] & 0x7F);
5525
- }
5526
- return ret
5527
- }
5528
-
5529
- function latin1Slice (buf, start, end) {
5530
- var ret = '';
5531
- end = Math.min(buf.length, end);
5532
-
5533
- for (var i = start; i < end; ++i) {
5534
- ret += String.fromCharCode(buf[i]);
5535
- }
5536
- return ret
5537
- }
5538
-
5539
- function hexSlice (buf, start, end) {
5540
- var len = buf.length;
5541
-
5542
- if (!start || start < 0) start = 0;
5543
- if (!end || end < 0 || end > len) end = len;
5544
-
5545
- var out = '';
5546
- for (var i = start; i < end; ++i) {
5547
- out += hexSliceLookupTable[buf[i]];
5548
- }
5549
- return out
5550
- }
5551
-
5552
- function utf16leSlice (buf, start, end) {
5553
- var bytes = buf.slice(start, end);
5554
- var res = '';
5555
- // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
5556
- for (var i = 0; i < bytes.length - 1; i += 2) {
5557
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
5558
- }
5559
- return res
5560
- }
5561
-
5562
- Buffer.prototype.slice = function slice (start, end) {
5563
- var len = this.length;
5564
- start = ~~start;
5565
- end = end === undefined ? len : ~~end;
5566
-
5567
- if (start < 0) {
5568
- start += len;
5569
- if (start < 0) start = 0;
5570
- } else if (start > len) {
5571
- start = len;
5572
- }
5573
-
5574
- if (end < 0) {
5575
- end += len;
5576
- if (end < 0) end = 0;
5577
- } else if (end > len) {
5578
- end = len;
5579
- }
5580
-
5581
- if (end < start) end = start;
5582
-
5583
- var newBuf = this.subarray(start, end);
5584
- // Return an augmented `Uint8Array` instance
5585
- Object.setPrototypeOf(newBuf, Buffer.prototype);
5586
-
5587
- return newBuf
5588
- };
5589
-
5590
- /*
5591
- * Need to make sure that buffer isn't trying to write out of bounds.
5592
- */
5593
- function checkOffset (offset, ext, length) {
5594
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
5595
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
5596
- }
5597
-
5598
- Buffer.prototype.readUintLE =
5599
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
5600
- offset = offset >>> 0;
5601
- byteLength = byteLength >>> 0;
5602
- if (!noAssert) checkOffset(offset, byteLength, this.length);
5603
-
5604
- var val = this[offset];
5605
- var mul = 1;
5606
- var i = 0;
5607
- while (++i < byteLength && (mul *= 0x100)) {
5608
- val += this[offset + i] * mul;
5609
- }
5610
-
5611
- return val
5612
- };
5613
-
5614
- Buffer.prototype.readUintBE =
5615
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
5616
- offset = offset >>> 0;
5617
- byteLength = byteLength >>> 0;
5618
- if (!noAssert) {
5619
- checkOffset(offset, byteLength, this.length);
5620
- }
5621
-
5622
- var val = this[offset + --byteLength];
5623
- var mul = 1;
5624
- while (byteLength > 0 && (mul *= 0x100)) {
5625
- val += this[offset + --byteLength] * mul;
5626
- }
5627
-
5628
- return val
5629
- };
5630
-
5631
- Buffer.prototype.readUint8 =
5632
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
5633
- offset = offset >>> 0;
5634
- if (!noAssert) checkOffset(offset, 1, this.length);
5635
- return this[offset]
5636
- };
5637
-
5638
- Buffer.prototype.readUint16LE =
5639
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
5640
- offset = offset >>> 0;
5641
- if (!noAssert) checkOffset(offset, 2, this.length);
5642
- return this[offset] | (this[offset + 1] << 8)
5643
- };
5644
-
5645
- Buffer.prototype.readUint16BE =
5646
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
5647
- offset = offset >>> 0;
5648
- if (!noAssert) checkOffset(offset, 2, this.length);
5649
- return (this[offset] << 8) | this[offset + 1]
5650
- };
5651
-
5652
- Buffer.prototype.readUint32LE =
5653
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
5654
- offset = offset >>> 0;
5655
- if (!noAssert) checkOffset(offset, 4, this.length);
5656
-
5657
- return ((this[offset]) |
5658
- (this[offset + 1] << 8) |
5659
- (this[offset + 2] << 16)) +
5660
- (this[offset + 3] * 0x1000000)
5661
- };
5662
-
5663
- Buffer.prototype.readUint32BE =
5664
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
5665
- offset = offset >>> 0;
5666
- if (!noAssert) checkOffset(offset, 4, this.length);
5667
-
5668
- return (this[offset] * 0x1000000) +
5669
- ((this[offset + 1] << 16) |
5670
- (this[offset + 2] << 8) |
5671
- this[offset + 3])
5672
- };
5673
-
5674
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
5675
- offset = offset >>> 0;
5676
- byteLength = byteLength >>> 0;
5677
- if (!noAssert) checkOffset(offset, byteLength, this.length);
5678
-
5679
- var val = this[offset];
5680
- var mul = 1;
5681
- var i = 0;
5682
- while (++i < byteLength && (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.readIntBE = function readIntBE (offset, byteLength, noAssert) {
5693
- offset = offset >>> 0;
5694
- byteLength = byteLength >>> 0;
5695
- if (!noAssert) checkOffset(offset, byteLength, this.length);
5696
-
5697
- var i = byteLength;
5698
- var mul = 1;
5699
- var val = this[offset + --i];
5700
- while (i > 0 && (mul *= 0x100)) {
5701
- val += this[offset + --i] * mul;
5702
- }
5703
- mul *= 0x80;
5704
-
5705
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
5706
-
5707
- return val
5708
- };
5709
-
5710
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
5711
- offset = offset >>> 0;
5712
- if (!noAssert) checkOffset(offset, 1, this.length);
5713
- if (!(this[offset] & 0x80)) return (this[offset])
5714
- return ((0xff - this[offset] + 1) * -1)
5715
- };
5716
-
5717
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
5718
- offset = offset >>> 0;
5719
- if (!noAssert) checkOffset(offset, 2, this.length);
5720
- var val = this[offset] | (this[offset + 1] << 8);
5721
- return (val & 0x8000) ? val | 0xFFFF0000 : val
5722
- };
5723
-
5724
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
5725
- offset = offset >>> 0;
5726
- if (!noAssert) checkOffset(offset, 2, this.length);
5727
- var val = this[offset + 1] | (this[offset] << 8);
5728
- return (val & 0x8000) ? val | 0xFFFF0000 : val
5729
- };
5730
-
5731
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
5732
- offset = offset >>> 0;
5733
- if (!noAssert) checkOffset(offset, 4, this.length);
5734
-
5735
- return (this[offset]) |
5736
- (this[offset + 1] << 8) |
5737
- (this[offset + 2] << 16) |
5738
- (this[offset + 3] << 24)
5739
- };
5740
-
5741
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
5742
- offset = offset >>> 0;
5743
- if (!noAssert) checkOffset(offset, 4, this.length);
5744
-
5745
- return (this[offset] << 24) |
5746
- (this[offset + 1] << 16) |
5747
- (this[offset + 2] << 8) |
5748
- (this[offset + 3])
5749
- };
5750
-
5751
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
5752
- offset = offset >>> 0;
5753
- if (!noAssert) checkOffset(offset, 4, this.length);
5754
- return ieee754.read(this, offset, true, 23, 4)
5755
- };
5756
-
5757
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
5758
- offset = offset >>> 0;
5759
- if (!noAssert) checkOffset(offset, 4, this.length);
5760
- return ieee754.read(this, offset, false, 23, 4)
5761
- };
5762
-
5763
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
5764
- offset = offset >>> 0;
5765
- if (!noAssert) checkOffset(offset, 8, this.length);
5766
- return ieee754.read(this, offset, true, 52, 8)
5767
- };
5768
-
5769
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
5770
- offset = offset >>> 0;
5771
- if (!noAssert) checkOffset(offset, 8, this.length);
5772
- return ieee754.read(this, offset, false, 52, 8)
5773
- };
5774
-
5775
- function checkInt (buf, value, offset, ext, max, min) {
5776
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
5777
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
5778
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
5779
- }
5780
-
5781
- Buffer.prototype.writeUintLE =
5782
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
5783
- value = +value;
5784
- offset = offset >>> 0;
5785
- byteLength = byteLength >>> 0;
5786
- if (!noAssert) {
5787
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
5788
- checkInt(this, value, offset, byteLength, maxBytes, 0);
5789
- }
5790
-
5791
- var mul = 1;
5792
- var i = 0;
5793
- this[offset] = value & 0xFF;
5794
- while (++i < byteLength && (mul *= 0x100)) {
5795
- this[offset + i] = (value / mul) & 0xFF;
5796
- }
5797
-
5798
- return offset + byteLength
5799
- };
5800
-
5801
- Buffer.prototype.writeUintBE =
5802
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
5803
- value = +value;
5804
- offset = offset >>> 0;
5805
- byteLength = byteLength >>> 0;
5806
- if (!noAssert) {
5807
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
5808
- checkInt(this, value, offset, byteLength, maxBytes, 0);
5809
- }
5810
-
5811
- var i = byteLength - 1;
5812
- var mul = 1;
5813
- this[offset + i] = value & 0xFF;
5814
- while (--i >= 0 && (mul *= 0x100)) {
5815
- this[offset + i] = (value / mul) & 0xFF;
5816
- }
5817
-
5818
- return offset + byteLength
5819
- };
5820
-
5821
- Buffer.prototype.writeUint8 =
5822
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
5823
- value = +value;
5824
- offset = offset >>> 0;
5825
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
5826
- this[offset] = (value & 0xff);
5827
- return offset + 1
5828
- };
5829
-
5830
- Buffer.prototype.writeUint16LE =
5831
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
5832
- value = +value;
5833
- offset = offset >>> 0;
5834
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
5835
- this[offset] = (value & 0xff);
5836
- this[offset + 1] = (value >>> 8);
5837
- return offset + 2
5838
- };
5839
-
5840
- Buffer.prototype.writeUint16BE =
5841
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
5842
- value = +value;
5843
- offset = offset >>> 0;
5844
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
5845
- this[offset] = (value >>> 8);
5846
- this[offset + 1] = (value & 0xff);
5847
- return offset + 2
5848
- };
5849
-
5850
- Buffer.prototype.writeUint32LE =
5851
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
5852
- value = +value;
5853
- offset = offset >>> 0;
5854
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
5855
- this[offset + 3] = (value >>> 24);
5856
- this[offset + 2] = (value >>> 16);
5857
- this[offset + 1] = (value >>> 8);
5858
- this[offset] = (value & 0xff);
5859
- return offset + 4
5860
- };
5861
-
5862
- Buffer.prototype.writeUint32BE =
5863
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
5864
- value = +value;
5865
- offset = offset >>> 0;
5866
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
5867
- this[offset] = (value >>> 24);
5868
- this[offset + 1] = (value >>> 16);
5869
- this[offset + 2] = (value >>> 8);
5870
- this[offset + 3] = (value & 0xff);
5871
- return offset + 4
5872
- };
5873
-
5874
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
5875
- value = +value;
5876
- offset = offset >>> 0;
5877
- if (!noAssert) {
5878
- var limit = Math.pow(2, (8 * byteLength) - 1);
5879
-
5880
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
5881
- }
5882
-
5883
- var i = 0;
5884
- var mul = 1;
5885
- var sub = 0;
5886
- this[offset] = value & 0xFF;
5887
- while (++i < byteLength && (mul *= 0x100)) {
5888
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
5889
- sub = 1;
5890
- }
5891
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
5892
- }
5893
-
5894
- return offset + byteLength
5895
- };
5896
-
5897
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
5898
- value = +value;
5899
- offset = offset >>> 0;
5900
- if (!noAssert) {
5901
- var limit = Math.pow(2, (8 * byteLength) - 1);
5902
-
5903
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
5904
- }
5905
-
5906
- var i = byteLength - 1;
5907
- var mul = 1;
5908
- var sub = 0;
5909
- this[offset + i] = value & 0xFF;
5910
- while (--i >= 0 && (mul *= 0x100)) {
5911
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
5912
- sub = 1;
5913
- }
5914
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
5915
- }
5916
-
5917
- return offset + byteLength
5918
- };
5919
-
5920
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
5921
- value = +value;
5922
- offset = offset >>> 0;
5923
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
5924
- if (value < 0) value = 0xff + value + 1;
5925
- this[offset] = (value & 0xff);
5926
- return offset + 1
5927
- };
5928
-
5929
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
5930
- value = +value;
5931
- offset = offset >>> 0;
5932
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
5933
- this[offset] = (value & 0xff);
5934
- this[offset + 1] = (value >>> 8);
5935
- return offset + 2
5936
- };
5937
-
5938
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
5939
- value = +value;
5940
- offset = offset >>> 0;
5941
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
5942
- this[offset] = (value >>> 8);
5943
- this[offset + 1] = (value & 0xff);
5944
- return offset + 2
5945
- };
5946
-
5947
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
5948
- value = +value;
5949
- offset = offset >>> 0;
5950
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
5951
- this[offset] = (value & 0xff);
5952
- this[offset + 1] = (value >>> 8);
5953
- this[offset + 2] = (value >>> 16);
5954
- this[offset + 3] = (value >>> 24);
5955
- return offset + 4
5956
- };
5957
-
5958
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
5959
- value = +value;
5960
- offset = offset >>> 0;
5961
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
5962
- if (value < 0) value = 0xffffffff + value + 1;
5963
- this[offset] = (value >>> 24);
5964
- this[offset + 1] = (value >>> 16);
5965
- this[offset + 2] = (value >>> 8);
5966
- this[offset + 3] = (value & 0xff);
5967
- return offset + 4
5968
- };
3995
+ return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
3996
+ });
5969
3997
 
5970
3998
  function checkIEEE754 (buf, value, offset, ext, max, min) {
5971
3999
  if (offset + ext > buf.length) throw new RangeError('Index out of range')
@@ -6034,7 +4062,7 @@ function requireBuffer () {
6034
4062
  end = target.length - targetStart + start;
6035
4063
  }
6036
4064
 
6037
- var len = end - start;
4065
+ const len = end - start;
6038
4066
 
6039
4067
  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
6040
4068
  // Use built-in when available, missing from IE11
@@ -6072,7 +4100,7 @@ function requireBuffer () {
6072
4100
  throw new TypeError('Unknown encoding: ' + encoding)
6073
4101
  }
6074
4102
  if (val.length === 1) {
6075
- var code = val.charCodeAt(0);
4103
+ const code = val.charCodeAt(0);
6076
4104
  if ((encoding === 'utf8' && code < 128) ||
6077
4105
  encoding === 'latin1') {
6078
4106
  // Fast path: If `val` fits into a single byte, use that numeric value.
@@ -6099,16 +4127,16 @@ function requireBuffer () {
6099
4127
 
6100
4128
  if (!val) val = 0;
6101
4129
 
6102
- var i;
4130
+ let i;
6103
4131
  if (typeof val === 'number') {
6104
4132
  for (i = start; i < end; ++i) {
6105
4133
  this[i] = val;
6106
4134
  }
6107
4135
  } else {
6108
- var bytes = Buffer.isBuffer(val)
4136
+ const bytes = Buffer.isBuffer(val)
6109
4137
  ? val
6110
4138
  : Buffer.from(val, encoding);
6111
- var len = bytes.length;
4139
+ const len = bytes.length;
6112
4140
  if (len === 0) {
6113
4141
  throw new TypeError('The value "' + val +
6114
4142
  '" is invalid for argument "value"')
@@ -6121,10 +4149,141 @@ function requireBuffer () {
6121
4149
  return this
6122
4150
  };
6123
4151
 
4152
+ // CUSTOM ERRORS
4153
+ // =============
4154
+
4155
+ // Simplified versions from Node, changed for Buffer-only usage
4156
+ const errors = {};
4157
+ function E (sym, getMessage, Base) {
4158
+ errors[sym] = class NodeError extends Base {
4159
+ constructor () {
4160
+ super();
4161
+
4162
+ Object.defineProperty(this, 'message', {
4163
+ value: getMessage.apply(this, arguments),
4164
+ writable: true,
4165
+ configurable: true
4166
+ });
4167
+
4168
+ // Add the error code to the name to include it in the stack trace.
4169
+ this.name = `${this.name} [${sym}]`;
4170
+ // Access the stack to generate the error message including the error code
4171
+ // from the name.
4172
+ this.stack; // eslint-disable-line no-unused-expressions
4173
+ // Reset the name to the actual name.
4174
+ delete this.name;
4175
+ }
4176
+
4177
+ get code () {
4178
+ return sym
4179
+ }
4180
+
4181
+ set code (value) {
4182
+ Object.defineProperty(this, 'code', {
4183
+ configurable: true,
4184
+ enumerable: true,
4185
+ value,
4186
+ writable: true
4187
+ });
4188
+ }
4189
+
4190
+ toString () {
4191
+ return `${this.name} [${sym}]: ${this.message}`
4192
+ }
4193
+ };
4194
+ }
4195
+
4196
+ E('ERR_BUFFER_OUT_OF_BOUNDS',
4197
+ function (name) {
4198
+ if (name) {
4199
+ return `${name} is outside of buffer bounds`
4200
+ }
4201
+
4202
+ return 'Attempt to access memory outside buffer bounds'
4203
+ }, RangeError);
4204
+ E('ERR_INVALID_ARG_TYPE',
4205
+ function (name, actual) {
4206
+ return `The "${name}" argument must be of type number. Received type ${typeof actual}`
4207
+ }, TypeError);
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);
4224
+
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}`;
4231
+ }
4232
+ return `${val.slice(0, i)}${res}`
4233
+ }
4234
+
4235
+ // CHECK FUNCTIONS
4236
+ // ===============
4237
+
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));
4242
+ }
4243
+ }
4244
+
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}`;
4255
+ }
4256
+ }
4257
+ throw new errors.ERR_OUT_OF_RANGE('value', range, value)
4258
+ }
4259
+ checkBounds(buf, offset, byteLength);
4260
+ }
4261
+
4262
+ function validateNumber (value, name) {
4263
+ if (typeof value !== 'number') {
4264
+ throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
4265
+ }
4266
+ }
4267
+
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)
4272
+ }
4273
+
4274
+ if (length < 0) {
4275
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
4276
+ }
4277
+
4278
+ throw new errors.ERR_OUT_OF_RANGE('offset',
4279
+ `>= ${0} and <= ${length}`,
4280
+ value)
4281
+ }
4282
+
6124
4283
  // HELPER FUNCTIONS
6125
4284
  // ================
6126
4285
 
6127
- var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
4286
+ const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
6128
4287
 
6129
4288
  function base64clean (str) {
6130
4289
  // Node takes equal signs as end of the Base64 encoding
@@ -6142,12 +4301,12 @@ function requireBuffer () {
6142
4301
 
6143
4302
  function utf8ToBytes (string, units) {
6144
4303
  units = units || Infinity;
6145
- var codePoint;
6146
- var length = string.length;
6147
- var leadSurrogate = null;
6148
- var bytes = [];
4304
+ let codePoint;
4305
+ const length = string.length;
4306
+ let leadSurrogate = null;
4307
+ const bytes = [];
6149
4308
 
6150
- for (var i = 0; i < length; ++i) {
4309
+ for (let i = 0; i < length; ++i) {
6151
4310
  codePoint = string.charCodeAt(i);
6152
4311
 
6153
4312
  // is surrogate component
@@ -6221,8 +4380,8 @@ function requireBuffer () {
6221
4380
  }
6222
4381
 
6223
4382
  function asciiToBytes (str) {
6224
- var byteArray = [];
6225
- for (var i = 0; i < str.length; ++i) {
4383
+ const byteArray = [];
4384
+ for (let i = 0; i < str.length; ++i) {
6226
4385
  // Node's code seems to be doing this and not & 0x7F..
6227
4386
  byteArray.push(str.charCodeAt(i) & 0xFF);
6228
4387
  }
@@ -6230,9 +4389,9 @@ function requireBuffer () {
6230
4389
  }
6231
4390
 
6232
4391
  function utf16leToBytes (str, units) {
6233
- var c, hi, lo;
6234
- var byteArray = [];
6235
- 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) {
6236
4395
  if ((units -= 2) < 0) break
6237
4396
 
6238
4397
  c = str.charCodeAt(i);
@@ -6250,7 +4409,8 @@ function requireBuffer () {
6250
4409
  }
6251
4410
 
6252
4411
  function blitBuffer (src, dst, offset, length) {
6253
- for (var i = 0; i < length; ++i) {
4412
+ let i;
4413
+ for (i = 0; i < length; ++i) {
6254
4414
  if ((i + offset >= dst.length) || (i >= src.length)) break
6255
4415
  dst[i + offset] = src[i];
6256
4416
  }
@@ -6272,23 +4432,34 @@ function requireBuffer () {
6272
4432
 
6273
4433
  // Create lookup table for `toString('hex')`
6274
4434
  // See: https://github.com/feross/buffer/issues/219
6275
- var hexSliceLookupTable = (function () {
6276
- var alphabet = '0123456789abcdef';
6277
- var table = new Array(256);
6278
- for (var i = 0; i < 16; ++i) {
6279
- var i16 = i * 16;
6280
- 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) {
6281
4441
  table[i16 + j] = alphabet[i] + alphabet[j];
6282
4442
  }
6283
4443
  }
6284
4444
  return table
6285
- })();
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
+ }
6286
4455
  } (buffer));
6287
4456
  return buffer;
6288
4457
  }
6289
4458
 
6290
4459
  var bufferExports = requireBuffer();
6291
4460
 
4461
+ var dist = {};
4462
+
6292
4463
  var Codecs = {};
6293
4464
 
6294
4465
  var Frames = {};
@@ -11071,7 +9242,7 @@ function requireDist () {
11071
9242
 
11072
9243
  var distExports = requireDist();
11073
9244
 
11074
- var version = "1.45.0";
9245
+ var version = "1.46.0";
11075
9246
  var PACKAGE = {
11076
9247
  version: version};
11077
9248
 
@@ -11142,6 +9313,16 @@ class DataStream extends BaseObserver {
11142
9313
  * @returns a Data payload or Null if the stream closed.
11143
9314
  */
11144
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
11145
9326
  if (this.closed) {
11146
9327
  return null;
11147
9328
  }
@@ -11181,7 +9362,7 @@ class DataStream extends BaseObserver {
11181
9362
  }
11182
9363
  const promise = (this.processingPromise = this._processQueue());
11183
9364
  promise.finally(() => {
11184
- return (this.processingPromise = null);
9365
+ this.processingPromise = null;
11185
9366
  });
11186
9367
  return promise;
11187
9368
  }
@@ -11213,7 +9394,6 @@ class DataStream extends BaseObserver {
11213
9394
  this.notifyDataAdded = null;
11214
9395
  }
11215
9396
  if (this.dataQueue.length > 0) {
11216
- // Next tick
11217
9397
  setTimeout(() => this.processQueue());
11218
9398
  }
11219
9399
  }
@@ -11593,7 +9773,7 @@ class AbstractRemote {
11593
9773
  else {
11594
9774
  contents = JSON.stringify(js);
11595
9775
  }
11596
- return bufferExports$1.Buffer.from(contents);
9776
+ return bufferExports.Buffer.from(contents);
11597
9777
  }
11598
9778
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
11599
9779
  const request = await this.buildRequest(path);
@@ -11833,7 +10013,11 @@ class AbstractRemote {
11833
10013
  };
11834
10014
  const stream = new DataStream({
11835
10015
  logger: this.logger,
11836
- mapLine: mapLine
10016
+ mapLine: mapLine,
10017
+ pressure: {
10018
+ highWaterMark: 20,
10019
+ lowWaterMark: 10
10020
+ }
11837
10021
  });
11838
10022
  abortSignal?.addEventListener('abort', () => {
11839
10023
  closeReader();
@@ -11841,42 +10025,47 @@ class AbstractRemote {
11841
10025
  });
11842
10026
  const decoder = this.createTextDecoder();
11843
10027
  let buffer = '';
11844
- const l = stream.registerListener({
11845
- lowWater: async () => {
11846
- 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();
11847
10038
  return;
11848
10039
  }
11849
- try {
11850
- let didCompleteLine = false;
11851
- while (!didCompleteLine) {
11852
- const { done, value } = await reader.read();
11853
- if (done) {
11854
- const remaining = buffer.trim();
11855
- if (remaining.length != 0) {
11856
- stream.enqueueData(remaining);
11857
- }
11858
- stream.close();
11859
- await closeReader();
11860
- return;
11861
- }
11862
- const data = decoder.decode(value, { stream: true });
11863
- buffer += data;
11864
- const lines = buffer.split('\n');
11865
- for (var i = 0; i < lines.length - 1; i++) {
11866
- var l = lines[i].trim();
11867
- if (l.length > 0) {
11868
- stream.enqueueData(l);
11869
- didCompleteLine = true;
11870
- }
11871
- }
11872
- 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);
11873
10047
  }
11874
10048
  }
11875
- catch (ex) {
11876
- stream.close();
11877
- 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
+ });
11878
10064
  }
11879
- },
10065
+ }
10066
+ };
10067
+ consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
10068
+ const l = stream.registerListener({
11880
10069
  closed: () => {
11881
10070
  closeReader();
11882
10071
  l?.();
@@ -11955,18 +10144,17 @@ var SyncClientImplementation;
11955
10144
  *
11956
10145
  * This is the default option.
11957
10146
  *
11958
- * @deprecated Don't use {@link SyncClientImplementation.JAVASCRIPT} directly. Instead, use
11959
- * {@link DEFAULT_SYNC_CLIENT_IMPLEMENTATION} or omit the option. The explicit choice to use
11960
- * 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.
11961
10150
  */
11962
10151
  SyncClientImplementation["JAVASCRIPT"] = "js";
11963
10152
  /**
11964
10153
  * This implementation offloads the sync line decoding and handling into the PowerSync
11965
10154
  * core extension.
11966
10155
  *
11967
- * @experimental
11968
- * While this implementation is more performant than {@link SyncClientImplementation.JAVASCRIPT},
11969
- * 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.
11970
10158
  *
11971
10159
  * ## Compatibility warning
11972
10160
  *
@@ -11984,13 +10172,9 @@ var SyncClientImplementation;
11984
10172
  SyncClientImplementation["RUST"] = "rust";
11985
10173
  })(SyncClientImplementation || (SyncClientImplementation = {}));
11986
10174
  /**
11987
- * The default {@link SyncClientImplementation} to use.
11988
- *
11989
- * Please use this field instead of {@link SyncClientImplementation.JAVASCRIPT} directly. A future version
11990
- * of the PowerSync SDK will enable {@link SyncClientImplementation.RUST} by default and remove the JavaScript
11991
- * option.
10175
+ * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
11992
10176
  */
11993
- const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.JAVASCRIPT;
10177
+ const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
11994
10178
  const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
11995
10179
  const DEFAULT_RETRY_DELAY_MS = 5000;
11996
10180
  const DEFAULT_STREAMING_SYNC_OPTIONS = {
@@ -12400,6 +10584,9 @@ The next upload iteration will be delayed.`);
12400
10584
  if (rawTables != null && rawTables.length) {
12401
10585
  this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
12402
10586
  }
10587
+ if (this.activeStreams.length) {
10588
+ this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
10589
+ }
12403
10590
  this.logger.debug('Streaming sync iteration started');
12404
10591
  this.options.adapter.startSession();
12405
10592
  let [req, bucketMap] = await this.collectLocalBucketState();
@@ -12915,6 +11102,27 @@ The next upload iteration will be delayed.`);
12915
11102
  }
12916
11103
  }
12917
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
+
12918
11126
  /**
12919
11127
  * SQLite operations to track changes for with {@link TriggerManager}
12920
11128
  * @experimental
@@ -12926,9 +11134,20 @@ var DiffTriggerOperation;
12926
11134
  DiffTriggerOperation["DELETE"] = "DELETE";
12927
11135
  })(DiffTriggerOperation || (DiffTriggerOperation = {}));
12928
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
+ */
12929
11145
  class TriggerManagerImpl {
12930
11146
  options;
12931
11147
  schema;
11148
+ defaultConfig;
11149
+ cleanupTimeout;
11150
+ isDisposed;
12932
11151
  constructor(options) {
12933
11152
  this.options = options;
12934
11153
  this.schema = options.schema;
@@ -12937,6 +11156,33 @@ class TriggerManagerImpl {
12937
11156
  this.schema = schema;
12938
11157
  }
12939
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);
12940
11186
  }
12941
11187
  get db() {
12942
11188
  return this.options.db;
@@ -12954,13 +11200,95 @@ class TriggerManagerImpl {
12954
11200
  await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);
12955
11201
  }
12956
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
+ }
12957
11276
  async createDiffTrigger(options) {
12958
11277
  await this.db.waitForReady();
12959
- 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;
12960
11281
  const operations = Object.keys(when);
12961
11282
  if (operations.length == 0) {
12962
11283
  throw new Error('At least one WHEN operation must be specified for the trigger.');
12963
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' : '';
12964
11292
  const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));
12965
11293
  /**
12966
11294
  * Allow specifying the View name as the source.
@@ -12974,6 +11302,7 @@ class TriggerManagerImpl {
12974
11302
  const internalSource = sourceDefinition.internalName;
12975
11303
  const triggerIds = [];
12976
11304
  const id = await this.getUUID();
11305
+ const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;
12977
11306
  /**
12978
11307
  * We default to replicating all columns if no columns array is provided.
12979
11308
  */
@@ -13006,26 +11335,27 @@ class TriggerManagerImpl {
13006
11335
  return this.db.writeLock(async (tx) => {
13007
11336
  await this.removeTriggers(tx, triggerIds);
13008
11337
  await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
11338
+ await releaseStorageClaim?.();
13009
11339
  });
13010
11340
  };
13011
11341
  const setup = async (tx) => {
13012
11342
  // Allow user code to execute in this lock context before the trigger is created.
13013
11343
  await hooks?.beforeCreate?.(tx);
13014
11344
  await tx.execute(/* sql */ `
13015
- CREATE TEMP TABLE ${destination} (
11345
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
13016
11346
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
13017
11347
  id TEXT,
13018
11348
  operation TEXT,
13019
11349
  timestamp TEXT,
13020
11350
  value TEXT,
13021
11351
  previous_value TEXT
13022
- );
11352
+ )
13023
11353
  `);
13024
11354
  if (operations.includes(DiffTriggerOperation.INSERT)) {
13025
- const insertTriggerId = `ps_temp_trigger_insert_${id}`;
11355
+ const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);
13026
11356
  triggerIds.push(insertTriggerId);
13027
11357
  await tx.execute(/* sql */ `
13028
- 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
13029
11359
  INSERT INTO
13030
11360
  ${destination} (id, operation, timestamp, value)
13031
11361
  VALUES
@@ -13036,14 +11366,14 @@ class TriggerManagerImpl {
13036
11366
  ${jsonFragment('NEW')}
13037
11367
  );
13038
11368
 
13039
- END;
11369
+ END
13040
11370
  `);
13041
11371
  }
13042
11372
  if (operations.includes(DiffTriggerOperation.UPDATE)) {
13043
- const updateTriggerId = `ps_temp_trigger_update_${id}`;
11373
+ const updateTriggerId = this.generateTriggerName(DiffTriggerOperation.UPDATE, destination, id);
13044
11374
  triggerIds.push(updateTriggerId);
13045
11375
  await tx.execute(/* sql */ `
13046
- CREATE TEMP TRIGGER ${updateTriggerId} AFTER
11376
+ CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER
13047
11377
  UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN
13048
11378
  INSERT INTO
13049
11379
  ${destination} (id, operation, timestamp, value, previous_value)
@@ -13060,11 +11390,11 @@ class TriggerManagerImpl {
13060
11390
  `);
13061
11391
  }
13062
11392
  if (operations.includes(DiffTriggerOperation.DELETE)) {
13063
- const deleteTriggerId = `ps_temp_trigger_delete_${id}`;
11393
+ const deleteTriggerId = this.generateTriggerName(DiffTriggerOperation.DELETE, destination, id);
13064
11394
  triggerIds.push(deleteTriggerId);
13065
11395
  // Create delete trigger for basic JSON
13066
11396
  await tx.execute(/* sql */ `
13067
- 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
13068
11398
  INSERT INTO
13069
11399
  ${destination} (id, operation, timestamp, value)
13070
11400
  VALUES
@@ -13108,7 +11438,7 @@ class TriggerManagerImpl {
13108
11438
  // If no array is provided, we use all columns from the source table.
13109
11439
  const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
13110
11440
  const id = await this.getUUID();
13111
- const destination = `ps_temp_track_${source}_${id}`;
11441
+ const destination = `__ps_temp_track_${source}_${id}`;
13112
11442
  // register an onChange before the trigger is created
13113
11443
  const abortController = new AbortController();
13114
11444
  const abortOnChange = () => abortController.abort();
@@ -13263,6 +11593,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13263
11593
  * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
13264
11594
  */
13265
11595
  triggers;
11596
+ triggersImpl;
13266
11597
  logger;
13267
11598
  constructor(options) {
13268
11599
  super();
@@ -13326,9 +11657,10 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13326
11657
  logger: this.logger
13327
11658
  });
13328
11659
  this._isReadyPromise = this.initialize();
13329
- this.triggers = new TriggerManagerImpl({
11660
+ this.triggers = this.triggersImpl = new TriggerManagerImpl({
13330
11661
  db: this,
13331
- schema: this.schema
11662
+ schema: this.schema,
11663
+ ...this.generateTriggerManagerConfig()
13332
11664
  });
13333
11665
  }
13334
11666
  /**
@@ -13354,6 +11686,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13354
11686
  get connecting() {
13355
11687
  return this.currentStatus?.connecting || false;
13356
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
+ }
13357
11698
  /**
13358
11699
  * @returns A promise which will resolve once initialization is completed.
13359
11700
  */
@@ -13414,14 +11755,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13414
11755
  async initialize() {
13415
11756
  await this._initialize();
13416
11757
  await this.bucketStorageAdapter.init();
13417
- await this._loadVersion();
11758
+ await this.loadVersion();
13418
11759
  await this.updateSchema(this.options.schema);
13419
11760
  await this.resolveOfflineSyncStatus();
13420
11761
  await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
11762
+ await this.triggersImpl.cleanupResources();
13421
11763
  this.ready = true;
13422
11764
  this.iterateListeners((cb) => cb.initialized?.());
13423
11765
  }
13424
- async _loadVersion() {
11766
+ async loadVersion() {
13425
11767
  try {
13426
11768
  const { version } = await this.database.get('SELECT powersync_rs_version() as version');
13427
11769
  this.sdkVersion = version;
@@ -13537,7 +11879,6 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13537
11879
  await this.disconnect();
13538
11880
  await this.waitForReady();
13539
11881
  const { clearLocal } = options;
13540
- // TODO DB name, verify this is necessary with extension
13541
11882
  await this.database.writeTransaction(async (tx) => {
13542
11883
  await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
13543
11884
  });
@@ -13569,6 +11910,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
13569
11910
  if (this.closed) {
13570
11911
  return;
13571
11912
  }
11913
+ this.triggersImpl.dispose();
13572
11914
  await this.iterateAsyncListeners(async (cb) => cb.closing?.());
13573
11915
  const { disconnect } = options;
13574
11916
  if (disconnect) {
@@ -15135,5 +13477,5 @@ const parseQuery = (query, parameters) => {
15135
13477
  return { sqlStatement, parameters: parameters };
15136
13478
  };
15137
13479
 
15138
- 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, 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 };
15139
13481
  //# sourceMappingURL=bundle.mjs.map