@powersync/common 0.0.0-dev-20260504100448 → 0.0.0-dev-20260630141119

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 (263) hide show
  1. package/lib/attachments/AttachmentContext.d.ts +9 -8
  2. package/lib/attachments/AttachmentContext.js +8 -3
  3. package/lib/attachments/AttachmentContext.js.map +1 -1
  4. package/lib/attachments/AttachmentErrorHandler.d.ts +6 -6
  5. package/lib/attachments/AttachmentQueue.d.ts +85 -36
  6. package/lib/attachments/AttachmentQueue.js +19 -21
  7. package/lib/attachments/AttachmentQueue.js.map +1 -1
  8. package/lib/attachments/AttachmentService.d.ts +3 -3
  9. package/lib/attachments/AttachmentService.js +4 -3
  10. package/lib/attachments/AttachmentService.js.map +1 -1
  11. package/lib/attachments/LocalStorageAdapter.d.ts +14 -8
  12. package/lib/attachments/LocalStorageAdapter.js +3 -0
  13. package/lib/attachments/LocalStorageAdapter.js.map +1 -1
  14. package/lib/attachments/RemoteStorageAdapter.d.ts +4 -4
  15. package/lib/attachments/Schema.d.ts +14 -6
  16. package/lib/attachments/Schema.js +8 -3
  17. package/lib/attachments/Schema.js.map +1 -1
  18. package/lib/attachments/SyncingService.d.ts +2 -2
  19. package/lib/attachments/SyncingService.js +8 -3
  20. package/lib/attachments/SyncingService.js.map +1 -1
  21. package/lib/attachments/WatchedAttachmentItem.d.ts +3 -1
  22. package/lib/client/{AbstractPowerSyncDatabase.d.ts → CommonPowerSyncDatabase.d.ts} +112 -238
  23. package/lib/client/CommonPowerSyncDatabase.js +2 -0
  24. package/lib/client/CommonPowerSyncDatabase.js.map +1 -0
  25. package/lib/client/Query.d.ts +9 -0
  26. package/lib/client/SQLOpenFactory.d.ts +44 -10
  27. package/lib/client/SQLOpenFactory.js +1 -19
  28. package/lib/client/SQLOpenFactory.js.map +1 -1
  29. package/lib/client/compilableQueryWatch.d.ts +8 -2
  30. package/lib/client/compilableQueryWatch.js +4 -2
  31. package/lib/client/compilableQueryWatch.js.map +1 -1
  32. package/lib/client/connection/PowerSyncBackendConnector.d.ts +6 -3
  33. package/lib/client/connection/PowerSyncCredentials.d.ts +3 -0
  34. package/lib/client/runOnSchemaChange.d.ts +5 -2
  35. package/lib/client/runOnSchemaChange.js +3 -0
  36. package/lib/client/runOnSchemaChange.js.map +1 -1
  37. package/lib/client/sync/bucket/CrudBatch.d.ts +2 -0
  38. package/lib/client/sync/bucket/CrudBatch.js +2 -0
  39. package/lib/client/sync/bucket/CrudBatch.js.map +1 -1
  40. package/lib/client/sync/bucket/CrudEntry.d.ts +9 -31
  41. package/lib/client/sync/bucket/CrudEntry.js +2 -97
  42. package/lib/client/sync/bucket/CrudEntry.js.map +1 -1
  43. package/lib/client/sync/bucket/CrudTransaction.d.ts +3 -0
  44. package/lib/client/sync/bucket/CrudTransaction.js +3 -0
  45. package/lib/client/sync/bucket/CrudTransaction.js.map +1 -1
  46. package/lib/client/sync/options.d.ts +65 -0
  47. package/lib/client/sync/options.js +25 -0
  48. package/lib/client/sync/options.js.map +1 -0
  49. package/lib/client/sync/stream/JsonValue.d.ts +3 -0
  50. package/lib/client/sync/sync-streams.d.ts +23 -8
  51. package/lib/client/triggers/TriggerManager.d.ts +28 -56
  52. package/lib/client/triggers/TriggerManager.js +2 -1
  53. package/lib/client/triggers/TriggerManager.js.map +1 -1
  54. package/lib/client/triggers/sanitizeSQL.d.ts +4 -0
  55. package/lib/client/triggers/sanitizeSQL.js +4 -0
  56. package/lib/client/triggers/sanitizeSQL.js.map +1 -1
  57. package/lib/client/watched/GetAllQuery.d.ts +7 -3
  58. package/lib/client/watched/GetAllQuery.js +3 -1
  59. package/lib/client/watched/GetAllQuery.js.map +1 -1
  60. package/lib/client/watched/WatchedQuery.d.ts +20 -6
  61. package/lib/client/watched/WatchedQuery.js +3 -5
  62. package/lib/client/watched/WatchedQuery.js.map +1 -1
  63. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +15 -45
  64. package/lib/client/watched/processors/DifferentialQueryProcessor.js +1 -172
  65. package/lib/client/watched/processors/DifferentialQueryProcessor.js.map +1 -1
  66. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +4 -22
  67. package/lib/client/watched/processors/OnChangeQueryProcessor.js +1 -82
  68. package/lib/client/watched/processors/OnChangeQueryProcessor.js.map +1 -1
  69. package/lib/client/watched/processors/comparators.d.ts +8 -0
  70. package/lib/client/watched/processors/comparators.js +4 -0
  71. package/lib/client/watched/processors/comparators.js.map +1 -1
  72. package/lib/db/DBAdapter.d.ts +90 -113
  73. package/lib/db/DBAdapter.js +70 -89
  74. package/lib/db/DBAdapter.js.map +1 -1
  75. package/lib/db/QueryResult.d.ts +104 -0
  76. package/lib/db/QueryResult.js +96 -0
  77. package/lib/db/QueryResult.js.map +1 -0
  78. package/lib/db/crud/SyncProgress.d.ts +7 -14
  79. package/lib/db/crud/SyncProgress.js +1 -60
  80. package/lib/db/crud/SyncProgress.js.map +1 -1
  81. package/lib/db/crud/SyncStatus.d.ts +54 -91
  82. package/lib/db/crud/SyncStatus.js +1 -245
  83. package/lib/db/crud/SyncStatus.js.map +1 -1
  84. package/lib/db/crud/UploadQueueStatus.d.ts +3 -0
  85. package/lib/db/crud/UploadQueueStatus.js +3 -0
  86. package/lib/db/crud/UploadQueueStatus.js.map +1 -1
  87. package/lib/db/schema/Column.d.ts +22 -1
  88. package/lib/db/schema/Column.js +10 -4
  89. package/lib/db/schema/Column.js.map +1 -1
  90. package/lib/db/schema/Index.d.ts +8 -3
  91. package/lib/db/schema/Index.js +4 -1
  92. package/lib/db/schema/Index.js.map +1 -1
  93. package/lib/db/schema/IndexedColumn.d.ts +8 -3
  94. package/lib/db/schema/IndexedColumn.js +4 -1
  95. package/lib/db/schema/IndexedColumn.js.map +1 -1
  96. package/lib/db/schema/RawTable.d.ts +7 -1
  97. package/lib/db/schema/Schema.d.ts +10 -29
  98. package/lib/db/schema/Schema.js +3 -1
  99. package/lib/db/schema/Schema.js.map +1 -1
  100. package/lib/db/schema/Table.d.ts +69 -91
  101. package/lib/db/schema/Table.js +88 -87
  102. package/lib/db/schema/Table.js.map +1 -1
  103. package/lib/index.d.ts +6 -22
  104. package/lib/index.js +5 -22
  105. package/lib/index.js.map +1 -1
  106. package/lib/types/types.d.ts +6 -0
  107. package/lib/utils/BaseObserver.d.ts +12 -0
  108. package/lib/utils/BaseObserver.js +3 -0
  109. package/lib/utils/BaseObserver.js.map +1 -1
  110. package/lib/utils/Logger.d.ts +60 -22
  111. package/lib/utils/Logger.js +38 -30
  112. package/lib/utils/Logger.js.map +1 -1
  113. package/lib/utils/MetaBaseObserver.d.ts +11 -11
  114. package/lib/utils/MetaBaseObserver.js +1 -50
  115. package/lib/utils/MetaBaseObserver.js.map +1 -1
  116. package/lib/utils/mutex.d.ts +3 -45
  117. package/lib/utils/mutex.js +1 -153
  118. package/lib/utils/mutex.js.map +1 -1
  119. package/package.json +9 -46
  120. package/src/attachments/AttachmentContext.ts +15 -13
  121. package/src/attachments/AttachmentErrorHandler.ts +6 -6
  122. package/src/attachments/AttachmentQueue.ts +99 -42
  123. package/src/attachments/AttachmentService.ts +7 -6
  124. package/src/attachments/LocalStorageAdapter.ts +14 -8
  125. package/src/attachments/README.md +2 -0
  126. package/src/attachments/RemoteStorageAdapter.ts +4 -4
  127. package/src/attachments/Schema.ts +14 -6
  128. package/src/attachments/SyncingService.ts +10 -6
  129. package/src/attachments/WatchedAttachmentItem.ts +3 -1
  130. package/src/client/CommonPowerSyncDatabase.ts +540 -0
  131. package/src/client/Query.ts +9 -0
  132. package/src/client/SQLOpenFactory.ts +47 -19
  133. package/src/client/compilableQueryWatch.ts +9 -4
  134. package/src/client/connection/PowerSyncBackendConnector.ts +6 -3
  135. package/src/client/connection/PowerSyncCredentials.ts +3 -0
  136. package/src/client/runOnSchemaChange.ts +5 -2
  137. package/src/client/sync/bucket/CrudBatch.ts +2 -0
  138. package/src/client/sync/bucket/CrudEntry.ts +10 -101
  139. package/src/client/sync/bucket/CrudTransaction.ts +3 -0
  140. package/src/client/sync/options.ts +77 -0
  141. package/src/client/sync/stream/JsonValue.ts +3 -0
  142. package/src/client/sync/sync-streams.ts +23 -10
  143. package/src/client/triggers/TriggerManager.ts +29 -59
  144. package/src/client/triggers/sanitizeSQL.ts +5 -0
  145. package/src/client/watched/GetAllQuery.ts +8 -4
  146. package/src/client/watched/WatchedQuery.ts +20 -11
  147. package/src/client/watched/processors/DifferentialQueryProcessor.ts +19 -219
  148. package/src/client/watched/processors/OnChangeQueryProcessor.ts +4 -109
  149. package/src/client/watched/processors/comparators.ts +8 -0
  150. package/src/db/DBAdapter.ts +160 -175
  151. package/src/db/QueryResult.ts +195 -0
  152. package/src/db/crud/SyncProgress.ts +8 -43
  153. package/src/db/crud/SyncStatus.ts +66 -216
  154. package/src/db/crud/UploadQueueStatus.ts +3 -0
  155. package/src/db/schema/Column.ts +22 -5
  156. package/src/db/schema/Index.ts +9 -3
  157. package/src/db/schema/IndexedColumn.ts +9 -3
  158. package/src/db/schema/RawTable.ts +7 -1
  159. package/src/db/schema/Schema.ts +12 -7
  160. package/src/db/schema/Table.ts +130 -180
  161. package/src/index.ts +6 -22
  162. package/src/types/types.ts +6 -0
  163. package/src/utils/BaseObserver.ts +12 -0
  164. package/src/utils/Logger.ts +86 -31
  165. package/src/utils/MetaBaseObserver.ts +14 -60
  166. package/src/utils/mutex.ts +4 -189
  167. package/dist/bundle.cjs +0 -14136
  168. package/dist/bundle.cjs.map +0 -1
  169. package/dist/bundle.mjs +0 -14056
  170. package/dist/bundle.mjs.map +0 -1
  171. package/dist/bundle.node.cjs +0 -11613
  172. package/dist/bundle.node.cjs.map +0 -1
  173. package/dist/bundle.node.mjs +0 -11533
  174. package/dist/bundle.node.mjs.map +0 -1
  175. package/dist/index.d.cts +0 -4052
  176. package/legacy/sync_protocol.d.ts +0 -103
  177. package/lib/client/AbstractPowerSyncDatabase.js +0 -987
  178. package/lib/client/AbstractPowerSyncDatabase.js.map +0 -1
  179. package/lib/client/AbstractPowerSyncOpenFactory.d.ts +0 -22
  180. package/lib/client/AbstractPowerSyncOpenFactory.js +0 -25
  181. package/lib/client/AbstractPowerSyncOpenFactory.js.map +0 -1
  182. package/lib/client/ConnectionManager.d.ts +0 -112
  183. package/lib/client/ConnectionManager.js +0 -294
  184. package/lib/client/ConnectionManager.js.map +0 -1
  185. package/lib/client/CustomQuery.d.ts +0 -22
  186. package/lib/client/CustomQuery.js +0 -43
  187. package/lib/client/CustomQuery.js.map +0 -1
  188. package/lib/client/constants.d.ts +0 -1
  189. package/lib/client/constants.js +0 -2
  190. package/lib/client/constants.js.map +0 -1
  191. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +0 -40
  192. package/lib/client/sync/bucket/BucketStorageAdapter.js +0 -19
  193. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +0 -1
  194. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +0 -34
  195. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -162
  196. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +0 -1
  197. package/lib/client/sync/stream/AbstractRemote.d.ts +0 -151
  198. package/lib/client/sync/stream/AbstractRemote.js +0 -473
  199. package/lib/client/sync/stream/AbstractRemote.js.map +0 -1
  200. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +0 -218
  201. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +0 -663
  202. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +0 -1
  203. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +0 -15
  204. package/lib/client/sync/stream/WebsocketClientTransport.js +0 -61
  205. package/lib/client/sync/stream/WebsocketClientTransport.js.map +0 -1
  206. package/lib/client/sync/stream/core-instruction.d.ts +0 -71
  207. package/lib/client/sync/stream/core-instruction.js +0 -27
  208. package/lib/client/sync/stream/core-instruction.js.map +0 -1
  209. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +0 -6
  210. package/lib/client/triggers/MemoryTriggerClaimManager.js +0 -21
  211. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +0 -1
  212. package/lib/client/triggers/TriggerManagerImpl.d.ts +0 -39
  213. package/lib/client/triggers/TriggerManagerImpl.js +0 -405
  214. package/lib/client/triggers/TriggerManagerImpl.js.map +0 -1
  215. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +0 -68
  216. package/lib/client/watched/processors/AbstractQueryProcessor.js +0 -151
  217. package/lib/client/watched/processors/AbstractQueryProcessor.js.map +0 -1
  218. package/lib/db/ConnectionClosedError.d.ts +0 -10
  219. package/lib/db/ConnectionClosedError.js +0 -21
  220. package/lib/db/ConnectionClosedError.js.map +0 -1
  221. package/lib/db/schema/TableV2.d.ts +0 -9
  222. package/lib/db/schema/TableV2.js +0 -9
  223. package/lib/db/schema/TableV2.js.map +0 -1
  224. package/lib/utils/AbortOperation.d.ts +0 -9
  225. package/lib/utils/AbortOperation.js +0 -19
  226. package/lib/utils/AbortOperation.js.map +0 -1
  227. package/lib/utils/ControlledExecutor.d.ts +0 -25
  228. package/lib/utils/ControlledExecutor.js +0 -51
  229. package/lib/utils/ControlledExecutor.js.map +0 -1
  230. package/lib/utils/async.d.ts +0 -14
  231. package/lib/utils/async.js +0 -46
  232. package/lib/utils/async.js.map +0 -1
  233. package/lib/utils/parseQuery.d.ts +0 -6
  234. package/lib/utils/parseQuery.js +0 -17
  235. package/lib/utils/parseQuery.js.map +0 -1
  236. package/lib/utils/queue.d.ts +0 -16
  237. package/lib/utils/queue.js +0 -42
  238. package/lib/utils/queue.js.map +0 -1
  239. package/lib/utils/stream_transform.d.ts +0 -39
  240. package/lib/utils/stream_transform.js +0 -206
  241. package/lib/utils/stream_transform.js.map +0 -1
  242. package/src/client/AbstractPowerSyncDatabase.ts +0 -1362
  243. package/src/client/AbstractPowerSyncOpenFactory.ts +0 -39
  244. package/src/client/ConnectionManager.ts +0 -402
  245. package/src/client/CustomQuery.ts +0 -56
  246. package/src/client/constants.ts +0 -1
  247. package/src/client/sync/bucket/BucketStorageAdapter.ts +0 -49
  248. package/src/client/sync/bucket/SqliteBucketStorage.ts +0 -199
  249. package/src/client/sync/stream/AbstractRemote.ts +0 -602
  250. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +0 -905
  251. package/src/client/sync/stream/WebsocketClientTransport.ts +0 -80
  252. package/src/client/sync/stream/core-instruction.ts +0 -98
  253. package/src/client/triggers/MemoryTriggerClaimManager.ts +0 -25
  254. package/src/client/triggers/TriggerManagerImpl.ts +0 -496
  255. package/src/client/watched/processors/AbstractQueryProcessor.ts +0 -226
  256. package/src/db/ConnectionClosedError.ts +0 -23
  257. package/src/db/schema/TableV2.ts +0 -9
  258. package/src/utils/AbortOperation.ts +0 -17
  259. package/src/utils/ControlledExecutor.ts +0 -72
  260. package/src/utils/async.ts +0 -50
  261. package/src/utils/parseQuery.ts +0 -25
  262. package/src/utils/queue.ts +0 -48
  263. package/src/utils/stream_transform.ts +0 -252
