@powersync/common 1.38.0 → 1.39.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.
package/dist/index.d.cts CHANGED
@@ -357,6 +357,7 @@ interface Checkpoint {
357
357
  last_op_id: OpId;
358
358
  buckets: BucketChecksum[];
359
359
  write_checkpoint?: string;
360
+ streams?: any[];
360
361
  }
361
362
  interface BucketState {
362
363
  bucket: string;
@@ -390,6 +391,12 @@ interface BucketChecksum {
390
391
  * Count of operations - informational only.
391
392
  */
392
393
  count?: number;
394
+ /**
395
+ * The JavaScript client does not use this field, which is why it's defined to be `any`. We rely on the structure of
396
+ * this interface to pass custom `BucketChecksum`s to the Rust client in unit tests, which so all fields need to be
397
+ * present.
398
+ */
399
+ subscriptions?: any;
393
400
  }
394
401
  declare enum PSInternalTable {
395
402
  DATA = "ps_data",
@@ -404,7 +411,8 @@ declare enum PowerSyncControlCommand {
404
411
  STOP = "stop",
405
412
  START = "start",
406
413
  NOTIFY_TOKEN_REFRESHED = "refreshed_token",
407
- NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload"
414
+ NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload",
415
+ UPDATE_SUBSCRIPTIONS = "update_subscriptions"
408
416
  }
409
417
  interface BucketStorageListener extends BaseListener {
410
418
  crudUpdate: () => void;
@@ -440,73 +448,6 @@ interface BucketStorageAdapter extends BaseObserverInterface<BucketStorageListen
440
448
  control(op: PowerSyncControlCommand, payload: string | Uint8Array | null): Promise<string>;
441
449
  }
442
450
 
443
- type DataStreamOptions<ParsedData, SourceData> = {
444
- mapLine?: (line: SourceData) => ParsedData;
445
- /**
446
- * Close the stream if any consumer throws an error
447
- */
448
- closeOnError?: boolean;
449
- pressure?: {
450
- highWaterMark?: number;
451
- lowWaterMark?: number;
452
- };
453
- logger?: ILogger;
454
- };
455
- type DataStreamCallback<Data extends any = any> = (data: Data) => Promise<void>;
456
- interface DataStreamListener<Data extends any = any> extends BaseListener {
457
- data: (data: Data) => Promise<void>;
458
- closed: () => void;
459
- error: (error: Error) => void;
460
- highWater: () => Promise<void>;
461
- lowWater: () => Promise<void>;
462
- }
463
- declare const DEFAULT_PRESSURE_LIMITS: {
464
- highWater: number;
465
- lowWater: number;
466
- };
467
- /**
468
- * A very basic implementation of a data stream with backpressure support which does not use
469
- * native JS streams or async iterators.
470
- * This is handy for environments such as React Native which need polyfills for the above.
471
- */
472
- declare class DataStream<ParsedData, SourceData = any> extends BaseObserver<DataStreamListener<ParsedData>> {
473
- protected options?: DataStreamOptions<ParsedData, SourceData> | undefined;
474
- dataQueue: SourceData[];
475
- protected isClosed: boolean;
476
- protected processingPromise: Promise<void> | null;
477
- protected notifyDataAdded: (() => void) | null;
478
- protected logger: ILogger;
479
- protected mapLine: (line: SourceData) => ParsedData;
480
- constructor(options?: DataStreamOptions<ParsedData, SourceData> | undefined);
481
- get highWatermark(): number;
482
- get lowWatermark(): number;
483
- get closed(): boolean;
484
- close(): Promise<void>;
485
- /**
486
- * Enqueues data for the consumers to read
487
- */
488
- enqueueData(data: SourceData): void;
489
- /**
490
- * Reads data once from the data stream
491
- * @returns a Data payload or Null if the stream closed.
492
- */
493
- read(): Promise<ParsedData | null>;
494
- /**
495
- * Executes a callback for each data item in the stream
496
- */
497
- forEach(callback: DataStreamCallback<ParsedData>): () => void;
498
- protected processQueue(): Promise<void> | undefined;
499
- protected hasDataReader(): boolean;
500
- protected _processQueue(): Promise<void>;
501
- protected iterateAsyncErrored(cb: (l: Partial<DataStreamListener<ParsedData>>) => Promise<void>): Promise<void>;
502
- }
503
-
504
- interface PowerSyncCredentials {
505
- endpoint: string;
506
- token: string;
507
- expiresAt?: Date;
508
- }
509
-
510
451
  /**
511
452
  * For sync2.json
512
453
  */
@@ -643,6 +584,94 @@ interface CrudResponse {
643
584
  checkpoint?: OpId;
644
585
  }
645
586
 
587
+ interface CoreStreamSubscription {
588
+ progress: {
589
+ total: number;
590
+ downloaded: number;
591
+ };
592
+ name: string;
593
+ parameters: any;
594
+ priority: number | null;
595
+ active: boolean;
596
+ is_default: boolean;
597
+ has_explicit_subscription: boolean;
598
+ expires_at: number | null;
599
+ last_synced_at: number | null;
600
+ }
601
+ interface BucketProgress {
602
+ priority: number;
603
+ at_last: number;
604
+ since_last: number;
605
+ target_count: number;
606
+ }
607
+
608
+ type DataStreamOptions<ParsedData, SourceData> = {
609
+ mapLine?: (line: SourceData) => ParsedData;
610
+ /**
611
+ * Close the stream if any consumer throws an error
612
+ */
613
+ closeOnError?: boolean;
614
+ pressure?: {
615
+ highWaterMark?: number;
616
+ lowWaterMark?: number;
617
+ };
618
+ logger?: ILogger;
619
+ };
620
+ type DataStreamCallback<Data extends any = any> = (data: Data) => Promise<void>;
621
+ interface DataStreamListener<Data extends any = any> extends BaseListener {
622
+ data: (data: Data) => Promise<void>;
623
+ closed: () => void;
624
+ error: (error: Error) => void;
625
+ highWater: () => Promise<void>;
626
+ lowWater: () => Promise<void>;
627
+ }
628
+ declare const DEFAULT_PRESSURE_LIMITS: {
629
+ highWater: number;
630
+ lowWater: number;
631
+ };
632
+ /**
633
+ * A very basic implementation of a data stream with backpressure support which does not use
634
+ * native JS streams or async iterators.
635
+ * This is handy for environments such as React Native which need polyfills for the above.
636
+ */
637
+ declare class DataStream<ParsedData, SourceData = any> extends BaseObserver<DataStreamListener<ParsedData>> {
638
+ protected options?: DataStreamOptions<ParsedData, SourceData> | undefined;
639
+ dataQueue: SourceData[];
640
+ protected isClosed: boolean;
641
+ protected processingPromise: Promise<void> | null;
642
+ protected notifyDataAdded: (() => void) | null;
643
+ protected logger: ILogger;
644
+ protected mapLine: (line: SourceData) => ParsedData;
645
+ constructor(options?: DataStreamOptions<ParsedData, SourceData> | undefined);
646
+ get highWatermark(): number;
647
+ get lowWatermark(): number;
648
+ get closed(): boolean;
649
+ close(): Promise<void>;
650
+ /**
651
+ * Enqueues data for the consumers to read
652
+ */
653
+ enqueueData(data: SourceData): void;
654
+ /**
655
+ * Reads data once from the data stream
656
+ * @returns a Data payload or Null if the stream closed.
657
+ */
658
+ read(): Promise<ParsedData | null>;
659
+ /**
660
+ * Executes a callback for each data item in the stream
661
+ */
662
+ forEach(callback: DataStreamCallback<ParsedData>): () => void;
663
+ protected processQueue(): Promise<void> | undefined;
664
+ protected hasDataReader(): boolean;
665
+ protected _processQueue(): Promise<void>;
666
+ protected iterateAsyncErrored(cb: (l: Partial<DataStreamListener<ParsedData>>) => Promise<void>): Promise<void>;
667
+ }
668
+
669
+ interface PowerSyncCredentials {
670
+ endpoint: string;
671
+ token: string;
672
+ expiresAt?: Date;
673
+ }
674
+
646
675
  type BSONImplementation = typeof BSON;
647
676
  type RemoteConnector = {
648
677
  fetchCredentials: () => Promise<PowerSyncCredentials | null>;
@@ -831,8 +860,9 @@ interface LockOptions<T> {
831
860
  type: LockType;
832
861
  signal?: AbortSignal;
833
862
  }
834
- interface AbstractStreamingSyncImplementationOptions extends AdditionalConnectionOptions {
863
+ interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
835
864
  adapter: BucketStorageAdapter;
865
+ subscriptions: SubscribedStream[];
836
866
  uploadCrud: () => Promise<void>;
837
867
  /**
838
868
  * An identifier for which PowerSync DB this sync implementation is
@@ -884,6 +914,12 @@ interface BaseConnectionOptions {
884
914
  * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
885
915
  */
886
916
  params?: Record<string, StreamingSyncRequestParameterType>;
917
+ /**
918
+ * Whether to include streams that have `auto_subscribe: true` in their definition.
919
+ *
920
+ * This defaults to `true`.
921
+ */
922
+ includeDefaultStreams?: boolean;
887
923
  /**
888
924
  * The serialized schema - mainly used to forward information about raw tables to the sync client.
889
925
  */
@@ -904,7 +940,9 @@ interface AdditionalConnectionOptions {
904
940
  crudUploadThrottleMs?: number;
905
941
  }
906
942
  /** @internal */
907
- type RequiredAdditionalConnectionOptions = Required<AdditionalConnectionOptions>;
943
+ interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
944
+ subscriptions: SubscribedStream[];
945
+ }
908
946
  interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
909
947
  /**
910
948
  * Connects to the sync service
@@ -924,6 +962,7 @@ interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyn
924
962
  waitForReady(): Promise<void>;
925
963
  waitForStatus(status: SyncStatusOptions): Promise<void>;
926
964
  waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
965
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
927
966
  }
928
967
  declare const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
929
968
  declare const DEFAULT_RETRY_DELAY_MS = 5000;
@@ -933,6 +972,10 @@ declare const DEFAULT_STREAMING_SYNC_OPTIONS: {
933
972
  };
934
973
  type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
935
974
  declare const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions;
975
+ type SubscribedStream = {
976
+ name: string;
977
+ params: Record<string, any> | null;
978
+ };
936
979
  declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
937
980
  protected _lastSyncedAt: Date | null;
938
981
  protected options: AbstractStreamingSyncImplementationOptions;
@@ -941,8 +984,10 @@ declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<
941
984
  protected crudUpdateListener?: () => void;
942
985
  protected streamingSyncPromise?: Promise<void>;
943
986
  protected logger: ILogger;
987
+ private activeStreams;
944
988
  private isUploadingCrud;
945
989
  private notifyCompletedUploads?;
990
+ private handleActiveStreamsChange?;
946
991
  syncStatus: SyncStatus;
947
992
  triggerCrudUpload: () => void;
948
993
  constructor(options: AbstractStreamingSyncImplementationOptions);
@@ -979,20 +1024,17 @@ declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<
979
1024
  * @returns Whether the database is now using the new, fixed subkey format.
980
1025
  */
981
1026
  private requireKeyFormat;
982
- protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void>;
1027
+ protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<RustIterationResult | null>;
983
1028
  private legacyStreamingSyncIteration;
984
1029
  private rustSyncIteration;
985
1030
  private updateSyncStatusForStartingCheckpoint;
986
1031
  private applyCheckpoint;
987
1032
  protected updateSyncStatus(options: SyncStatusOptions): void;
988
1033
  private delayRetry;
1034
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
989
1035
  }
990
-
991
- interface BucketProgress {
992
- priority: number;
993
- at_last: number;
994
- since_last: number;
995
- target_count: number;
1036
+ interface RustIterationResult {
1037
+ immediateRestart: boolean;
996
1038
  }
997
1039
 
998
1040
  /** @internal */
@@ -1059,6 +1101,105 @@ declare class SyncProgress implements ProgressWithOperations {
1059
1101
  untilPriority(priority: number): ProgressWithOperations;
1060
1102
  }
1061
1103
 
1104
+ /**
1105
+ * A description of a sync stream, consisting of its {@link name} and the {@link parameters} used when subscribing.
1106
+ */
1107
+ interface SyncStreamDescription {
1108
+ /**
1109
+ * The name of the stream as it appears in the stream definition for the PowerSync service.
1110
+ */
1111
+ name: string;
1112
+ /**
1113
+ * The parameters used to subscribe to the stream, if any.
1114
+ *
1115
+ * The same stream can be subscribed to multiple times with different parameters.
1116
+ */
1117
+ parameters: Record<string, any> | null;
1118
+ }
1119
+ /**
1120
+ * Information about a subscribed sync stream.
1121
+ *
1122
+ * This includes the {@link SyncStreamDescription}, along with information about the current sync status.
1123
+ */
1124
+ interface SyncSubscriptionDescription extends SyncStreamDescription {
1125
+ active: boolean;
1126
+ /**
1127
+ * Whether this stream subscription is included by default, regardless of whether the stream has explicitly been
1128
+ * subscribed to or not.
1129
+ *
1130
+ * It's possible for both {@link isDefault} and {@link hasExplicitSubscription} to be true at the same time - this
1131
+ * happens when a default stream was subscribed explicitly.
1132
+ */
1133
+ isDefault: boolean;
1134
+ /**
1135
+ * Whether this stream has been subscribed to explicitly.
1136
+ *
1137
+ * It's possible for both {@link isDefault} and {@link hasExplicitSubscription} to be true at the same time - this
1138
+ * happens when a default stream was subscribed explicitly.
1139
+ */
1140
+ hasExplicitSubscription: boolean;
1141
+ /**
1142
+ * For sync streams that have a time-to-live, the current time at which the stream would expire if not subscribed to
1143
+ * again.
1144
+ */
1145
+ expiresAt: Date | null;
1146
+ /**
1147
+ * Whether this stream subscription has been synced at least once.
1148
+ */
1149
+ hasSynced: boolean;
1150
+ /**
1151
+ * If {@link hasSynced} is true, the last time data from this stream has been synced.
1152
+ */
1153
+ lastSyncedAt: Date | null;
1154
+ }
1155
+ interface SyncStreamSubscribeOptions {
1156
+ /**
1157
+ * A "time to live" for this stream subscription, in seconds.
1158
+ *
1159
+ * The TTL control when a stream gets evicted after not having an active {@link SyncStreamSubscription} object
1160
+ * attached to it.
1161
+ */
1162
+ ttl?: number;
1163
+ /**
1164
+ * A priority to assign to this subscription. This overrides the default priority that may have been set on streams.
1165
+ *
1166
+ * For details on priorities, see [priotized sync](https://docs.powersync.com/usage/use-case-examples/prioritized-sync).
1167
+ */
1168
+ priority?: 0 | 1 | 2 | 3;
1169
+ }
1170
+ /**
1171
+ * A handle to a {@link SyncStreamDescription} that allows subscribing to the stream.
1172
+ *
1173
+ * To obtain an instance of {@link SyncStream}, call {@link AbstractPowerSyncDatabase.syncStream}.
1174
+ */
1175
+ interface SyncStream extends SyncStreamDescription {
1176
+ /**
1177
+ * Adds a subscription to this stream, requesting it to be included when connecting to the sync service.
1178
+ *
1179
+ * You should keep a reference to the returned {@link SyncStreamSubscription} object along as you need data for that
1180
+ * stream. As soon as {@link SyncStreamSubscription.unsubscribe} is called for all subscriptions on this stream
1181
+ * (including subscriptions created on other tabs), the {@link SyncStreamSubscribeOptions.ttl} starts ticking and will
1182
+ * eventually evict the stream (unless {@link subscribe} is called again).
1183
+ */
1184
+ subscribe(options?: SyncStreamSubscribeOptions): Promise<SyncStreamSubscription>;
1185
+ /**
1186
+ * Clears all subscriptions attached to this stream and resets the TTL for the stream.
1187
+ *
1188
+ * This is a potentially dangerous operations, as it interferes with other stream subscriptions.
1189
+ */
1190
+ unsubscribeAll(): Promise<void>;
1191
+ }
1192
+ interface SyncStreamSubscription extends SyncStreamDescription {
1193
+ /**
1194
+ * A promise that resolves once data from in this sync stream has been synced and applied.
1195
+ */
1196
+ waitForFirstSync(abort?: AbortSignal): Promise<void>;
1197
+ /**
1198
+ * Removes this stream subscription.
1199
+ */
1200
+ unsubscribe(): void;
1201
+ }
1202
+
1062
1203
  type SyncDataFlowStatus = Partial<{
1063
1204
  downloading: boolean;
1064
1205
  uploading: boolean;
@@ -1079,6 +1220,7 @@ type SyncDataFlowStatus = Partial<{
1079
1220
  * Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1080
1221
  */
1081
1222
  downloadProgress: InternalProgressInformation | null;
1223
+ internalStreamSubscriptions: CoreStreamSubscription[] | null;
1082
1224
  }>;
1083
1225
  interface SyncPriorityStatus {
1084
1226
  priority: number;
@@ -1158,7 +1300,23 @@ declare class SyncStatus {
1158
1300
  * Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1159
1301
  */
1160
1302
  downloadProgress: InternalProgressInformation | null;
1303
+ internalStreamSubscriptions: CoreStreamSubscription[] | null;
1161
1304
  }>;
1305
+ /**
1306
+ * All sync streams currently being tracked in teh database.
1307
+ *
1308
+ * This returns null when the database is currently being opened and we don't have reliable information about all
1309
+ * included streams yet.
1310
+ *
1311
+ * @experimental Sync streams are currently in alpha.
1312
+ */
1313
+ get syncStreams(): SyncStreamStatus[] | undefined;
1314
+ /**
1315
+ * If the `stream` appears in {@link syncStreams}, returns the current status for that stream.
1316
+ *
1317
+ * @experimental Sync streams are currently in alpha.
1318
+ */
1319
+ forStream(stream: SyncStreamDescription): SyncStreamStatus | undefined;
1162
1320
  /**
1163
1321
  * Provides sync status information for all bucket priorities, sorted by priority (highest first).
1164
1322
  *
@@ -1216,6 +1374,14 @@ declare class SyncStatus {
1216
1374
  toJSON(): SyncStatusOptions;
1217
1375
  private static comparePriorities;
1218
1376
  }
1377
+ /**
1378
+ * Information about a sync stream subscription.
1379
+ */
1380
+ interface SyncStreamStatus {
1381
+ progress: ProgressWithOperations | null;
1382
+ subscription: SyncSubscriptionDescription;
1383
+ priority: number | null;
1384
+ }
1219
1385
 
1220
1386
  declare class UploadQueueStats {
1221
1387
  /**
@@ -1618,11 +1784,24 @@ interface ConnectionManagerSyncImplementationResult {
1618
1784
  */
1619
1785
  onDispose: () => Promise<void> | void;
1620
1786
  }
1787
+ /**
1788
+ * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
1789
+ *
1790
+ * @internal
1791
+ */
1792
+ interface CreateSyncImplementationOptions extends AdditionalConnectionOptions {
1793
+ subscriptions: SubscribedStream[];
1794
+ }
1795
+ interface InternalSubscriptionAdapter {
1796
+ firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
1797
+ resolveOfflineSyncStatus(): Promise<void>;
1798
+ rustSubscriptionsCommand(payload: any): Promise<void>;
1799
+ }
1621
1800
  /**
1622
1801
  * @internal
1623
1802
  */
1624
1803
  interface ConnectionManagerOptions {
1625
- createSyncImplementation(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<ConnectionManagerSyncImplementationResult>;
1804
+ createSyncImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions): Promise<ConnectionManagerSyncImplementationResult>;
1626
1805
  logger: ILogger;
1627
1806
  }
1628
1807
  type StoredConnectionOptions = {
@@ -1668,6 +1847,12 @@ declare class ConnectionManager extends BaseObserver<ConnectionManagerListener>
1668
1847
  * is disposed.
1669
1848
  */
1670
1849
  protected syncDisposer: (() => Promise<void> | void) | null;
1850
+ /**
1851
+ * Subscriptions managed in this connection manager.
1852
+ *
1853
+ * On the web, these local subscriptions are merged across tabs by a shared worker.
1854
+ */
1855
+ private locallyActiveSubscriptions;
1671
1856
  constructor(options: ConnectionManagerOptions);
1672
1857
  get logger(): ILogger;
1673
1858
  close(): Promise<void>;
@@ -1681,6 +1866,15 @@ declare class ConnectionManager extends BaseObserver<ConnectionManagerListener>
1681
1866
  disconnect(): Promise<void>;
1682
1867
  protected disconnectInternal(): Promise<void>;
1683
1868
  protected performDisconnect(): Promise<void>;
1869
+ stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream;
1870
+ /**
1871
+ * @internal exposed for testing
1872
+ */
1873
+ get activeStreams(): {
1874
+ name: string;
1875
+ params: Record<string, any> | null;
1876
+ }[];
1877
+ private subscriptionsMayHaveChanged;
1684
1878
  }
1685
1879
 
1686
1880
  /**
@@ -1815,12 +2009,14 @@ declare enum WatchedQueryListenerEvent {
1815
2009
  ON_DATA = "onData",
1816
2010
  ON_ERROR = "onError",
1817
2011
  ON_STATE_CHANGE = "onStateChange",
2012
+ SETTINGS_WILL_UPDATE = "settingsWillUpdate",
1818
2013
  CLOSED = "closed"
1819
2014
  }
1820
2015
  interface WatchedQueryListener<Data> extends BaseListener {
1821
2016
  [WatchedQueryListenerEvent.ON_DATA]?: (data: Data) => void | Promise<void>;
1822
2017
  [WatchedQueryListenerEvent.ON_ERROR]?: (error: Error) => void | Promise<void>;
1823
2018
  [WatchedQueryListenerEvent.ON_STATE_CHANGE]?: (state: WatchedQueryState<Data>) => void | Promise<void>;
2019
+ [WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?: () => void;
1824
2020
  [WatchedQueryListenerEvent.CLOSED]?: () => void | Promise<void>;
1825
2021
  }
1826
2022
  declare const DEFAULT_WATCH_THROTTLE_MS = 30;
@@ -1886,6 +2082,7 @@ declare abstract class AbstractQueryProcessor<Data = unknown[], Settings extends
1886
2082
  constructor(options: AbstractQueryProcessorOptions<Data, Settings>);
1887
2083
  protected constructInitialState(): WatchedQueryState<Data>;
1888
2084
  protected get reportFetching(): boolean;
2085
+ protected updateSettingsInternal(settings: Settings, signal: AbortSignal): Promise<void>;
1889
2086
  /**
1890
2087
  * Updates the underlying query.
1891
2088
  */
@@ -1899,7 +2096,7 @@ declare abstract class AbstractQueryProcessor<Data = unknown[], Settings extends
1899
2096
  /**
1900
2097
  * Configures base DB listeners and links the query to listeners.
1901
2098
  */
1902
- protected init(): Promise<void>;
2099
+ protected init(signal: AbortSignal): Promise<void>;
1903
2100
  close(): Promise<void>;
1904
2101
  /**
1905
2102
  * Runs a callback and reports errors to the error listeners.
@@ -2549,7 +2746,7 @@ interface TriggerManager {
2549
2746
  * },
2550
2747
  * onChange: async (context) => {
2551
2748
  * // Fetches the todo records that were inserted during this diff
2552
- * const newTodos = await context.getAll<Database['todos']>(`
2749
+ * const newTodos = await context.withDiff<Database['todos']>(`
2553
2750
  * SELECT
2554
2751
  * todos.*
2555
2752
  * FROM
@@ -2700,6 +2897,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2700
2897
  protected bucketStorageAdapter: BucketStorageAdapter;
2701
2898
  protected _isReadyPromise: Promise<void>;
2702
2899
  protected connectionManager: ConnectionManager;
2900
+ private subscriptions;
2703
2901
  get syncStreamImplementation(): StreamingSyncImplementation | null;
2704
2902
  protected _schema: Schema;
2705
2903
  private _database;
@@ -2735,7 +2933,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2735
2933
  * Opens the DBAdapter given open options using a default open factory
2736
2934
  */
2737
2935
  protected abstract openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
2738
- protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
2936
+ protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
2739
2937
  protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
2740
2938
  /**
2741
2939
  * @returns A promise which will resolve once initialization is completed.
@@ -2754,6 +2952,10 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2754
2952
  signal?: AbortSignal;
2755
2953
  priority?: number;
2756
2954
  }): Promise<void>;
2955
+ /**
2956
+ * Waits for the first sync status for which the `status` callback returns a truthy value.
2957
+ */
2958
+ waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void>;
2757
2959
  /**
2758
2960
  * Allows for extended implementations to execute custom initialization
2759
2961
  * logic as part of the total init process
@@ -2765,7 +2967,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2765
2967
  */
2766
2968
  protected initialize(): Promise<void>;
2767
2969
  private _loadVersion;
2768
- protected updateHasSynced(): Promise<void>;
2970
+ protected resolveOfflineSyncStatus(): Promise<void>;
2769
2971
  /**
2770
2972
  * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
2771
2973
  *
@@ -2777,7 +2979,7 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2777
2979
  * While initializing is automatic, this helps to catch and report initialization errors.
2778
2980
  */
2779
2981
  init(): Promise<void>;
2780
- resolvedConnectionOptions(options?: PowerSyncConnectionOptions): RequiredAdditionalConnectionOptions;
2982
+ protected resolvedConnectionOptions(options: CreateSyncImplementationOptions): CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions;
2781
2983
  /**
2782
2984
  * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.
2783
2985
  * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.
@@ -2807,6 +3009,15 @@ declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncD
2807
3009
  * To preserve data in local-only tables, set clearLocal to false.
2808
3010
  */
2809
3011
  disconnectAndClear(options?: DisconnectAndClearOptions): Promise<void>;
3012
+ /**
3013
+ * Create a sync stream to query its status or to subscribe to it.
3014
+ *
3015
+ * @param name The name of the stream to subscribe to.
3016
+ * @param params Optional parameters for the stream subscription.
3017
+ * @returns A {@link SyncStream} instance that can be subscribed to.
3018
+ * @experimental Sync streams are currently in alpha.
3019
+ */
3020
+ syncStream(name: string, params?: Record<string, any>): SyncStream;
2810
3021
  /**
2811
3022
  * Close the database, releasing resources.
2812
3023
  *
@@ -3373,4 +3584,4 @@ interface ParsedQuery {
3373
3584
  declare const parseQuery: <T>(query: string | CompilableQuery<T>, parameters: any[]) => ParsedQuery;
3374
3585
 
3375
3586
  export { AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, BaseObserver, Column, ColumnType, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_PRESSURE_LIMITS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DataStream, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, Table, TableV2, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
3376
- export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, LinkQueryOptions, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RemoteConnector, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStreamOptions, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState };
3587
+ export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, BSONImplementation, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketChecksum, BucketDescription, BucketOperationProgress, BucketRequest, BucketState, BucketStorageAdapter, BucketStorageListener, Checkpoint, ChecksumCache, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ContinueCheckpointRequest, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CreateSyncImplementationOptions, CrudRequest, CrudResponse, CrudUploadNotification, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DataStreamCallback, DataStreamListener, DataStreamOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, InternalSubscriptionAdapter, LinkQueryOptions, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, OpTypeJSON, OplogEntryJSON, ParsedQuery, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RemoteConnector, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SavedProgress, SchemaTableType, SocketSyncStreamOptions, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncCheckpoint, StreamingSyncCheckpointComplete, StreamingSyncCheckpointDiff, StreamingSyncCheckpointPartiallyComplete, StreamingSyncDataJSON, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncKeepalive, StreamingSyncLine, StreamingSyncLineOrCrudUploadComplete, StreamingSyncRequest, StreamingSyncRequestParameterType, SubscribedStream, SyncDataBucketJSON, SyncDataFlowStatus, SyncLocalDatabaseResult, SyncNewCheckpointRequest, SyncPriorityStatus, SyncRequest, SyncResponse, SyncStatusOptions, SyncStream, SyncStreamDescription, SyncStreamOptions, SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription, SyncSubscriptionDescription, TableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerRemoveCallback, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState };