@powersync/common 1.51.0 → 1.52.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 (37) hide show
  1. package/dist/bundle.cjs +431 -445
  2. package/dist/bundle.cjs.map +1 -1
  3. package/dist/bundle.mjs +432 -444
  4. package/dist/bundle.mjs.map +1 -1
  5. package/dist/bundle.node.cjs +429 -445
  6. package/dist/bundle.node.cjs.map +1 -1
  7. package/dist/bundle.node.mjs +430 -444
  8. package/dist/bundle.node.mjs.map +1 -1
  9. package/dist/index.d.cts +41 -70
  10. package/lib/client/AbstractPowerSyncDatabase.js +3 -3
  11. package/lib/client/AbstractPowerSyncDatabase.js.map +1 -1
  12. package/lib/client/sync/stream/AbstractRemote.d.ts +29 -8
  13. package/lib/client/sync/stream/AbstractRemote.js +154 -177
  14. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  15. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +1 -0
  16. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +69 -88
  17. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  18. package/lib/index.d.ts +1 -1
  19. package/lib/index.js +0 -1
  20. package/lib/index.js.map +1 -1
  21. package/lib/utils/async.d.ts +0 -9
  22. package/lib/utils/async.js +0 -9
  23. package/lib/utils/async.js.map +1 -1
  24. package/lib/utils/stream_transform.d.ts +39 -0
  25. package/lib/utils/stream_transform.js +206 -0
  26. package/lib/utils/stream_transform.js.map +1 -0
  27. package/package.json +9 -7
  28. package/src/client/AbstractPowerSyncDatabase.ts +3 -3
  29. package/src/client/sync/stream/AbstractRemote.ts +182 -206
  30. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +82 -83
  31. package/src/index.ts +1 -1
  32. package/src/utils/async.ts +0 -11
  33. package/src/utils/stream_transform.ts +252 -0
  34. package/lib/utils/DataStream.d.ts +0 -62
  35. package/lib/utils/DataStream.js +0 -169
  36. package/lib/utils/DataStream.js.map +0 -1
  37. package/src/utils/DataStream.ts +0 -222
@@ -2257,15 +2257,6 @@ class ControlledExecutor {
2257
2257
  }
2258
2258
  }
2259
2259
 
2260
- /**
2261
- * A ponyfill for `Symbol.asyncIterator` that is compatible with the
2262
- * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)
2263
- * we recommend for React Native.
2264
- *
2265
- * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async
2266
- * iterators without requiring them.
2267
- */
2268
- const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
2269
2260
  /**
2270
2261
  * Throttle a function to be called at most once every "wait" milliseconds,
2271
2262
  * on the trailing edge.
@@ -8231,177 +8222,10 @@ function requireDist () {
8231
8222
 
8232
8223
  var distExports = requireDist();
8233
8224
 
8234
- var version = "1.51.0";
8225
+ var version = "1.52.0";
8235
8226
  var PACKAGE = {
8236
8227
  version: version};
8237
8228
 
8238
- const DEFAULT_PRESSURE_LIMITS = {
8239
- highWater: 10,
8240
- lowWater: 0
8241
- };
8242
- /**
8243
- * A very basic implementation of a data stream with backpressure support which does not use
8244
- * native JS streams or async iterators.
8245
- * This is handy for environments such as React Native which need polyfills for the above.
8246
- */
8247
- class DataStream extends BaseObserver {
8248
- options;
8249
- dataQueue;
8250
- isClosed;
8251
- processingPromise;
8252
- notifyDataAdded;
8253
- logger;
8254
- mapLine;
8255
- constructor(options) {
8256
- super();
8257
- this.options = options;
8258
- this.processingPromise = null;
8259
- this.isClosed = false;
8260
- this.dataQueue = [];
8261
- this.mapLine = options?.mapLine ?? ((line) => line);
8262
- this.logger = options?.logger ?? Logger.get('DataStream');
8263
- if (options?.closeOnError) {
8264
- const l = this.registerListener({
8265
- error: (ex) => {
8266
- l?.();
8267
- this.close();
8268
- }
8269
- });
8270
- }
8271
- }
8272
- get highWatermark() {
8273
- return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;
8274
- }
8275
- get lowWatermark() {
8276
- return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;
8277
- }
8278
- get closed() {
8279
- return this.isClosed;
8280
- }
8281
- async close() {
8282
- this.isClosed = true;
8283
- await this.processingPromise;
8284
- this.iterateListeners((l) => l.closed?.());
8285
- // Discard any data in the queue
8286
- this.dataQueue = [];
8287
- this.listeners.clear();
8288
- }
8289
- /**
8290
- * Enqueues data for the consumers to read
8291
- */
8292
- enqueueData(data) {
8293
- if (this.isClosed) {
8294
- throw new Error('Cannot enqueue data into closed stream.');
8295
- }
8296
- this.dataQueue.push(data);
8297
- this.notifyDataAdded?.();
8298
- this.processQueue();
8299
- }
8300
- /**
8301
- * Reads data once from the data stream
8302
- * @returns a Data payload or Null if the stream closed.
8303
- */
8304
- async read() {
8305
- if (this.closed) {
8306
- return null;
8307
- }
8308
- // Wait for any pending processing to complete first.
8309
- // This ensures we register our listener before calling processQueue(),
8310
- // avoiding a race where processQueue() sees no reader and returns early.
8311
- if (this.processingPromise) {
8312
- await this.processingPromise;
8313
- }
8314
- // Re-check after await - stream may have closed while we were waiting
8315
- if (this.closed) {
8316
- return null;
8317
- }
8318
- return new Promise((resolve, reject) => {
8319
- const l = this.registerListener({
8320
- data: async (data) => {
8321
- resolve(data);
8322
- // Remove the listener
8323
- l?.();
8324
- },
8325
- closed: () => {
8326
- resolve(null);
8327
- l?.();
8328
- },
8329
- error: (ex) => {
8330
- reject(ex);
8331
- l?.();
8332
- }
8333
- });
8334
- this.processQueue();
8335
- });
8336
- }
8337
- /**
8338
- * Executes a callback for each data item in the stream
8339
- */
8340
- forEach(callback) {
8341
- if (this.dataQueue.length <= this.lowWatermark) {
8342
- this.iterateAsyncErrored(async (l) => l.lowWater?.());
8343
- }
8344
- return this.registerListener({
8345
- data: callback
8346
- });
8347
- }
8348
- processQueue() {
8349
- if (this.processingPromise) {
8350
- return;
8351
- }
8352
- const promise = (this.processingPromise = this._processQueue());
8353
- promise.finally(() => {
8354
- this.processingPromise = null;
8355
- });
8356
- return promise;
8357
- }
8358
- hasDataReader() {
8359
- return Array.from(this.listeners.values()).some((l) => !!l.data);
8360
- }
8361
- async _processQueue() {
8362
- /**
8363
- * Allow listeners to mutate the queue before processing.
8364
- * This allows for operations such as dropping or compressing data
8365
- * on high water or requesting more data on low water.
8366
- */
8367
- if (this.dataQueue.length >= this.highWatermark) {
8368
- await this.iterateAsyncErrored(async (l) => l.highWater?.());
8369
- }
8370
- if (this.isClosed || !this.hasDataReader()) {
8371
- return;
8372
- }
8373
- if (this.dataQueue.length) {
8374
- const data = this.dataQueue.shift();
8375
- const mapped = this.mapLine(data);
8376
- await this.iterateAsyncErrored(async (l) => l.data?.(mapped));
8377
- }
8378
- if (this.dataQueue.length <= this.lowWatermark) {
8379
- const dataAdded = new Promise((resolve) => {
8380
- this.notifyDataAdded = resolve;
8381
- });
8382
- await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);
8383
- this.notifyDataAdded = null;
8384
- }
8385
- if (this.dataQueue.length > 0) {
8386
- setTimeout(() => this.processQueue());
8387
- }
8388
- }
8389
- async iterateAsyncErrored(cb) {
8390
- // Important: We need to copy the listeners, as calling a listener could result in adding another
8391
- // listener, resulting in infinite loops.
8392
- const listeners = Array.from(this.listeners.values());
8393
- for (let i of listeners) {
8394
- try {
8395
- await cb(i);
8396
- }
8397
- catch (ex) {
8398
- this.logger.error(ex);
8399
- this.iterateListeners((l) => l.error?.(ex));
8400
- }
8401
- }
8402
- }
8403
- }
8404
-
8405
8229
  var WebsocketDuplexConnection = {};