@@ -1,905 +0,0 @@
1
- import Logger, { ILogger } from 'js-logger';
2
-
3
- import { SyncStatus, SyncStatusOptions } from '../../../db/crud/SyncStatus.js';
4
- import { AbortOperation } from '../../../utils/AbortOperation.js';
5
- import { BaseListener, BaseObserver, BaseObserverInterface, Disposable } from '../../../utils/BaseObserver.js';
6
- import { throttleLeadingTrailing } from '../../../utils/async.js';
7
- import { BucketStorageAdapter, PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
8
- import { CrudEntry } from '../bucket/CrudEntry.js';
9
- import { AbstractRemote, FetchStrategy, SyncStreamOptions } from './AbstractRemote.js';
10
- import { EstablishSyncStream, Instruction, coreStatusToJs } from './core-instruction.js';
11
- import { injectable, InjectableIterator, map, SimpleAsyncIterator } from '../../../utils/stream_transform.js';
12
- import { StreamingSyncRequestParameterType } from './JsonValue.js';
13
-
14
- export enum LockType {
15
- CRUD = 'crud',
16
- SYNC = 'sync'
17
- }
18
-
19
- export enum SyncStreamConnectionMethod {
20
- HTTP = 'http',
21
- WEB_SOCKET = 'web-socket'
22
- }
23
-
24
- export enum SyncClientImplementation {
25
- /**
26
- * This implementation offloads the sync line decoding and handling into the PowerSync
27
- * core extension.
28
- *
29
- * This is the only option, as an older JavaScript client implementation has been removed from the SDK.
30
- *
31
- * ## Compatibility warning
32
- *
33
- * The Rust sync client stores sync data in a format that is slightly different than the one used
34
- * by the old JavaScript client. When adopting the {@link RUST} client on existing databases, the PowerSync SDK will
35
- * migrate the format automatically.
36
- *
37
- * SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
38
- * implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
39
- * possible anymore. Problematic SDK versions have been released before 2025-06-09.
40
- */
41
- RUST = 'rust'
42
- }
43
-
44
- /**
45
- * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
46
- */
47
- export const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
48
-
49
- /**
50
- * Abstract Lock to be implemented by various JS environments
51
- */
52
- export interface LockOptions<T> {
53
- callback: () => Promise<T>;
54
- type: LockType;
55
- signal?: AbortSignal;
56
- }
57
-
58
- export interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
59
- adapter: BucketStorageAdapter;
60
- subscriptions: SubscribedStream[];
61
- uploadCrud: () => Promise<void>;
62
- /**
63
- * An identifier for which PowerSync DB this sync implementation is
64
- * linked to. Most commonly DB name, but not restricted to DB name.
65
- */
66
- identifier?: string;
67
- logger?: ILogger;
68
- remote: AbstractRemote;
69
- }
70
-
71
- export interface StreamingSyncImplementationListener extends BaseListener {
72
- /**
73
- * Triggered whenever a status update has been attempted to be made or
74
- * refreshed.
75
- */
76
- statusUpdated?: ((statusUpdate: SyncStatusOptions) => void) | undefined;
77
- /**
78
- * Triggers whenever the status' members have changed in value
79
- */
80
- statusChanged?: ((status: SyncStatus) => void) | undefined;
81
- }
82
-
83
- /**
84
- * Configurable options to be used when connecting to the PowerSync
85
- * backend instance.
86
- */
87
- export type PowerSyncConnectionOptions = Omit<InternalConnectionOptions, 'serializedSchema'>;
88
-
89
- export interface InternalConnectionOptions extends BaseConnectionOptions, AdditionalConnectionOptions {}
90
-
91
- /** @internal */
92
- export interface BaseConnectionOptions {
93
- /**
94
- * A set of metadata to be included in service logs.
95
- */
96
- appMetadata?: Record<string, string>;
97
-
98
- /**
99
- * @deprecated The Rust sync client is used unconditionally, so this option can't be configured.
100
- */
101
- clientImplementation?: SyncClientImplementation;
102
-
103
- /**
104
- * The connection method to use when streaming updates from
105
- * the PowerSync backend instance.
106
- * Defaults to a HTTP streaming connection.
107
- */
108
- connectionMethod?: SyncStreamConnectionMethod;
109
-
110
- /**
111
- * The fetch strategy to use when streaming updates from the PowerSync backend instance.
112
- */
113
- fetchStrategy?: FetchStrategy;
114
-
115
- /**
116
- * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
117
- */
118
- params?: Record<string, StreamingSyncRequestParameterType>;
119
-
120
- /**
121
- * Whether to include streams that have `auto_subscribe: true` in their definition.
122
- *
123
- * This defaults to `true`.
124
- */
125
- includeDefaultStreams?: boolean;
126
-
127
- /**
128
- * The serialized schema - mainly used to forward information about raw tables to the sync client.
129
- */
130
- serializedSchema?: any;
131
- }
132
-
133
- /** @internal */
134
- export interface AdditionalConnectionOptions {
135
- /**
136
- * Delay for retrying sync streaming operations
137
- * from the PowerSync backend after an error occurs.
138
- */
139
- retryDelayMs?: number;
140
- /**
141
- * Backend Connector CRUD operations are throttled
142
- * to occur at most every `crudUploadThrottleMs`
143
- * milliseconds.
144
- */
145
- crudUploadThrottleMs?: number;
146
- }
147
-
148
- /** @internal */
149
- export interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
150
- subscriptions: SubscribedStream[];
151
- }
152
-
153
- export interface StreamingSyncImplementation
154
- extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
155
- /**
156
- * Connects to the sync service
157
- */
158
- connect(options?: InternalConnectionOptions): Promise<void>;
159
- /**
160
- * Disconnects from the sync services.
161
- * @throws if not connected or if abort is not controlled internally
162
- */
163
- disconnect(): Promise<void>;
164
- getWriteCheckpoint: () => Promise<string>;
165
- isConnected: boolean;
166
- syncStatus: SyncStatus;
167
- triggerCrudUpload: () => void;
168
- waitForReady(): Promise<void>;
169
- waitForStatus(status: SyncStatusOptions): Promise<void>;
170
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
171
- updateSubscriptions(subscriptions: SubscribedStream[]): void;
172
- markConnectionMayHaveChanged(): void;
173
- }
174
-
175
- export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
176
- export const DEFAULT_RETRY_DELAY_MS = 5000;
177
-
178
- export const DEFAULT_STREAMING_SYNC_OPTIONS = {
179
- retryDelayMs: DEFAULT_RETRY_DELAY_MS,
180
- crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
181
- };
182
-
183
- export type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
184
-
185
- export const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions = {
186
- appMetadata: {},
187
- connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,
188
- clientImplementation: DEFAULT_SYNC_CLIENT_IMPLEMENTATION,
189
- fetchStrategy: FetchStrategy.Buffered,
190
- params: {},
191
- serializedSchema: undefined,
192
- includeDefaultStreams: true
193
- };
194
-
195
- export type SubscribedStream = {
196
- name: string;
197
- params: Record<string, any> | null;
198
- };
199
-
200
- // The priority we assume when we receive checkpoint lines where no priority is set.
201
- // This is the default priority used by the sync service, but can be set to an arbitrary
202
- // value since sync services without priorities also won't send partial sync completion
203
- // messages.
204
- const FALLBACK_PRIORITY = 3;
205
-
206
- export abstract class AbstractStreamingSyncImplementation
207
- extends BaseObserver<StreamingSyncImplementationListener>
208
- implements StreamingSyncImplementation
209
- {
210
- protected options: AbstractStreamingSyncImplementationOptions;
211
- protected abortController: AbortController | null;
212
- // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
213
- // This allows ensuring that all upload processes can be aborted.
214
- protected uploadAbortController: AbortController | undefined;
215
- protected crudUpdateListener?: () => void;
216
- protected streamingSyncPromise?: Promise<void>;
217
- protected logger: ILogger;
218
- private activeStreams: SubscribedStream[];
219
- private connectionMayHaveChanged = false;
220
-
221
- private isUploadingCrud: boolean = false;
222
- private notifyCompletedUploads?: () => void;
223
- private handleActiveStreamsChange?: () => void;
224
-
225
- syncStatus: SyncStatus;
226
- triggerCrudUpload: () => void;
227
-
228
- constructor(options: AbstractStreamingSyncImplementationOptions) {
229
- super();
230
- this.options = options;
231
- this.activeStreams = options.subscriptions;
232
- this.logger = options.logger ?? Logger.get('PowerSyncStream');
233
-
234
- this.syncStatus = new SyncStatus({
235
- connected: false,
236
- connecting: false,
237
- lastSyncedAt: undefined,
238
- dataFlow: {
239
- uploading: false,
240
- downloading: false
241
- }
242
- });
243
- this.abortController = null;
244
-
245
- this.triggerCrudUpload = throttleLeadingTrailing(() => {
246
- if (!this.syncStatus.connected || this.isUploadingCrud) {
247
- return;
248
- }
249
-
250
- this.isUploadingCrud = true;
251
- this._uploadAllCrud().finally(() => {
252
- this.notifyCompletedUploads?.();
253
- this.isUploadingCrud = false;
254
- });
255
- }, this.options.crudUploadThrottleMs!);
256
- }
257
-
258
- async waitForReady() {}
259
-
260
- waitForStatus(status: SyncStatusOptions): Promise<void> {
261
- return this.waitUntilStatusMatches((currentStatus) => {
262
- /**
263
- * Match only the partial status options provided in the
264
- * matching status
265
- */
266
- const matchPartialObject = (compA: object, compB: any): any => {
267
- return Object.entries(compA).every(([key, value]) => {
268
- const comparisonBValue = compB[key];
269
- if (typeof value == 'object' && typeof comparisonBValue == 'object') {
270
- return matchPartialObject(value, comparisonBValue);
271
- }
272
- return value == comparisonBValue;
273
- });
274
- };
275
-
276
- return matchPartialObject(status, currentStatus);
277
- });
278
- }
279
-
280
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void> {
281
- return new Promise((resolve) => {
282
- if (predicate(this.syncStatus)) {
283
- resolve();
284
- return;
285
- }
286
-
287
- const l = this.registerListener({
288
- statusChanged: (updatedStatus) => {
289
- if (predicate(updatedStatus)) {
290
- resolve();
291
- l?.();
292
- }
293
- }
294
- });
295
- });
296
- }
297
-
298
- get lastSyncedAt() {
299
- const lastSynced = this.syncStatus.lastSyncedAt;
300
- return lastSynced && new Date(lastSynced);
301
- }
302
-
303
- get isConnected() {
304
- return this.syncStatus.connected;
305
- }
306
-
307
- async dispose() {
308
- super.dispose();
309
- this.crudUpdateListener?.();
310
- this.crudUpdateListener = undefined;
311
- this.uploadAbortController?.abort();
312
- }
313
-
314
- abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
315
-
316
- async getWriteCheckpoint(): Promise<string> {
317
- const clientId = await this.options.adapter.getClientId();
318
- let path = `/write-checkpoint2.json?client_id=${clientId}`;
319
- const response = await this.options.remote.get(path);
320
- const checkpoint = response['data']['write_checkpoint'] as string;
321
- this.logger.debug(`Created write checkpoint: ${checkpoint}`);
322
- return checkpoint;
323
- }
324
-
325
- protected async _uploadAllCrud(): Promise<void> {
326
- return this.obtainLock({
327
- type: LockType.CRUD,
328
- callback: async () => {
329
- /**
330
- * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
331
- */
332
- let checkedCrudItem: CrudEntry | undefined;
333
-
334
- const controller = new AbortController();
335
- this.uploadAbortController = controller;
336
- this.abortController?.signal.addEventListener(
337
- 'abort',
338
- () => {
339
- controller.abort();
340
- },
341
- { once: true }
342
- );
343
-
344
- while (!controller.signal.aborted) {
345
- try {
346
- /**
347
- * This is the first item in the FIFO CRUD queue.
348
- */
349
- const nextCrudItem = await this.options.adapter.nextCrudItem();
350
- if (nextCrudItem) {
351
- this.updateSyncStatus({
352
- dataFlow: {
353
- uploading: true
354
- }
355
- });
356
-
357
- if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
358
- // This will force a higher log level than exceptions which are caught here.
359
- this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.
360
- Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
361
- The next upload iteration will be delayed.`);
362
- throw new Error('Delaying due to previously encountered CRUD item.');
363
- }
364
-
365
- checkedCrudItem = nextCrudItem;
366
- await this.options.uploadCrud();
367
- this.updateSyncStatus({
368
- dataFlow: {
369
- uploadError: undefined
370
- }
371
- });
372
- } else {
373
- // Uploading is completed
374
- const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
375
- if (neededUpdate == false && checkedCrudItem != null) {
376
- // Only log this if there was something to upload
377
- this.logger.debug('Upload complete, no write checkpoint needed.');
378
- }
379
- break;
380
- }
381
- } catch (ex) {
382
- checkedCrudItem = undefined;
383
- this.updateSyncStatus({
384
- dataFlow: {
385
- uploading: false,
386
- uploadError: ex as Error
387
- }
388
- });
389
- await this.delayRetry(controller.signal);
390
- if (!this.isConnected) {
391
- // Exit the upload loop if the sync stream is no longer connected
392
- break;
393
- }
394
- this.logger.debug(
395
- `Caught exception when uploading. Upload will retry after a delay. Exception: ${(ex as Error).message}`
396
- );
397
- } finally {
398
- this.updateSyncStatus({
399
- dataFlow: {
400
- uploading: false
401
- }
402
- });
403
- }
404
- }
405
- this.uploadAbortController = undefined;
406
- }
407
- });
408
- }
409
-
410
- async connect(options?: PowerSyncConnectionOptions) {
411
- if (this.abortController) {
412
- await this.disconnect();
413
- }
414
-
415
- const controller = new AbortController();
416
- this.abortController = controller;
417
- this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);
418
-
419
- // Return a promise that resolves when the connection status is updated to indicate that we're connected.
420
- return new Promise<void>((resolve) => {
421
- const disposer = this.registerListener({
422
- statusChanged: (status) => {
423
- if (status.dataFlowStatus.downloadError != null) {
424
- this.logger.warn('Initial connect attempt did not successfully connect to server');
425
- } else if (status.connecting) {
426
- // Still connecting.
427
- return;
428
- }
429
-
430
- disposer();
431
- resolve();
432
- }
433
- });
434
- });
435
- }
436
-
437
- async disconnect(): Promise<void> {
438
- if (!this.abortController) {
439
- return;
440
- }
441
-
442
- // This might be called multiple times
443
- if (!this.abortController.signal.aborted) {
444
- this.abortController.abort(new AbortOperation('Disconnect has been requested'));
445
- }
446
-
447
- // Await any pending operations before completing the disconnect operation
448
- try {
449
- await this.streamingSyncPromise;
450
- } catch (ex) {
451
- // The operation might have failed, all we care about is if it has completed
452
- this.logger.warn(ex);
453
- }
454
- this.streamingSyncPromise = undefined;
455
-
456
- this.abortController = null;
457
- this.updateSyncStatus({ connected: false, connecting: false });
458
- }
459
-
460
- /**
461
- * @deprecated use [connect instead]
462
- */
463
- async streamingSync(signal?: AbortSignal, options?: PowerSyncConnectionOptions): Promise<void> {
464
- if (!signal) {
465
- this.abortController = new AbortController();
466
- signal = this.abortController.signal;
467
- }
468
-
469
- /**
470
- * Listen for CRUD updates and trigger upstream uploads
471
- */
472
- this.crudUpdateListener = this.options.adapter.registerListener({
473
- crudUpdate: () => this.triggerCrudUpload()
474
- });
475
-
476
- /**
477
- * Create a new abort controller which aborts items downstream.
478
- * This is needed to close any previous connections on exception.
479
- */
480
- let nestedAbortController = new AbortController();
481
-
482
- signal.addEventListener('abort', () => {
483
- /**
484
- * A request for disconnect was received upstream. Relay the request
485
- * to the nested abort controller.
486
- */
487
- nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
488
- this.crudUpdateListener?.();
489
- this.crudUpdateListener = undefined;
490
- this.updateSyncStatus({
491
- connected: false,
492
- connecting: false,
493
- dataFlow: {
494
- downloading: false,
495
- downloadProgress: null
496
- }
497
- });
498
- });
499
-
500
- /**
501
- * This loops runs until [retry] is false or the abort signal is set to aborted.
502
- * Aborting the nestedAbortController will:
503
- * - Abort any pending fetch requests
504
- * - Close any sync stream ReadableStreams (which will also close any established network requests)
505
- */
506
- while (true) {
507
- this.updateSyncStatus({ connecting: true });
508
- let shouldDelayRetry = true;
509
- let result: RustIterationResult | null = null;
510
-
511
- try {
512
- if (signal?.aborted) {
513
- break;
514
- }
515
- result = await this.streamingSyncIteration(nestedAbortController.signal, options);
516
- // Continue immediately, streamingSyncIteration will wait before completing if necessary.
517
- } catch (ex) {
518
- /**
519
- * Either:
520
- * - A network request failed with a failed connection or not OKAY response code.
521
- * - There was a sync processing error.
522
- * - The connection was aborted.
523
- * This loop will retry after a delay if the connection was not aborted.
524
- * The nested abort controller will cleanup any open network requests and streams.
525
- * The WebRemote should only abort pending fetch requests or close active Readable streams.
526
- */
527
-
528
- if (ex instanceof AbortOperation) {
529
- this.logger.warn(ex);
530
- shouldDelayRetry = false;
531
- // A disconnect was requested, we should not delay since there is no explicit retry
532
- } else if (this.connectionMayHaveChanged && (ex as Error).message?.indexOf('No iteration is active') >= 0) {
533
- this.connectionMayHaveChanged = false;
534
- this.logger.info('Sync error after changed connection, retrying immediately');
535
- shouldDelayRetry = false;
536
- } else {
537
- this.logger.error(ex);
538
- }
539
-
540
- this.updateSyncStatus({
541
- dataFlow: {
542
- downloadError: ex as Error
543
- }
544
- });
545
- } finally {
546
- this.notifyCompletedUploads = undefined;
547
-
548
- if (!signal.aborted) {
549
- nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
550
- nestedAbortController = new AbortController();
551
- }
552
-
553
- if (result?.immediateRestart != true) {
554
- this.updateSyncStatus({
555
- connected: false,
556
- connecting: true // May be unnecessary
557
- });
558
-
559
- // On error, wait a little before retrying
560
- if (shouldDelayRetry) {
561
- await this.delayRetry(nestedAbortController.signal);
562
- }
563
- }
564
- }
565
- }
566
-
567
- // Mark as disconnected if here
568
- this.updateSyncStatus({ connected: false, connecting: false });
569
- }
570
-
571
- markConnectionMayHaveChanged() {
572
- // By setting this field, we'll immediately retry if the next sync event causes an error triggered by us not having
573
- // an active sync iteration on the connection in use.
574
- this.connectionMayHaveChanged = true;
575
-
576
- // This triggers a `powersync_control` invocation if a sync iteration is currently active. This is a cheap call to
577
- // make when no subscriptions have actually changed, we're mainly interested in this immediately throwing if no
578
- // iteration is active. That allows us to reconnect ASAP, instead of having to wait for the next sync line.
579
- this.handleActiveStreamsChange?.();
580
- }
581
-
582
- /**
583
- * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
584
- * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
585
- * While this is not a problem as long as it's done consistently, it causes issues when a database
586
- * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
587
- * is enabled.
588
- *
589
- * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
590
- * migration is only triggered when necessary (for now). The function returns whether the new format
591
- * should be used, so that the JS SDK is able to write to updated databases.
592
- *
593
- * @param requireFixedKeyFormat Whether we require the new format or also support the old one.
594
- * The Rust client requires the new subkey format.
595
- * @returns Whether the database is now using the new, fixed subkey format.
596
- */
597
- private async requireKeyFormat(requireFixedKeyFormat: boolean): Promise<boolean> {
598
- const hasMigrated = await this.options.adapter.hasMigratedSubkeys();
599
- if (requireFixedKeyFormat && !hasMigrated) {
600
- await this.options.adapter.migrateToFixedSubkeys();
601
- return true;
602
- } else {
603
- return hasMigrated;
604
- }
605
- }
606
-
607
- protected streamingSyncIteration(
608
- signal: AbortSignal,
609
- options?: PowerSyncConnectionOptions
610
- ): Promise<RustIterationResult | null> {
611
- return this.obtainLock({
612
- type: LockType.SYNC,
613
- signal,
614
- callback: async () => {
615
- const resolvedOptions: RequiredPowerSyncConnectionOptions = {
616
- ...DEFAULT_STREAM_CONNECTION_OPTIONS,
617
- ...(options ?? {})
618
- };
619
-
620
- // Validate app metadata
621
- const invalidMetadata = Object.entries(resolvedOptions.appMetadata).filter(
622
- ([_, value]) => typeof value != 'string'
623
- );
624
- if (invalidMetadata.length > 0) {
625
- throw new Error(
626
- `Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`
627
- );
628
- }
629
- const clientImplementation = resolvedOptions.clientImplementation;
630
- this.updateSyncStatus({ clientImplementation });
631
-
632
- await this.requireKeyFormat(true);
633
- return await this.rustSyncIteration(signal, resolvedOptions);
634
- }
635
- });
636
- }
637
-
638
- private async receiveSyncLines(data: {
639
- options: SyncStreamOptions;
640
- connection: RequiredPowerSyncConnectionOptions;
641
- }): Promise<SimpleAsyncIterator<Uint8Array | string>> {
642
- const { options, connection } = data;
643
- const remote = this.options.remote;
644
-
645
- if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
646
- return await remote.fetchStream(options);
647
- } else {
648
- return await this.options.remote.socketStreamRaw({
649
- ...options,
650
- ...{ fetchStrategy: connection.fetchStrategy }
651
- });
652
- }
653
- }
654
-
655
- private async rustSyncIteration(
656
- signal: AbortSignal,
657
- resolvedOptions: RequiredPowerSyncConnectionOptions
658
- ): Promise<RustIterationResult> {
659
- const syncImplementation = this;
660
- const adapter = this.options.adapter;
661
- const remote = this.options.remote;
662
- const controller = new AbortController();
663
- const abort = () => {
664
- return controller.abort(signal.reason);
665
- };
666
- signal.addEventListener('abort', abort);
667
- let receivingLines: Promise<void> | null = null;
668
- let hadSyncLine = false;
669
- let hideDisconnectOnRestart = false;
670
-
671
- if (signal.aborted) {
672
- throw new AbortOperation('Connection request has been aborted');
673
- }
674
-
675
- // Pending sync lines received from the service, as well as local events that trigger a powersync_control
676
- // invocation (local events include refreshed tokens and completed uploads).
677
- // This is a single data stream so that we can handle all control calls from a single place.
678
- let controlInvocations: InjectableIterator<EnqueuedCommand> | null = null;
679
-
680
- async function connect(instr: EstablishSyncStream) {
681
- const syncOptions: SyncStreamOptions = {
682
- path: '/sync/stream',
683
- abortSignal: controller.signal,
684
- data: instr.request
685
- };
686
-
687
- controlInvocations = injectable(
688
- map(
689
- await syncImplementation.receiveSyncLines({
690
- options: syncOptions,
691
- connection: resolvedOptions
692
- }),
693
- (line) => {
694
- if (typeof line == 'string') {
695
- return {
696
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
697
- payload: line
698
- };
699
- } else {
700
- return {
701
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
702
- payload: line
703
- };
704
- }
705
- }
706
- )
707
- );
708
-
709
- // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
710
- // we're already connected here and can report that.
711
- syncImplementation.updateSyncStatus({ connected: true });
712
-
713
- try {
714
- while (true) {
715
- let event = await controlInvocations.next();
716
- if (event.done) {
717
- break;
718
- }
719
-
720
- const line = event.value;
721
- await control(line.command, line.payload);
722
-
723
- if (!hadSyncLine) {
724
- syncImplementation.triggerCrudUpload();
725
- hadSyncLine = true;
726
- }
727
- }
728
- } finally {
729
- abort();
730
- signal.removeEventListener('abort', abort);
731
- }
732
- }
733
-
734
- async function stop() {
735
- await control(PowerSyncControlCommand.STOP);
736
- }
737
-
738
- async function control(op: PowerSyncControlCommand, payload?: Uint8Array | string) {
739
- const rawResponse = await adapter.control(op, payload ?? null);
740
- const logger = syncImplementation.logger;
741
- logger.trace(
742
- 'powersync_control',
743
- op,
744
- payload == null || typeof payload == 'string' ? payload : '<bytes>',
745
- rawResponse
746
- );
747
-
748
- if (op != PowerSyncControlCommand.STOP) {
749
- // Evidently we have a working connection here, otherwise powersync_control would have failed.
750
- syncImplementation.connectionMayHaveChanged = false;
751
- }
752
- await handleInstructions(JSON.parse(rawResponse));
753
- }
754
-
755
- async function handleInstruction(instruction: Instruction) {
756
- if ('LogLine' in instruction) {
757
- switch (instruction.LogLine.severity) {
758
- case 'DEBUG':
759
- syncImplementation.logger.debug(instruction.LogLine.line);
760
- break;
761
- case 'INFO':
762
- syncImplementation.logger.info(instruction.LogLine.line);
763
- break;
764
- case 'WARNING':
765
- syncImplementation.logger.warn(instruction.LogLine.line);
766
- break;
767
- }
768
- } else if ('UpdateSyncStatus' in instruction) {
769
- syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
770
- } else if ('EstablishSyncStream' in instruction) {
771
- if (receivingLines != null) {
772
- // Already connected, this shouldn't happen during a single iteration.
773
- throw 'Unexpected request to establish sync stream, already connected';
774
- }
775
-
776
- receivingLines = connect(instruction.EstablishSyncStream);
777
- } else if ('FetchCredentials' in instruction) {
778
- if (instruction.FetchCredentials.did_expire) {
779
- remote.invalidateCredentials();
780
- } else {
781
- remote.invalidateCredentials();
782
-
783
- // Restart iteration after the credentials have been refreshed.
784
- remote.fetchCredentials().then(
785
- (_) => {
786
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
787
- },
788
- (err) => {
789
- syncImplementation.logger.warn('Could not prefetch credentials', err);
790
- }
791
- );
792
- }
793
- } else if ('CloseSyncStream' in instruction) {
794
- controller.abort();
795
- hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
796
- } else if ('FlushFileSystem' in instruction) {
797
- // Not necessary on JS platforms.
798
- } else if ('DidCompleteSync' in instruction) {
799
- syncImplementation.updateSyncStatus({
800
- dataFlow: {
801
- downloadError: undefined
802
- }
803
- });
804
- }
805
- }
806
-
807
- async function handleInstructions(instructions: Instruction[]) {
808
- for (const instr of instructions) {
809
- await handleInstruction(instr);
810
- }
811
- }
812
-
813
- try {
814
- const options: any = {
815
- parameters: resolvedOptions.params,
816
- app_metadata: resolvedOptions.appMetadata,
817
- active_streams: this.activeStreams,
818
- include_defaults: resolvedOptions.includeDefaultStreams
819
- };
820
- if (resolvedOptions.serializedSchema) {
821
- options.schema = resolvedOptions.serializedSchema;
822
- }
823
-
824
- await control(PowerSyncControlCommand.START, JSON.stringify(options));
825
-
826
- this.notifyCompletedUploads = () => {
827
- controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
828
- };
829
- this.handleActiveStreamsChange = () => {
830
- controlInvocations?.inject({
831
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
832
- payload: JSON.stringify(this.activeStreams)
833
- });
834
- };
835
- await receivingLines;
836
- } finally {
837
- this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
838
- await stop();
839
- }
840
-
841
- return { immediateRestart: hideDisconnectOnRestart };
842
- }
843
-
844
- protected updateSyncStatus(options: SyncStatusOptions) {
845
- const updatedStatus = new SyncStatus({
846
- connected: options.connected ?? this.syncStatus.connected,
847
- connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),
848
- lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,
849
- dataFlow: {
850
- ...this.syncStatus.dataFlowStatus,
851
- ...options.dataFlow
852
- },
853
- priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries,
854
- clientImplementation: options.clientImplementation ?? this.syncStatus.clientImplementation
855
- });
856
-
857
- if (!this.syncStatus.isEqual(updatedStatus)) {
858
- this.syncStatus = updatedStatus;
859
- // Only trigger this is there was a change
860
- this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));
861
- }
862
-
863
- // trigger this for all updates
864
- this.iterateListeners((cb) => cb.statusUpdated?.(options));
865
- }
866
-
867
- private async delayRetry(signal?: AbortSignal): Promise<void> {
868
- return new Promise((resolve) => {
869
- if (signal?.aborted) {
870
- // If the signal is already aborted, resolve immediately
871
- resolve();
872
- return;
873
- }
874
- const { retryDelayMs } = this.options;
875
-
876
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
877
-
878
- const endDelay = () => {
879
- resolve();
880
- if (timeoutId) {
881
- clearTimeout(timeoutId);
882
- timeoutId = undefined;
883
- }
884
- signal?.removeEventListener('abort', endDelay);
885
- };
886
-
887
- signal?.addEventListener('abort', endDelay, { once: true });
888
- timeoutId = setTimeout(endDelay, retryDelayMs);
889
- });
890
- }
891
-
892
- updateSubscriptions(subscriptions: SubscribedStream[]): void {
893
- this.activeStreams = subscriptions;
894
- this.handleActiveStreamsChange?.();
895
- }
896
- }
897
-
898
- interface EnqueuedCommand {
899
- command: PowerSyncControlCommand;
900
- payload?: Uint8Array | string;
901
- }
902
-
903
- interface RustIterationResult {
904
- immediateRestart: boolean;
905
- }