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