8406
8230
 
8407
8231
  var hasRequiredWebsocketDuplexConnection;
@@ -8564,8 +8388,215 @@ class WebsocketClientTransport {
8564
8388
  }
8565
8389
  }
8566
8390
 
8391
+ const doneResult = { done: true, value: undefined };
8392
+ function valueResult(value) {
8393
+ return { done: false, value };
8394
+ }
8395
+ /**
8396
+ * A variant of {@link Array.map} for async iterators.
8397
+ */
8398
+ function map(source, map) {
8399
+ return {
8400
+ next: async () => {
8401
+ const value = await source.next();
8402
+ if (value.done) {
8403
+ return value;
8404
+ }
8405
+ else {
8406
+ return { value: map(value.value) };
8407
+ }
8408
+ }
8409
+ };
8410
+ }
8411
+ /**
8412
+ * Expands a source async iterator by allowing to inject events asynchronously.
8413
+ *
8414
+ * The resulting iterator will emit all events from its source. Additionally though, events can be injected. These
8415
+ * events are dropped once the main iterator completes, but are otherwise forwarded.
8416
+ *
8417
+ * The iterator completes when its source completes, and it supports backpressure by only calling `next()` on the source
8418
+ * in response to a `next()` call from downstream if no pending injected events can be dispatched.
8419
+ */
8420
+ function injectable(source) {
8421
+ let sourceIsDone = false;
8422
+ let waiter = undefined; // An active, waiting next() call.
8423
+ // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.
8424
+ let pendingSourceEvent = null;
8425
+ let pendingInjectedEvents = [];
8426
+ const consumeWaiter = () => {
8427
+ const pending = waiter;
8428
+ waiter = undefined;
8429
+ return pending;
8430
+ };
8431
+ const fetchFromSource = () => {
8432
+ const resolveWaiter = (propagate) => {
8433
+ const active = consumeWaiter();
8434
+ if (active) {
8435
+ propagate(active);
8436
+ }
8437
+ else {
8438
+ pendingSourceEvent = propagate;
8439
+ }
8440
+ };
8441
+ const nextFromSource = source.next();
8442
+ nextFromSource.then((value) => {
8443
+ sourceIsDone = value.done == true;
8444
+ resolveWaiter((w) => w.resolve(value));
8445
+ }, (error) => {
8446
+ resolveWaiter((w) => w.reject(error));
8447
+ });
8448
+ };
8449
+ return {
8450
+ next: () => {
8451
+ return new Promise((resolve, reject) => {
8452
+ // First priority: Dispatch ready upstream events.
8453
+ if (sourceIsDone) {
8454
+ return resolve(doneResult);
8455
+ }
8456
+ if (pendingSourceEvent) {
8457
+ pendingSourceEvent({ resolve, reject });
8458
+ pendingSourceEvent = null;
8459
+ return;
8460
+ }
8461
+ // Second priority: Dispatch injected events
8462
+ if (pendingInjectedEvents.length) {
8463
+ return resolve(valueResult(pendingInjectedEvents.shift()));
8464
+ }
8465
+ // Nothing pending? Fetch from source
8466
+ waiter = { resolve, reject };
8467
+ return fetchFromSource();
8468
+ });
8469
+ },
8470
+ inject: (event) => {
8471
+ const pending = consumeWaiter();
8472
+ if (pending != null) {
8473
+ pending.resolve(valueResult(event));
8474
+ }
8475
+ else {
8476
+ pendingInjectedEvents.push(event);
8477
+ }
8478
+ }
8479
+ };
8480
+ }
8481
+ /**
8482
+ * Splits a byte stream at line endings, emitting each line as a string.
8483
+ */
8484
+ function extractJsonLines(source, decoder) {
8485
+ let buffer = '';
8486
+ const pendingLines = [];
8487
+ let isFinalEvent = false;
8488
+ return {
8489
+ next: async () => {
8490
+ while (true) {
8491
+ if (isFinalEvent) {
8492
+ return doneResult;
8493
+ }
8494
+ {
8495
+ const first = pendingLines.shift();
8496
+ if (first) {
8497
+ return { done: false, value: first };
8498
+ }
8499
+ }
8500
+ const { done, value } = await source.next();
8501
+ if (done) {
8502
+ const remaining = buffer.trim();
8503
+ if (remaining.length != 0) {
8504
+ isFinalEvent = true;
8505
+ return { done: false, value: remaining };
8506
+ }
8507
+ return doneResult;
8508
+ }
8509
+ const data = decoder.decode(value, { stream: true });
8510
+ buffer += data;
8511
+ const lines = buffer.split('\n');
8512
+ for (let i = 0; i < lines.length - 1; i++) {
8513
+ const l = lines[i].trim();
8514
+ if (l.length > 0) {
8515
+ pendingLines.push(l);
8516
+ }
8517
+ }
8518
+ buffer = lines[lines.length - 1];
8519
+ }
8520
+ }
8521
+ };
8522
+ }
8523
+ /**
8524
+ * Splits a concatenated stream of BSON objects by emitting individual objects.
8525
+ */
8526
+ function extractBsonObjects(source) {
8527
+ // Fully read but not emitted yet.
8528
+ const completedObjects = [];
8529
+ // Whether source has returned { done: true }. We do the same once completed objects have been emitted.
8530
+ let isDone = false;
8531
+ const lengthBuffer = new DataView(new ArrayBuffer(4));
8532
+ let objectBody = null;
8533
+ // If we're parsing the length field, a number between 1 and 4 (inclusive) describing remaining bytes in the header.
8534
+ // If we're consuming a document, the bytes remaining.
8535
+ let remainingLength = 4;
8536
+ return {
8537
+ async next() {
8538
+ while (true) {
8539
+ // Before fetching new data from upstream, return completed objects.
8540
+ if (completedObjects.length) {
8541
+ return valueResult(completedObjects.shift());
8542
+ }
8543
+ if (isDone) {
8544
+ return doneResult;
8545
+ }
8546
+ const upstreamEvent = await source.next();
8547
+ if (upstreamEvent.done) {
8548
+ isDone = true;
8549
+ if (objectBody || remainingLength != 4) {
8550
+ throw new Error('illegal end of stream in BSON object');
8551
+ }
8552
+ return doneResult;
8553
+ }
8554
+ const chunk = upstreamEvent.value;
8555
+ for (let i = 0; i < chunk.length;) {
8556
+ const availableInData = chunk.length - i;
8557
+ if (objectBody) {
8558
+ // We're in the middle of reading a BSON document.
8559
+ const bytesToRead = Math.min(availableInData, remainingLength);
8560
+ const copySource = new Uint8Array(chunk.buffer, chunk.byteOffset + i, bytesToRead);
8561
+ objectBody.set(copySource, objectBody.length - remainingLength);
8562
+ i += bytesToRead;
8563
+ remainingLength -= bytesToRead;
8564
+ if (remainingLength == 0) {
8565
+ completedObjects.push(objectBody);
8566
+ // Prepare to read another document, starting with its length
8567
+ objectBody = null;
8568
+ remainingLength = 4;
8569
+ }
8570
+ }
8571
+ else {
8572
+ // Copy up to 4 bytes into lengthBuffer, depending on how many we still need.
8573
+ const bytesToRead = Math.min(availableInData, remainingLength);
8574
+ for (let j = 0; j < bytesToRead; j++) {
8575
+ lengthBuffer.setUint8(4 - remainingLength + j, chunk[i + j]);
8576
+ }
8577
+ i += bytesToRead;
8578
+ remainingLength -= bytesToRead;
8579
+ if (remainingLength == 0) {
8580
+ // Transition from reading length header to reading document. Subtracting 4 because the length of the
8581
+ // header is included in length.
8582
+ const length = lengthBuffer.getInt32(0, true /* little endian */);
8583
+ remainingLength = length - 4;
8584
+ if (remainingLength < 1) {
8585
+ throw new Error(`invalid length for bson: ${length}`);
8586
+ }
8587
+ objectBody = new Uint8Array(length);
8588
+ new DataView(objectBody.buffer).setInt32(0, length, true);
8589
+ }
8590
+ }
8591
+ }
8592
+ }
8593
+ }
8594
+ };
8595
+ }
8596
+
8567
8597
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
8568
8598
  const POWERSYNC_JS_VERSION = PACKAGE.version;
8599
+ const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
8569
8600
  const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
8570
8601
  // Keep alive message is sent every period
8571
8602
  const KEEP_ALIVE_MS = 20_000;
@@ -8745,13 +8776,14 @@ class AbstractRemote {
8745
8776
  return new WebSocket(url);
8746
8777
  }
8747
8778
  /**
8748
- * Returns a data stream of sync line data.
8779
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
8780
+ *
8781
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
8749
8782
  *
8750
- * @param map Maps received payload frames to the typed event value.
8751
8783
  * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
8752
8784
  * (required for compatibility with older sync services).
8753
8785
  */
8754
- async socketStreamRaw(options, map, bson) {
8786
+ async socketStreamRaw(options, bson) {
8755
8787
  const { path, fetchStrategy = exports.FetchStrategy.Buffered } = options;
8756
8788
  const mimeType = bson == null ? 'application/json' : 'application/bson';
8757
8789
  function toBuffer(js) {
@@ -8766,52 +8798,55 @@ class AbstractRemote {
8766
8798
  }
8767
8799
  const syncQueueRequestSize = fetchStrategy == exports.FetchStrategy.Buffered ? 10 : 1;
8768
8800
  const request = await this.buildRequest(path);
8801
+ const url = this.options.socketUrlTransformer(request.url);
8769
8802
  // Add the user agent in the setup payload - we can't set custom
8770
8803
  // headers with websockets on web. The browser userAgent is however added
8771
8804
  // automatically as a header.
8772
8805
  const userAgent = this.getUserAgent();
8773
- const stream = new DataStream({
8774
- logger: this.logger,
8775
- pressure: {
8776
- lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
8777
- },
8778
- mapLine: map
8779
- });
8806
+ // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
8807
+ // to abort the connection.
8808
+ let pendingSocket = null;
8809
+ let keepAliveTimeout;
8810
+ let rsocket = null;
8811
+ let queue = null;
8812
+ let didClose = false;
8813
+ const abortRequest = () => {
8814
+ if (didClose) {
8815
+ return;
8816
+ }
8817
+ didClose = true;
8818
+ clearTimeout(keepAliveTimeout);
8819
+ if (pendingSocket) {
8820
+ pendingSocket.close();
8821
+ }
8822
+ if (rsocket) {
8823
+ rsocket.close();
8824
+ }
8825
+ if (queue) {
8826
+ queue.stop();
8827
+ }
8828
+ };
8780
8829
  // Handle upstream abort
8781
- if (options.abortSignal?.aborted) {
8830
+ if (options.abortSignal.aborted) {
8782
8831
  throw new AbortOperation('Connection request aborted');
8783
8832
  }
8784
8833
  else {
8785
- options.abortSignal?.addEventListener('abort', () => {
8786
- stream.close();
8787
- }, { once: true });
8834
+ options.abortSignal.addEventListener('abort', abortRequest);
8788
8835
  }
8789
- let keepAliveTimeout;
8790
8836
  const resetTimeout = () => {
8791
8837
  clearTimeout(keepAliveTimeout);
8792
8838
  keepAliveTimeout = setTimeout(() => {
8793
8839
  this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
8794
- stream.close();
8840
+ abortRequest();
8795
8841
  }, SOCKET_TIMEOUT_MS);
8796
8842
  };
8797
8843
  resetTimeout();
8798
- // Typescript complains about this being `never` if it's not assigned here.
8799
- // This is assigned in `wsCreator`.
8800
- let disposeSocketConnectionTimeout = () => { };
8801
- const url = this.options.socketUrlTransformer(request.url);
8802
8844
  const connector = new distExports.RSocketConnector({
8803
8845
  transport: new WebsocketClientTransport({
8804
8846
  url,
8805
8847
  wsCreator: (url) => {
8806
- const socket = this.createSocket(url);
8807
- disposeSocketConnectionTimeout = stream.registerListener({
8808
- closed: () => {
8809
- // Allow closing the underlying WebSocket if the stream was closed before the
8810
- // RSocket connect completed. This should effectively abort the request.
8811
- socket.close();
8812
- }
8813
- });
8814
- socket.addEventListener('message', (event) => {
8848
+ const socket = (pendingSocket = this.createSocket(url));
8849
+ socket.addEventListener('message', () => {
8815
8850
  resetTimeout();
8816
8851
  });
8817
8852
  return socket;
@@ -8831,43 +8866,40 @@ class AbstractRemote {
8831
8866
  }
8832
8867
  }
8833
8868
  });
8834
- let rsocket;
8835
8869
  try {
8836
8870
  rsocket = await connector.connect();
8837
8871
  // The connection is established, we no longer need to monitor the initial timeout
8838
- disposeSocketConnectionTimeout();
8872
+ pendingSocket = null;
8839
8873
  }
8840
8874
  catch (ex) {
8841
8875
  this.logger.error(`Failed to connect WebSocket`, ex);
8842
- clearTimeout(keepAliveTimeout);
8843
- if (!stream.closed) {
8844
- await stream.close();
8845
- }
8876
+ abortRequest();
8846
8877
  throw ex;
8847
8878
  }
8848
8879
  resetTimeout();
8849
- let socketIsClosed = false;
8850
- const closeSocket = () => {
8851
- clearTimeout(keepAliveTimeout);
8852
- if (socketIsClosed) {
8853
- return;
8854
- }
8855
- socketIsClosed = true;
8856
- rsocket.close();
8857
- };
8858
8880
  // Helps to prevent double close scenarios
8859
- rsocket.onClose(() => (socketIsClosed = true));
8860
- // We initially request this amount and expect these to arrive eventually
8861
- let pendingEventsCount = syncQueueRequestSize;
8862
- const disposeClosedListener = stream.registerListener({
8863
- closed: () => {
8864
- closeSocket();
8865
- disposeClosedListener();
8866
- }
8867
- });
8868
- const socket = await new Promise((resolve, reject) => {
8881
+ rsocket.onClose(() => (rsocket = null));
8882
+ return await new Promise((resolve, reject) => {
8869
8883
  let connectionEstablished = false;
8870
- const res = rsocket.requestStream({
8884
+ let pendingEventsCount = syncQueueRequestSize;
8885
+ let paused = false;
8886
+ let res = null;
8887
+ function requestMore() {
8888
+ const delta = syncQueueRequestSize - pendingEventsCount;
8889
+ if (!paused && delta > 0) {
8890
+ res?.request(delta);
8891
+ pendingEventsCount = syncQueueRequestSize;
8892
+ }
8893
+ }
8894
+ const events = new eventIterator.EventIterator((q) => {
8895
+ queue = q;
8896
+ q.on('highWater', () => (paused = true));
8897
+ q.on('lowWater', () => {
8898
+ paused = false;
8899
+ requestMore();
8900
+ });
8901
+ }, { highWaterMark: SYNC_QUEUE_REQUEST_HIGH_WATER, lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER })[Symbol.asyncIterator]();
8902
+ res = rsocket.requestStream({
8871
8903
  data: toBuffer(options.data),
8872
8904
  metadata: toBuffer({
8873
8905
  path
@@ -8892,7 +8924,7 @@ class AbstractRemote {
8892
8924
  }
8893
8925
  // RSocket will close the RSocket stream automatically
8894
8926
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
8895
- stream.close();
8927
+ abortRequest();
8896
8928
  // Handles cases where the connection failed e.g. auth error or connection error
8897
8929
  if (!connectionEstablished) {
8898
8930
  reject(e);
@@ -8902,41 +8934,40 @@ class AbstractRemote {
8902
8934
  // The connection is active
8903
8935
  if (!connectionEstablished) {
8904
8936
  connectionEstablished = true;
8905
- resolve(res);
8937
+ resolve(events);
8906
8938
  }
8907
8939
  const { data } = payload;
8940
+ if (data) {
8941
+ queue.push(data);
8942
+ }
8908
8943
  // Less events are now pending
8909
8944
  pendingEventsCount--;
8910
- if (!data) {
8911
- return;
8912
- }
8913
- stream.enqueueData(data);
8945
+ // Request another event (unless the downstream consumer is paused).
8946
+ requestMore();
8914
8947
  },
8915
8948
  onComplete: () => {
8916
- stream.close();
8949
+ abortRequest(); // this will also emit a done event
8917
8950
  },
8918
8951
  onExtension: () => { }
8919
8952
  });
8920
8953
  });
8921
- const l = stream.registerListener({
8922
- lowWater: async () => {
8923
- // Request to fill up the queue
8924
- const required = syncQueueRequestSize - pendingEventsCount;
8925
- if (required > 0) {
8926
- socket.request(syncQueueRequestSize - pendingEventsCount);
8927
- pendingEventsCount = syncQueueRequestSize;
8928
- }
8929
- },
8930
- closed: () => {
8931
- l();
8932
- }
8933
- });
8934
- return stream;
8935
8954
  }
8936
8955
  /**
8937
- * Connects to the sync/stream http endpoint, mapping and emitting each received string line.
8956
+ * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
8957
+ * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
8958
+ *
8959
+ * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
8960
+ */
8961
+ get supportsStreamingBinaryResponses() {
8962
+ return true;
8963
+ }
8964
+ /**
8965
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
8966
+ * async iterator of byte blobs.
8967
+ *
8968
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
8938
8969
  */
8939
- async postStreamRaw(options, mapLine) {
8970
+ async fetchStreamRaw(options) {
8940
8971
  const { data, path, headers, abortSignal } = options;
8941
8972
  const request = await this.buildRequest(path);
8942
8973
  /**
@@ -8948,119 +8979,94 @@ class AbstractRemote {
8948
8979
  * Aborting the active fetch request while it is being consumed seems to throw
8949
8980
  * an unhandled exception on the window level.
8950
8981
  */
8951
- if (abortSignal?.aborted) {
8952
- throw new AbortOperation('Abort request received before making postStreamRaw request');
8982
+ if (abortSignal.aborted) {
8983
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
8953
8984
  }
8954
8985
  const controller = new AbortController();
8955
- let requestResolved = false;
8956
- abortSignal?.addEventListener('abort', () => {
8957
- if (!requestResolved) {
8986
+ let reader = null;
8987
+ abortSignal.addEventListener('abort', () => {
8988
+ const reason = abortSignal.reason ??
8989
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
8990
+ if (reader == null) {
8958
8991
  // Only abort via the abort controller if the request has not resolved yet
8959
- controller.abort(abortSignal.reason ??
8960
- new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
8992
+ controller.abort(reason);
8993
+ }
8994
+ else {
8995
+ reader.cancel(reason).catch(() => {
8996
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
8997
+ // ignore it here.
8998
+ });
8961
8999
  }
8962
9000
  });
8963
- const res = await this.fetch(request.url, {
8964
- method: 'POST',
8965
- headers: { ...headers, ...request.headers },
8966
- body: JSON.stringify(data),
8967
- signal: controller.signal,
8968
- cache: 'no-store',
8969
- ...(this.options.fetchOptions ?? {}),
8970
- ...options.fetchOptions
8971
- }).catch((ex) => {
9001
+ let res;
9002
+ let responseIsBson = false;
9003
+ try {
9004
+ const ndJson = 'application/x-ndjson';
9005
+ const bson = 'application/vnd.powersync.bson-stream';
9006
+ res = await this.fetch(request.url, {
9007
+ method: 'POST',
9008
+ headers: {
9009
+ ...headers,
9010
+ ...request.headers,
9011
+ accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
9012
+ },
9013
+ body: JSON.stringify(data),
9014
+ signal: controller.signal,
9015
+ cache: 'no-store',
9016
+ ...(this.options.fetchOptions ?? {}),
9017
+ ...options.fetchOptions
9018
+ });
9019
+ if (!res.ok || !res.body) {
9020
+ const text = await res.text();
9021
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
9022
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
9023
+ error.status = res.status;
9024
+ throw error;
9025
+ }
9026
+ const contentType = res.headers.get('content-type');
9027
+ responseIsBson = contentType == bson;
9028
+ }
9029
+ catch (ex) {
8972
9030
  if (ex.name == 'AbortError') {
8973
9031
  throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
8974
9032
  }
8975
9033
  throw ex;
8976
- });
8977
- if (!res) {
8978
- throw new Error('Fetch request was aborted');
8979
- }
8980
- requestResolved = true;
8981
- if (!res.ok || !res.body) {
8982
- const text = await res.text();
8983
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
8984
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
8985
- error.status = res.status;
8986
- throw error;
8987
9034
  }
8988
- // Create a new stream splitting the response at line endings while also handling cancellations
8989
- // by closing the reader.
8990
- const reader = res.body.getReader();
8991
- let readerReleased = false;
8992
- // This will close the network request and read stream
8993
- const closeReader = async () => {
8994
- try {
8995
- readerReleased = true;
8996
- await reader.cancel();
8997
- }
8998
- catch (ex) {
8999
- // an error will throw if the reader hasn't been used yet
9000
- }
9001
- reader.releaseLock();
9002
- };
9003
- const stream = new DataStream({
9004
- logger: this.logger,
9005
- mapLine: mapLine,
9006
- pressure: {
9007
- highWaterMark: 20,
9008
- lowWaterMark: 10
9009
- }
9010
- });
9011
- abortSignal?.addEventListener('abort', () => {
9012
- closeReader();
9013
- stream.close();
9014
- });
9015
- const decoder = this.createTextDecoder();
9016
- let buffer = '';
9017
- const consumeStream = async () => {
9018
- while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
9019
- const { done, value } = await reader.read();
9020
- if (done) {
9021
- const remaining = buffer.trim();
9022
- if (remaining.length != 0) {
9023
- stream.enqueueData(remaining);
9024
- }
9025
- stream.close();
9026
- await closeReader();
9027
- return;
9035
+ reader = res.body.getReader();
9036
+ const stream = {
9037
+ next: async () => {
9038
+ if (controller.signal.aborted) {
9039
+ return doneResult;
9028
9040
  }
9029
- const data = decoder.decode(value, { stream: true });
9030
- buffer += data;
9031
- const lines = buffer.split('\n');
9032
- for (var i = 0; i < lines.length - 1; i++) {
9033
- var l = lines[i].trim();
9034
- if (l.length > 0) {
9035
- stream.enqueueData(l);
9036
- }
9041
+ try {
9042
+ return await reader.read();
9037
9043
  }
9038
- buffer = lines[lines.length - 1];
9039
- // Implement backpressure by waiting for the low water mark to be reached
9040
- if (stream.dataQueue.length > stream.highWatermark) {
9041
- await new Promise((resolve) => {
9042
- const dispose = stream.registerListener({
9043
- lowWater: async () => {
9044
- resolve();
9045
- dispose();
9046
- },
9047
- closed: () => {
9048
- resolve();
9049
- dispose();
9050
- }
9051
- });
9052
- });
9044
+ catch (ex) {
9045
+ if (controller.signal.aborted) {
9046
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
9047
+ // things working as intended, we can return a done event and consider the exception handled.
9048
+ return doneResult;
9049
+ }
9050
+ throw ex;
9053
9051
  }
9054
9052
  }
9055
9053
  };
9056
- consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
9057
- const l = stream.registerListener({
9058
- closed: () => {
9059
- closeReader();
9060
- l?.();
9061
- }
9062
- });
9063
- return stream;
9054
+ return { isBson: responseIsBson, stream };
9055
+ }
9056
+ /**
9057
+ * Posts a `/sync/stream` request.
9058
+ *
9059
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
9060
+ * {@link Uint8Array}s.
9061
+ */
9062
+ async fetchStream(options) {
9063
+ const { isBson, stream } = await this.fetchStreamRaw(options);
9064
+ if (isBson) {
9065
+ return extractBsonObjects(stream);
9066
+ }
9067
+ else {
9068
+ return extractJsonLines(stream, this.createTextDecoder());
9069
+ }
9064
9070
  }
9065
9071
  }
9066
9072
 
@@ -9568,6 +9574,19 @@ The next upload iteration will be delayed.`);
9568
9574
  }
9569
9575
  });
9570
9576
  }
9577
+ async receiveSyncLines(data) {
9578
+ const { options, connection, bson } = data;
9579
+ const remote = this.options.remote;
9580
+ if (connection.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9581
+ return await remote.fetchStream(options);
9582
+ }
9583
+ else {
9584
+ return await this.options.remote.socketStreamRaw({
9585
+ ...options,
9586
+ ...{ fetchStrategy: connection.fetchStrategy }
9587
+ }, bson);
9588
+ }
9589
+ }
9571
9590
  async legacyStreamingSyncIteration(signal, resolvedOptions) {
9572
9591
  const rawTables = resolvedOptions.serializedSchema?.raw_tables;
9573
9592
  if (rawTables != null && rawTables.length) {
@@ -9597,42 +9616,27 @@ The next upload iteration will be delayed.`);
9597
9616
  client_id: clientId
9598
9617
  }
9599
9618
  };
9600
- let stream;
9601
- if (resolvedOptions?.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9602
- stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {
9603
- if (typeof line == 'string') {
9604
- return JSON.parse(line);
9605
- }
9606
- else {
9607
- // Directly enqueued by us
9608
- return line;
9609
- }
9610
- });
9611
- }
9612
- else {
9613
- const bson = await this.options.remote.getBSON();
9614
- stream = await this.options.remote.socketStreamRaw({
9615
- ...syncOptions,
9616
- ...{ fetchStrategy: resolvedOptions.fetchStrategy }
9617
- }, (payload) => {
9618
- if (payload instanceof Uint8Array) {
9619
- return bson.deserialize(payload);
9620
- }
9621
- else {
9622
- // Directly enqueued by us
9623
- return payload;
9624
- }
9625
- }, bson);
9626
- }
9619
+ const bson = await this.options.remote.getBSON();
9620
+ const source = await this.receiveSyncLines({
9621
+ options: syncOptions,
9622
+ connection: resolvedOptions,
9623
+ bson
9624
+ });
9625
+ const stream = injectable(map(source, (line) => {
9626
+ if (typeof line == 'string') {
9627
+ return JSON.parse(line);
9628
+ }
9629
+ else {
9630
+ return bson.deserialize(line);
9631
+ }
9632
+ }));
9627
9633
  this.logger.debug('Stream established. Processing events');
9628
9634
  this.notifyCompletedUploads = () => {
9629
- if (!stream.closed) {
9630
- stream.enqueueData({ crud_upload_completed: null });
9631
- }
9635
+ stream.inject({ crud_upload_completed: null });
9632
9636
  };
9633
- while (!stream.closed) {
9634
- const line = await stream.read();
9635
- if (!line) {
9637
+ while (true) {
9638
+ const { value: line, done } = await stream.next();
9639
+ if (done) {
9636
9640
  // The stream has closed while waiting
9637
9641
  return;
9638
9642
  }
@@ -9811,14 +9815,17 @@ The next upload iteration will be delayed.`);
9811
9815
  const syncImplementation = this;
9812
9816
  const adapter = this.options.adapter;
9813
9817
  const remote = this.options.remote;
9818
+ const controller = new AbortController();
9819
+ const abort = () => {
9820
+ return controller.abort(signal.reason);
9821
+ };
9822
+ signal.addEventListener('abort', abort);
9814
9823
  let receivingLines = null;
9815
9824
  let hadSyncLine = false;
9816
9825
  let hideDisconnectOnRestart = false;
9817
9826
  if (signal.aborted) {
9818
9827
  throw new AbortOperation('Connection request has been aborted');
9819
9828
  }
9820
- const abortController = new AbortController();
9821
- signal.addEventListener('abort', () => abortController.abort());
9822
9829
  // Pending sync lines received from the service, as well as local events that trigger a powersync_control
9823
9830
  // invocation (local events include refreshed tokens and completed uploads).
9824
9831
  // This is a single data stream so that we can handle all control calls from a single place.
@@ -9826,49 +9833,36 @@ The next upload iteration will be delayed.`);
9826
9833
  async function connect(instr) {
9827
9834
  const syncOptions = {
9828
9835
  path: '/sync/stream',
9829
- abortSignal: abortController.signal,
9836
+ abortSignal: controller.signal,
9830
9837
  data: instr.request
9831
9838
  };
9832
- if (resolvedOptions.connectionMethod == exports.SyncStreamConnectionMethod.HTTP) {
9833
- controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {
9834
- if (typeof line == 'string') {
9835
- return {
9836
- command: exports.PowerSyncControlCommand.PROCESS_TEXT_LINE,
9837
- payload: line
9838
- };
9839
- }
9840
- else {
9841
- // Directly enqueued by us
9842
- return line;
9843
- }
9844
- });
9845
- }
9846
- else {
9847
- controlInvocations = await remote.socketStreamRaw({
9848
- ...syncOptions,
9849
- fetchStrategy: resolvedOptions.fetchStrategy
9850
- }, (payload) => {
9851
- if (payload instanceof Uint8Array) {
9852
- return {
9853
- command: exports.PowerSyncControlCommand.PROCESS_BSON_LINE,
9854
- payload: payload
9855
- };
9856
- }
9857
- else {
9858
- // Directly enqueued by us
9859
- return payload;
9860
- }
9861
- });
9862
- }
9839
+ controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
9840
+ options: syncOptions,
9841
+ connection: resolvedOptions
9842
+ }), (line) => {
9843
+ if (typeof line == 'string') {
9844
+ return {
9845
+ command: exports.PowerSyncControlCommand.PROCESS_TEXT_LINE,
9846
+ payload: line
9847
+ };
9848
+ }
9849
+ else {
9850
+ return {
9851
+ command: exports.PowerSyncControlCommand.PROCESS_BSON_LINE,
9852
+ payload: line
9853
+ };
9854
+ }
9855
+ }));
9863
9856
  // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
9864
9857
  // we're already connected here and can report that.
9865
9858
  syncImplementation.updateSyncStatus({ connected: true });
9866
9859
  try {
9867
- while (!controlInvocations.closed) {
9868
- const line = await controlInvocations.read();
9869
- if (line == null) {
9870
- return;
9860
+ while (true) {
9861
+ let event = await controlInvocations.next();
9862
+ if (event.done) {
9863
+ break;
9871
9864
  }
9865
+ const line = event.value;
9872
9866
  await control(line.command, line.payload);
9873
9867
  if (!hadSyncLine) {
9874
9868
  syncImplementation.triggerCrudUpload();
@@ -9877,12 +9871,8 @@ The next upload iteration will be delayed.`);
9877
9871
  }
9878
9872
  }
9879
9873
  finally {
9880
- const activeInstructions = controlInvocations;
9881
- // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is
9882
- // refreshed. That would throw after closing (and we can't handle those events either way), so set this back
9883
- // to null.
9884
- controlInvocations = null;
9885
- await activeInstructions.close();
9874
+ abort();
9875
+ signal.removeEventListener('abort', abort);
9886
9876
  }
9887
9877
  }
9888
9878
  async function stop() {
@@ -9926,14 +9916,14 @@ The next upload iteration will be delayed.`);
9926
9916
  remote.invalidateCredentials();
9927
9917
  // Restart iteration after the credentials have been refreshed.
9928
9918
  remote.fetchCredentials().then((_) => {
9929
- controlInvocations?.enqueueData({ command: exports.PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
9919
+ controlInvocations?.inject({ command: exports.PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
9930
9920
  }, (err) => {
9931
9921
  syncImplementation.logger.warn('Could not prefetch credentials', err);
9932
9922
  });
9933
9923
  }
9934
9924
  }
9935
9925
  else if ('CloseSyncStream' in instruction) {
9936
- abortController.abort();
9926
+ controller.abort();
9937
9927
  hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
9938
9928
  }
9939
9929
  else if ('FlushFileSystem' in instruction) ;
@@ -9962,17 +9952,13 @@ The next upload iteration will be delayed.`);
9962
9952
  }
9963
9953
  await control(exports.PowerSyncControlCommand.START, JSON.stringify(options));
9964
9954
  this.notifyCompletedUploads = () => {
9965
- if (controlInvocations && !controlInvocations?.closed) {
9966
- controlInvocations.enqueueData({ command: exports.PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9967
- }
9955
+ controlInvocations?.inject({ command: exports.PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
9968
9956
  };
9969
9957
  this.handleActiveStreamsChange = () => {
9970
- if (controlInvocations && !controlInvocations?.closed) {
9971
- controlInvocations.enqueueData({
9972
- command: exports.PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
9973
- payload: JSON.stringify(this.activeStreams)
9974
- });
9975
- }
9958
+ controlInvocations?.inject({
9959
+ command: exports.PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
9960
+ payload: JSON.stringify(this.activeStreams)
9961
+ });
9976
9962
  };
9977
9963
  await receivingLines;
9978
9964
  }
@@ -10989,7 +10975,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
10989
10975
  * @returns A transaction of CRUD operations to upload, or null if there are none
10990
10976
  */
10991
10977
  async getNextCrudTransaction() {
10992
- const iterator = this.getCrudTransactions()[symbolAsyncIterator]();
10978
+ const iterator = this.getCrudTransactions()[Symbol.asyncIterator]();
10993
10979
  return (await iterator.next()).value;
10994
10980
  }
10995
10981
  /**
@@ -11025,7 +11011,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
11025
11011
  */
11026
11012
  getCrudTransactions() {
11027
11013
  return {
11028
- [symbolAsyncIterator]: () => {
11014
+ [Symbol.asyncIterator]: () => {
11029
11015
  let lastCrudItemId = -1;
11030
11016
  const sql = `
11031
11017
  WITH RECURSIVE crud_entries AS (
@@ -12194,7 +12180,6 @@ exports.DEFAULT_INDEX_OPTIONS = DEFAULT_INDEX_OPTIONS;
12194
12180
  exports.DEFAULT_LOCK_TIMEOUT_MS = DEFAULT_LOCK_TIMEOUT_MS;
12195
12181
  exports.DEFAULT_POWERSYNC_CLOSE_OPTIONS = DEFAULT_POWERSYNC_CLOSE_OPTIONS;
12196
12182
  exports.DEFAULT_POWERSYNC_DB_OPTIONS = DEFAULT_POWERSYNC_DB_OPTIONS;
12197
- exports.DEFAULT_PRESSURE_LIMITS = DEFAULT_PRESSURE_LIMITS;
12198
12183
  exports.DEFAULT_REMOTE_LOGGER = DEFAULT_REMOTE_LOGGER;
12199
12184
  exports.DEFAULT_REMOTE_OPTIONS = DEFAULT_REMOTE_OPTIONS;
12200
12185
  exports.DEFAULT_RETRY_DELAY_MS = DEFAULT_RETRY_DELAY_MS;
@@ -12205,7 +12190,6 @@ exports.DEFAULT_SYNC_CLIENT_IMPLEMENTATION = DEFAULT_SYNC_CLIENT_IMPLEMENTATION;
12205
12190
  exports.DEFAULT_TABLE_OPTIONS = DEFAULT_TABLE_OPTIONS;
12206
12191
  exports.DEFAULT_WATCH_QUERY_OPTIONS = DEFAULT_WATCH_QUERY_OPTIONS;
12207
12192
  exports.DEFAULT_WATCH_THROTTLE_MS = DEFAULT_WATCH_THROTTLE_MS;
12208
- exports.DataStream = DataStream;
12209
12193
  exports.DifferentialQueryProcessor = DifferentialQueryProcessor;
12210
12194
  exports.EMPTY_DIFFERENTIAL = EMPTY_DIFFERENTIAL;
12211
12195
  exports.FalsyComparator = FalsyComparator;