@powersync/common 0.0.0-dev-20260202162549 → 0.0.0-dev-20260216124709

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 (214) hide show
  1. package/dist/bundle.cjs +14470 -0
  2. package/dist/bundle.cjs.map +1 -0
  3. package/dist/bundle.mjs +14379 -0
  4. package/dist/bundle.mjs.map +1 -0
  5. package/dist/bundle.node.cjs +11948 -0
  6. package/dist/bundle.node.cjs.map +1 -0
  7. package/dist/bundle.node.mjs +11857 -0
  8. package/dist/bundle.node.mjs.map +1 -0
  9. package/dist/index.d.cts +4272 -0
  10. package/lib/attachments/AttachmentContext.d.ts +86 -0
  11. package/lib/attachments/AttachmentContext.js +229 -0
  12. package/lib/attachments/AttachmentContext.js.map +1 -0
  13. package/lib/attachments/AttachmentErrorHandler.d.ts +31 -0
  14. package/lib/attachments/AttachmentErrorHandler.js +2 -0
  15. package/lib/attachments/AttachmentErrorHandler.js.map +1 -0
  16. package/lib/attachments/AttachmentQueue.d.ts +149 -0
  17. package/lib/attachments/AttachmentQueue.js +362 -0
  18. package/lib/attachments/AttachmentQueue.js.map +1 -0
  19. package/lib/attachments/AttachmentService.d.ts +29 -0
  20. package/lib/attachments/AttachmentService.js +56 -0
  21. package/lib/attachments/AttachmentService.js.map +1 -0
  22. package/lib/attachments/LocalStorageAdapter.d.ts +62 -0
  23. package/lib/attachments/LocalStorageAdapter.js +6 -0
  24. package/lib/attachments/LocalStorageAdapter.js.map +1 -0
  25. package/lib/attachments/RemoteStorageAdapter.d.ts +27 -0
  26. package/lib/attachments/RemoteStorageAdapter.js +2 -0
  27. package/lib/attachments/RemoteStorageAdapter.js.map +1 -0
  28. package/lib/attachments/Schema.d.ts +50 -0
  29. package/lib/attachments/Schema.js +62 -0
  30. package/lib/attachments/Schema.js.map +1 -0
  31. package/lib/attachments/SyncingService.d.ts +62 -0
  32. package/lib/attachments/SyncingService.js +168 -0
  33. package/lib/attachments/SyncingService.js.map +1 -0
  34. package/lib/attachments/WatchedAttachmentItem.d.ts +17 -0
  35. package/lib/attachments/WatchedAttachmentItem.js +2 -0
  36. package/lib/attachments/WatchedAttachmentItem.js.map +1 -0
  37. package/lib/client/AbstractPowerSyncDatabase.d.ts +615 -0
  38. package/lib/client/AbstractPowerSyncDatabase.js +983 -0
  39. package/lib/client/AbstractPowerSyncDatabase.js.map +1 -0
  40. package/lib/client/AbstractPowerSyncOpenFactory.d.ts +22 -0
  41. package/lib/client/AbstractPowerSyncOpenFactory.js +25 -0
  42. package/lib/client/AbstractPowerSyncOpenFactory.js.map +1 -0
  43. package/lib/client/ConnectionManager.d.ts +112 -0
  44. package/lib/client/ConnectionManager.js +294 -0
  45. package/lib/client/ConnectionManager.js.map +1 -0
  46. package/lib/client/CustomQuery.d.ts +22 -0
  47. package/lib/client/CustomQuery.js +43 -0
  48. package/lib/client/CustomQuery.js.map +1 -0
  49. package/lib/client/Query.d.ts +97 -0
  50. package/lib/client/Query.js +2 -0
  51. package/lib/client/Query.js.map +1 -0
  52. package/lib/client/SQLOpenFactory.d.ts +42 -0
  53. package/lib/client/SQLOpenFactory.js +20 -0
  54. package/lib/client/SQLOpenFactory.js.map +1 -0
  55. package/lib/client/compilableQueryWatch.d.ts +7 -0
  56. package/lib/client/compilableQueryWatch.js +38 -0
  57. package/lib/client/compilableQueryWatch.js.map +1 -0
  58. package/lib/client/connection/PowerSyncBackendConnector.d.ts +23 -0
  59. package/lib/client/connection/PowerSyncBackendConnector.js +2 -0
  60. package/lib/client/connection/PowerSyncBackendConnector.js.map +1 -0
  61. package/lib/client/connection/PowerSyncCredentials.d.ts +5 -0
  62. package/lib/client/connection/PowerSyncCredentials.js +2 -0
  63. package/lib/client/connection/PowerSyncCredentials.js.map +1 -0
  64. package/lib/client/constants.d.ts +1 -0
  65. package/lib/client/constants.js +2 -0
  66. package/lib/client/constants.js.map +1 -0
  67. package/lib/client/runOnSchemaChange.d.ts +2 -0
  68. package/lib/client/runOnSchemaChange.js +24 -0
  69. package/lib/client/runOnSchemaChange.js.map +1 -0
  70. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +102 -0
  71. package/lib/client/sync/bucket/BucketStorageAdapter.js +19 -0
  72. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  73. package/lib/client/sync/bucket/CrudBatch.d.ts +31 -0
  74. package/lib/client/sync/bucket/CrudBatch.js +26 -0
  75. package/lib/client/sync/bucket/CrudBatch.js.map +1 -0
  76. package/lib/client/sync/bucket/CrudEntry.d.ts +95 -0
  77. package/lib/client/sync/bucket/CrudEntry.js +110 -0
  78. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  79. package/lib/client/sync/bucket/CrudTransaction.d.ts +29 -0
  80. package/lib/client/sync/bucket/CrudTransaction.js +25 -0
  81. package/lib/client/sync/bucket/CrudTransaction.js.map +1 -0
  82. package/lib/client/sync/bucket/OpType.d.ts +16 -0
  83. package/lib/client/sync/bucket/OpType.js +23 -0
  84. package/lib/client/sync/bucket/OpType.js.map +1 -0
  85. package/lib/client/sync/bucket/OplogEntry.d.ts +23 -0
  86. package/lib/client/sync/bucket/OplogEntry.js +36 -0
  87. package/lib/client/sync/bucket/OplogEntry.js.map +1 -0
  88. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +61 -0
  89. package/lib/client/sync/bucket/SqliteBucketStorage.js +324 -0
  90. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  91. package/lib/client/sync/bucket/SyncDataBatch.d.ts +6 -0
  92. package/lib/client/sync/bucket/SyncDataBatch.js +12 -0
  93. package/lib/client/sync/bucket/SyncDataBatch.js.map +1 -0
  94. package/lib/client/sync/bucket/SyncDataBucket.d.ts +40 -0
  95. package/lib/client/sync/bucket/SyncDataBucket.js +40 -0
  96. package/lib/client/sync/bucket/SyncDataBucket.js.map +1 -0
  97. package/lib/client/sync/stream/AbstractRemote.d.ts +140 -0
  98. package/lib/client/sync/stream/AbstractRemote.js +506 -0
  99. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  100. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +240 -0
  101. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +990 -0
  102. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  103. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  104. package/lib/client/sync/stream/WebsocketClientTransport.js +61 -0
  105. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  106. package/lib/client/sync/stream/core-instruction.d.ts +72 -0
  107. package/lib/client/sync/stream/core-instruction.js +27 -0
  108. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  109. package/lib/client/sync/stream/streaming-sync-types.d.ts +143 -0
  110. package/lib/client/sync/stream/streaming-sync-types.js +26 -0
  111. package/lib/client/sync/stream/streaming-sync-types.js.map +1 -0
  112. package/lib/client/sync/sync-streams.d.ts +98 -0
  113. package/lib/client/sync/sync-streams.js +2 -0
  114. package/lib/client/sync/sync-streams.js.map +1 -0
  115. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  116. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  117. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  118. package/lib/client/triggers/TriggerManager.d.ts +459 -0
  119. package/lib/client/triggers/TriggerManager.js +11 -0
  120. package/lib/client/triggers/TriggerManager.js.map +1 -0
  121. package/lib/client/triggers/TriggerManagerImpl.d.ts +39 -0
  122. package/lib/client/triggers/TriggerManagerImpl.js +393 -0
  123. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  124. package/lib/client/triggers/sanitizeSQL.d.ts +34 -0
  125. package/lib/client/triggers/sanitizeSQL.js +69 -0
  126. package/lib/client/triggers/sanitizeSQL.js.map +1 -0
  127. package/lib/client/watched/GetAllQuery.d.ts +32 -0
  128. package/lib/client/watched/GetAllQuery.js +25 -0
  129. package/lib/client/watched/GetAllQuery.js.map +1 -0
  130. package/lib/client/watched/WatchedQuery.d.ts +100 -0
  131. package/lib/client/watched/WatchedQuery.js +14 -0
  132. package/lib/client/watched/WatchedQuery.js.map +1 -0
  133. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +68 -0
  134. package/lib/client/watched/processors/AbstractQueryProcessor.js +151 -0
  135. package/lib/client/watched/processors/AbstractQueryProcessor.js.map +1 -0
  136. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +121 -0
  137. package/lib/client/watched/processors/DifferentialQueryProcessor.js +173 -0
  138. package/lib/client/watched/processors/DifferentialQueryProcessor.js.map +1 -0
  139. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +33 -0
  140. package/lib/client/watched/processors/OnChangeQueryProcessor.js +83 -0
  141. package/lib/client/watched/processors/OnChangeQueryProcessor.js.map +1 -0
  142. package/lib/client/watched/processors/comparators.d.ts +30 -0
  143. package/lib/client/watched/processors/comparators.js +35 -0
  144. package/lib/client/watched/processors/comparators.js.map +1 -0
  145. package/lib/db/ConnectionClosedError.d.ts +10 -0
  146. package/lib/db/ConnectionClosedError.js +21 -0
  147. package/lib/db/ConnectionClosedError.js.map +1 -0
  148. package/lib/db/DBAdapter.d.ts +115 -0
  149. package/lib/db/DBAdapter.js +20 -0
  150. package/lib/db/DBAdapter.js.map +1 -0
  151. package/lib/db/crud/SyncProgress.d.ts +68 -0
  152. package/lib/db/crud/SyncProgress.js +61 -0
  153. package/lib/db/crud/SyncProgress.js.map +1 -0
  154. package/lib/db/crud/SyncStatus.d.ts +195 -0
  155. package/lib/db/crud/SyncStatus.js +250 -0
  156. package/lib/db/crud/SyncStatus.js.map +1 -0
  157. package/lib/db/crud/UploadQueueStatus.d.ts +20 -0
  158. package/lib/db/crud/UploadQueueStatus.js +25 -0
  159. package/lib/db/crud/UploadQueueStatus.js.map +1 -0
  160. package/lib/db/schema/Column.d.ts +30 -0
  161. package/lib/db/schema/Column.js +43 -0
  162. package/lib/db/schema/Column.js.map +1 -0
  163. package/lib/db/schema/Index.d.ts +22 -0
  164. package/lib/db/schema/Index.js +30 -0
  165. package/lib/db/schema/Index.js.map +1 -0
  166. package/lib/db/schema/IndexedColumn.d.ts +19 -0
  167. package/lib/db/schema/IndexedColumn.js +30 -0
  168. package/lib/db/schema/IndexedColumn.js.map +1 -0
  169. package/lib/db/schema/RawTable.d.ts +61 -0
  170. package/lib/db/schema/RawTable.js +33 -0
  171. package/lib/db/schema/RawTable.js.map +1 -0
  172. package/lib/db/schema/Schema.d.ts +54 -0
  173. package/lib/db/schema/Schema.js +61 -0
  174. package/lib/db/schema/Schema.js.map +1 -0
  175. package/lib/db/schema/Table.d.ts +157 -0
  176. package/lib/db/schema/Table.js +208 -0
  177. package/lib/db/schema/Table.js.map +1 -0
  178. package/lib/db/schema/TableV2.d.ts +9 -0
  179. package/lib/db/schema/TableV2.js +9 -0
  180. package/lib/db/schema/TableV2.js.map +1 -0
  181. package/lib/index.d.ts +62 -0
  182. package/lib/index.js +63 -0
  183. package/lib/index.js.map +1 -0
  184. package/lib/types/types.d.ts +8 -0
  185. package/lib/types/types.js +2 -0
  186. package/lib/types/types.js.map +1 -0
  187. package/lib/utils/AbortOperation.d.ts +9 -0
  188. package/lib/utils/AbortOperation.js +19 -0
  189. package/lib/utils/AbortOperation.js.map +1 -0
  190. package/lib/utils/BaseObserver.d.ts +18 -0
  191. package/lib/utils/BaseObserver.js +27 -0
  192. package/lib/utils/BaseObserver.js.map +1 -0
  193. package/lib/utils/ControlledExecutor.d.ts +25 -0
  194. package/lib/utils/ControlledExecutor.js +51 -0
  195. package/lib/utils/ControlledExecutor.js.map +1 -0
  196. package/lib/utils/DataStream.d.ts +62 -0
  197. package/lib/utils/DataStream.js +169 -0
  198. package/lib/utils/DataStream.js.map +1 -0
  199. package/lib/utils/Logger.d.ts +31 -0
  200. package/lib/utils/Logger.js +37 -0
  201. package/lib/utils/Logger.js.map +1 -0
  202. package/lib/utils/MetaBaseObserver.d.ts +29 -0
  203. package/lib/utils/MetaBaseObserver.js +51 -0
  204. package/lib/utils/MetaBaseObserver.js.map +1 -0
  205. package/lib/utils/async.d.ts +23 -0
  206. package/lib/utils/async.js +55 -0
  207. package/lib/utils/async.js.map +1 -0
  208. package/lib/utils/mutex.d.ts +7 -0
  209. package/lib/utils/mutex.js +29 -0
  210. package/lib/utils/mutex.js.map +1 -0
  211. package/lib/utils/parseQuery.d.ts +6 -0
  212. package/lib/utils/parseQuery.js +17 -0
  213. package/lib/utils/parseQuery.js.map +1 -0
  214. package/package.json +1 -1
@@ -0,0 +1,990 @@
1
+ import Logger from 'js-logger';
2
+ import { SyncStatus } from '../../../db/crud/SyncStatus.js';
3
+ import { AbortOperation } from '../../../utils/AbortOperation.js';
4
+ import { BaseObserver } from '../../../utils/BaseObserver.js';
5
+ import { throttleLeadingTrailing } from '../../../utils/async.js';
6
+ import { PowerSyncControlCommand } from '../bucket/BucketStorageAdapter.js';
7
+ import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
8
+ import { FetchStrategy } from './AbstractRemote.js';
9
+ import { coreStatusToJs } from './core-instruction.js';
10
+ import { isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData } from './streaming-sync-types.js';
11
+ export var LockType;
12
+ (function (LockType) {
13
+ LockType["CRUD"] = "crud";
14
+ LockType["SYNC"] = "sync";
15
+ })(LockType || (LockType = {}));
16
+ export var SyncStreamConnectionMethod;
17
+ (function (SyncStreamConnectionMethod) {
18
+ SyncStreamConnectionMethod["HTTP"] = "http";
19
+ SyncStreamConnectionMethod["WEB_SOCKET"] = "web-socket";
20
+ })(SyncStreamConnectionMethod || (SyncStreamConnectionMethod = {}));
21
+ export var SyncClientImplementation;
22
+ (function (SyncClientImplementation) {
23
+ /**
24
+ * Decodes and handles sync lines received from the sync service in JavaScript.
25
+ *
26
+ * This is the default option.
27
+ *
28
+ * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
29
+ * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
30
+ * version of the PowerSync SDK.
31
+ */
32
+ SyncClientImplementation["JAVASCRIPT"] = "js";
33
+ /**
34
+ * This implementation offloads the sync line decoding and handling into the PowerSync
35
+ * core extension.
36
+ *
37
+ * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
38
+ * recommended client implementation for all apps.
39
+ *
40
+ * ## Compatibility warning
41
+ *
42
+ * The Rust sync client stores sync data in a format that is slightly different than the one used
43
+ * by the old {@link JAVASCRIPT} implementation. When adopting the {@link RUST} client on existing
44
+ * databases, the PowerSync SDK will migrate the format automatically.
45
+ * Further, the {@link JAVASCRIPT} client in recent versions of the PowerSync JS SDK (starting from
46
+ * the version introducing {@link RUST} as an option) also supports the new format, so you can switch
47
+ * back to {@link JAVASCRIPT} later.
48
+ *
49
+ * __However__: Upgrading the SDK version, then adopting {@link RUST} as a sync client and later
50
+ * downgrading the SDK to an older version (necessarily using the JavaScript-based implementation then)
51
+ * can lead to sync issues.
52
+ */
53
+ SyncClientImplementation["RUST"] = "rust";
54
+ })(SyncClientImplementation || (SyncClientImplementation = {}));
55
+ /**
56
+ * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
57
+ */
58
+ export const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
59
+ export const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
60
+ export const DEFAULT_RETRY_DELAY_MS = 5000;
61
+ export const DEFAULT_STREAMING_SYNC_OPTIONS = {
62
+ retryDelayMs: DEFAULT_RETRY_DELAY_MS,
63
+ crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
64
+ };
65
+ export const DEFAULT_STREAM_CONNECTION_OPTIONS = {
66
+ appMetadata: {},
67
+ connectionMethod: SyncStreamConnectionMethod.WEB_SOCKET,
68
+ clientImplementation: DEFAULT_SYNC_CLIENT_IMPLEMENTATION,
69
+ fetchStrategy: FetchStrategy.Buffered,
70
+ params: {},
71
+ serializedSchema: undefined,
72
+ includeDefaultStreams: true
73
+ };
74
+ // The priority we assume when we receive checkpoint lines where no priority is set.
75
+ // This is the default priority used by the sync service, but can be set to an arbitrary
76
+ // value since sync services without priorities also won't send partial sync completion
77
+ // messages.
78
+ const FALLBACK_PRIORITY = 3;
79
+ export class AbstractStreamingSyncImplementation extends BaseObserver {
80
+ _lastSyncedAt;
81
+ options;
82
+ abortController;
83
+ // In rare cases, mostly for tests, uploads can be triggered without being properly connected.
84
+ // This allows ensuring that all upload processes can be aborted.
85
+ uploadAbortController;
86
+ crudUpdateListener;
87
+ streamingSyncPromise;
88
+ logger;
89
+ activeStreams;
90
+ isUploadingCrud = false;
91
+ notifyCompletedUploads;
92
+ handleActiveStreamsChange;
93
+ syncStatus;
94
+ triggerCrudUpload;
95
+ constructor(options) {
96
+ super();
97
+ this.options = options;
98
+ this.activeStreams = options.subscriptions;
99
+ this.logger = options.logger ?? Logger.get('PowerSyncStream');
100
+ this.syncStatus = new SyncStatus({
101
+ connected: false,
102
+ connecting: false,
103
+ lastSyncedAt: undefined,
104
+ dataFlow: {
105
+ uploading: false,
106
+ downloading: false
107
+ }
108
+ });
109
+ this.abortController = null;
110
+ this.triggerCrudUpload = throttleLeadingTrailing(() => {
111
+ if (!this.syncStatus.connected || this.isUploadingCrud) {
112
+ return;
113
+ }
114
+ this.isUploadingCrud = true;
115
+ this._uploadAllCrud().finally(() => {
116
+ this.notifyCompletedUploads?.();
117
+ this.isUploadingCrud = false;
118
+ });
119
+ }, this.options.crudUploadThrottleMs);
120
+ }
121
+ async waitForReady() { }
122
+ waitForStatus(status) {
123
+ return this.waitUntilStatusMatches((currentStatus) => {
124
+ /**
125
+ * Match only the partial status options provided in the
126
+ * matching status
127
+ */
128
+ const matchPartialObject = (compA, compB) => {
129
+ return Object.entries(compA).every(([key, value]) => {
130
+ const comparisonBValue = compB[key];
131
+ if (typeof value == 'object' && typeof comparisonBValue == 'object') {
132
+ return matchPartialObject(value, comparisonBValue);
133
+ }
134
+ return value == comparisonBValue;
135
+ });
136
+ };
137
+ return matchPartialObject(status, currentStatus);
138
+ });
139
+ }
140
+ waitUntilStatusMatches(predicate) {
141
+ return new Promise((resolve) => {
142
+ if (predicate(this.syncStatus)) {
143
+ resolve();
144
+ return;
145
+ }
146
+ const l = this.registerListener({
147
+ statusChanged: (updatedStatus) => {
148
+ if (predicate(updatedStatus)) {
149
+ resolve();
150
+ l?.();
151
+ }
152
+ }
153
+ });
154
+ });
155
+ }
156
+ get lastSyncedAt() {
157
+ const lastSynced = this.syncStatus.lastSyncedAt;
158
+ return lastSynced && new Date(lastSynced);
159
+ }
160
+ get isConnected() {
161
+ return this.syncStatus.connected;
162
+ }
163
+ async dispose() {
164
+ super.dispose();
165
+ this.crudUpdateListener?.();
166
+ this.crudUpdateListener = undefined;
167
+ this.uploadAbortController?.abort();
168
+ }
169
+ async hasCompletedSync() {
170
+ return this.options.adapter.hasCompletedSync();
171
+ }
172
+ async getWriteCheckpoint() {
173
+ const clientId = await this.options.adapter.getClientId();
174
+ let path = `/write-checkpoint2.json?client_id=${clientId}`;
175
+ const response = await this.options.remote.get(path);
176
+ const checkpoint = response['data']['write_checkpoint'];
177
+ this.logger.debug(`Created write checkpoint: ${checkpoint}`);
178
+ return checkpoint;
179
+ }
180
+ async _uploadAllCrud() {
181
+ return this.obtainLock({
182
+ type: LockType.CRUD,
183
+ callback: async () => {
184
+ /**
185
+ * Keep track of the first item in the CRUD queue for the last `uploadCrud` iteration.
186
+ */
187
+ let checkedCrudItem;
188
+ const controller = new AbortController();
189
+ this.uploadAbortController = controller;
190
+ this.abortController?.signal.addEventListener('abort', () => {
191
+ controller.abort();
192
+ }, { once: true });
193
+ while (!controller.signal.aborted) {
194
+ try {
195
+ /**
196
+ * This is the first item in the FIFO CRUD queue.
197
+ */
198
+ const nextCrudItem = await this.options.adapter.nextCrudItem();
199
+ if (nextCrudItem) {
200
+ this.updateSyncStatus({
201
+ dataFlow: {
202
+ uploading: true
203
+ }
204
+ });
205
+ if (nextCrudItem.clientId == checkedCrudItem?.clientId) {
206
+ // This will force a higher log level than exceptions which are caught here.
207
+ this.logger.warn(`Potentially previously uploaded CRUD entries are still present in the upload queue.
208
+ Make sure to handle uploads and complete CRUD transactions or batches by calling and awaiting their [.complete()] method.
209
+ The next upload iteration will be delayed.`);
210
+ throw new Error('Delaying due to previously encountered CRUD item.');
211
+ }
212
+ checkedCrudItem = nextCrudItem;
213
+ await this.options.uploadCrud();
214
+ this.updateSyncStatus({
215
+ dataFlow: {
216
+ uploadError: undefined
217
+ }
218
+ });
219
+ }
220
+ else {
221
+ // Uploading is completed
222
+ const neededUpdate = await this.options.adapter.updateLocalTarget(() => this.getWriteCheckpoint());
223
+ if (neededUpdate == false && checkedCrudItem != null) {
224
+ // Only log this if there was something to upload
225
+ this.logger.debug('Upload complete, no write checkpoint needed.');
226
+ }
227
+ break;
228
+ }
229
+ }
230
+ catch (ex) {
231
+ checkedCrudItem = undefined;
232
+ this.updateSyncStatus({
233
+ dataFlow: {
234
+ uploading: false,
235
+ uploadError: ex
236
+ }
237
+ });
238
+ await this.delayRetry(controller.signal);
239
+ if (!this.isConnected) {
240
+ // Exit the upload loop if the sync stream is no longer connected
241
+ break;
242
+ }
243
+ this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`);
244
+ }
245
+ finally {
246
+ this.updateSyncStatus({
247
+ dataFlow: {
248
+ uploading: false
249
+ }
250
+ });
251
+ }
252
+ }
253
+ this.uploadAbortController = null;
254
+ }
255
+ });
256
+ }
257
+ async connect(options) {
258
+ if (this.abortController) {
259
+ await this.disconnect();
260
+ }
261
+ const controller = new AbortController();
262
+ this.abortController = controller;
263
+ this.streamingSyncPromise = this.streamingSync(this.abortController.signal, options);
264
+ // Return a promise that resolves when the connection status is updated to indicate that we're connected.
265
+ return new Promise((resolve) => {
266
+ const disposer = this.registerListener({
267
+ statusChanged: (status) => {
268
+ if (status.dataFlowStatus.downloadError != null) {
269
+ this.logger.warn('Initial connect attempt did not successfully connect to server');
270
+ }
271
+ else if (status.connecting) {
272
+ // Still connecting.
273
+ return;
274
+ }
275
+ disposer();
276
+ resolve();
277
+ }
278
+ });
279
+ });
280
+ }
281
+ async disconnect() {
282
+ if (!this.abortController) {
283
+ return;
284
+ }
285
+ // This might be called multiple times
286
+ if (!this.abortController.signal.aborted) {
287
+ this.abortController.abort(new AbortOperation('Disconnect has been requested'));
288
+ }
289
+ // Await any pending operations before completing the disconnect operation
290
+ try {
291
+ await this.streamingSyncPromise;
292
+ }
293
+ catch (ex) {
294
+ // The operation might have failed, all we care about is if it has completed
295
+ this.logger.warn(ex);
296
+ }
297
+ this.streamingSyncPromise = undefined;
298
+ this.abortController = null;
299
+ this.updateSyncStatus({ connected: false, connecting: false });
300
+ }
301
+ /**
302
+ * @deprecated use [connect instead]
303
+ */
304
+ async streamingSync(signal, options) {
305
+ if (!signal) {
306
+ this.abortController = new AbortController();
307
+ signal = this.abortController.signal;
308
+ }
309
+ /**
310
+ * Listen for CRUD updates and trigger upstream uploads
311
+ */
312
+ this.crudUpdateListener = this.options.adapter.registerListener({
313
+ crudUpdate: () => this.triggerCrudUpload()
314
+ });
315
+ /**
316
+ * Create a new abort controller which aborts items downstream.
317
+ * This is needed to close any previous connections on exception.
318
+ */
319
+ let nestedAbortController = new AbortController();
320
+ signal.addEventListener('abort', () => {
321
+ /**
322
+ * A request for disconnect was received upstream. Relay the request
323
+ * to the nested abort controller.
324
+ */
325
+ nestedAbortController.abort(signal?.reason ?? new AbortOperation('Received command to disconnect from upstream'));
326
+ this.crudUpdateListener?.();
327
+ this.crudUpdateListener = undefined;
328
+ this.updateSyncStatus({
329
+ connected: false,
330
+ connecting: false,
331
+ dataFlow: {
332
+ downloading: false,
333
+ downloadProgress: null
334
+ }
335
+ });
336
+ });
337
+ /**
338
+ * This loops runs until [retry] is false or the abort signal is set to aborted.
339
+ * Aborting the nestedAbortController will:
340
+ * - Abort any pending fetch requests
341
+ * - Close any sync stream ReadableStreams (which will also close any established network requests)
342
+ */
343
+ while (true) {
344
+ this.updateSyncStatus({ connecting: true });
345
+ let shouldDelayRetry = true;
346
+ let result = null;
347
+ try {
348
+ if (signal?.aborted) {
349
+ break;
350
+ }
351
+ result = await this.streamingSyncIteration(nestedAbortController.signal, options);
352
+ // Continue immediately, streamingSyncIteration will wait before completing if necessary.
353
+ }
354
+ catch (ex) {
355
+ /**
356
+ * Either:
357
+ * - A network request failed with a failed connection or not OKAY response code.
358
+ * - There was a sync processing error.
359
+ * - The connection was aborted.
360
+ * This loop will retry after a delay if the connection was not aborted.
361
+ * The nested abort controller will cleanup any open network requests and streams.
362
+ * The WebRemote should only abort pending fetch requests or close active Readable streams.
363
+ */
364
+ if (ex instanceof AbortOperation) {
365
+ this.logger.warn(ex);
366
+ shouldDelayRetry = false;
367
+ // A disconnect was requested, we should not delay since there is no explicit retry
368
+ }
369
+ else {
370
+ this.logger.error(ex);
371
+ }
372
+ this.updateSyncStatus({
373
+ dataFlow: {
374
+ downloadError: ex
375
+ }
376
+ });
377
+ }
378
+ finally {
379
+ this.notifyCompletedUploads = undefined;
380
+ if (!signal.aborted) {
381
+ nestedAbortController.abort(new AbortOperation('Closing sync stream network requests before retry.'));
382
+ nestedAbortController = new AbortController();
383
+ }
384
+ if (result?.immediateRestart != true) {
385
+ this.updateSyncStatus({
386
+ connected: false,
387
+ connecting: true // May be unnecessary
388
+ });
389
+ // On error, wait a little before retrying
390
+ if (shouldDelayRetry) {
391
+ await this.delayRetry(nestedAbortController.signal);
392
+ }
393
+ }
394
+ }
395
+ }
396
+ // Mark as disconnected if here
397
+ this.updateSyncStatus({ connected: false, connecting: false });
398
+ }
399
+ async collectLocalBucketState() {
400
+ const bucketEntries = await this.options.adapter.getBucketStates();
401
+ const req = bucketEntries.map((entry) => ({
402
+ name: entry.bucket,
403
+ after: entry.op_id
404
+ }));
405
+ const localDescriptions = new Map();
406
+ for (const entry of bucketEntries) {
407
+ localDescriptions.set(entry.bucket, null);
408
+ }
409
+ return [req, localDescriptions];
410
+ }
411
+ /**
412
+ * Older versions of the JS SDK used to encode subkeys as JSON in {@link OplogEntry.toJSON}.
413
+ * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
414
+ * While this is not a problem as long as it's done consistently, it causes issues when a database
415
+ * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
416
+ * is enabled.
417
+ *
418
+ * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
419
+ * migration is only triggered when necessary (for now). The function returns whether the new format
420
+ * should be used, so that the JS SDK is able to write to updated databases.
421
+ *
422
+ * @param requireFixedKeyFormat Whether we require the new format or also support the old one.
423
+ * The Rust client requires the new subkey format.
424
+ * @returns Whether the database is now using the new, fixed subkey format.
425
+ */
426
+ async requireKeyFormat(requireFixedKeyFormat) {
427
+ const hasMigrated = await this.options.adapter.hasMigratedSubkeys();
428
+ if (requireFixedKeyFormat && !hasMigrated) {
429
+ await this.options.adapter.migrateToFixedSubkeys();
430
+ return true;
431
+ }
432
+ else {
433
+ return hasMigrated;
434
+ }
435
+ }
436
+ streamingSyncIteration(signal, options) {
437
+ return this.obtainLock({
438
+ type: LockType.SYNC,
439
+ signal,
440
+ callback: async () => {
441
+ const resolvedOptions = {
442
+ ...DEFAULT_STREAM_CONNECTION_OPTIONS,
443
+ ...(options ?? {})
444
+ };
445
+ // Validate app metadata
446
+ const invalidMetadata = Object.entries(resolvedOptions.appMetadata).filter(([_, value]) => typeof value != 'string');
447
+ if (invalidMetadata.length > 0) {
448
+ throw new Error(`Invalid appMetadata provided. Only string values are allowed. Invalid values: ${invalidMetadata.map(([key, value]) => `${key}: ${value}`).join(', ')}`);
449
+ }
450
+ const clientImplementation = resolvedOptions.clientImplementation;
451
+ this.updateSyncStatus({ clientImplementation });
452
+ if (clientImplementation == SyncClientImplementation.JAVASCRIPT) {
453
+ await this.legacyStreamingSyncIteration(signal, resolvedOptions);
454
+ return null;
455
+ }
456
+ else {
457
+ await this.requireKeyFormat(true);
458
+ return await this.rustSyncIteration(signal, resolvedOptions);
459
+ }
460
+ }
461
+ });
462
+ }
463
+ async legacyStreamingSyncIteration(signal, resolvedOptions) {
464
+ const rawTables = resolvedOptions.serializedSchema?.raw_tables;
465
+ if (rawTables != null && rawTables.length) {
466
+ this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
467
+ }
468
+ if (this.activeStreams.length) {
469
+ this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
470
+ }
471
+ this.logger.debug('Streaming sync iteration started');
472
+ this.options.adapter.startSession();
473
+ let [req, bucketMap] = await this.collectLocalBucketState();
474
+ let targetCheckpoint = null;
475
+ // A checkpoint that has been validated but not applied (e.g. due to pending local writes)
476
+ let pendingValidatedCheckpoint = null;
477
+ const clientId = await this.options.adapter.getClientId();
478
+ const usingFixedKeyFormat = await this.requireKeyFormat(false);
479
+ this.logger.debug('Requesting stream from server');
480
+ const syncOptions = {
481
+ path: '/sync/stream',
482
+ abortSignal: signal,
483
+ data: {
484
+ buckets: req,
485
+ include_checksum: true,
486
+ raw_data: true,
487
+ parameters: resolvedOptions.params,
488
+ app_metadata: resolvedOptions.appMetadata,
489
+ client_id: clientId
490
+ }
491
+ };
492
+ let stream;
493
+ if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {
494
+ stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {
495
+ if (typeof line == 'string') {
496
+ return JSON.parse(line);
497
+ }
498
+ else {
499
+ // Directly enqueued by us
500
+ return line;
501
+ }
502
+ });
503
+ }
504
+ else {
505
+ const bson = await this.options.remote.getBSON();
506
+ stream = await this.options.remote.socketStreamRaw({
507
+ ...syncOptions,
508
+ ...{ fetchStrategy: resolvedOptions.fetchStrategy }
509
+ }, (payload) => {
510
+ if (payload instanceof Uint8Array) {
511
+ return bson.deserialize(payload);
512
+ }
513
+ else {
514
+ // Directly enqueued by us
515
+ return payload;
516
+ }
517
+ }, bson);
518
+ }
519
+ this.logger.debug('Stream established. Processing events');
520
+ this.notifyCompletedUploads = () => {
521
+ if (!stream.closed) {
522
+ stream.enqueueData({ crud_upload_completed: null });
523
+ }
524
+ };
525
+ while (!stream.closed) {
526
+ const line = await stream.read();
527
+ if (!line) {
528
+ // The stream has closed while waiting
529
+ return;
530
+ }
531
+ if ('crud_upload_completed' in line) {
532
+ if (pendingValidatedCheckpoint != null) {
533
+ const { applied, endIteration } = await this.applyCheckpoint(pendingValidatedCheckpoint);
534
+ if (applied) {
535
+ pendingValidatedCheckpoint = null;
536
+ }
537
+ else if (endIteration) {
538
+ break;
539
+ }
540
+ }
541
+ continue;
542
+ }
543
+ // A connection is active and messages are being received
544
+ if (!this.syncStatus.connected) {
545
+ // There is a connection now
546
+ Promise.resolve().then(() => this.triggerCrudUpload());
547
+ this.updateSyncStatus({
548
+ connected: true
549
+ });
550
+ }
551
+ if (isStreamingSyncCheckpoint(line)) {
552
+ targetCheckpoint = line.checkpoint;
553
+ // New checkpoint - existing validated checkpoint is no longer valid
554
+ pendingValidatedCheckpoint = null;
555
+ const bucketsToDelete = new Set(bucketMap.keys());
556
+ const newBuckets = new Map();
557
+ for (const checksum of line.checkpoint.buckets) {
558
+ newBuckets.set(checksum.bucket, {
559
+ name: checksum.bucket,
560
+ priority: checksum.priority ?? FALLBACK_PRIORITY
561
+ });
562
+ bucketsToDelete.delete(checksum.bucket);
563
+ }
564
+ if (bucketsToDelete.size > 0) {
565
+ this.logger.debug('Removing buckets', [...bucketsToDelete]);
566
+ }
567
+ bucketMap = newBuckets;
568
+ await this.options.adapter.removeBuckets([...bucketsToDelete]);
569
+ await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
570
+ await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
571
+ }
572
+ else if (isStreamingSyncCheckpointComplete(line)) {
573
+ const result = await this.applyCheckpoint(targetCheckpoint);
574
+ if (result.endIteration) {
575
+ return;
576
+ }
577
+ else if (!result.applied) {
578
+ // "Could not apply checkpoint due to local data". We need to retry after
579
+ // finishing uploads.
580
+ pendingValidatedCheckpoint = targetCheckpoint;
581
+ }
582
+ else {
583
+ // Nothing to retry later. This would likely already be null from the last
584
+ // checksum or checksum_diff operation, but we make sure.
585
+ pendingValidatedCheckpoint = null;
586
+ }
587
+ }
588
+ else if (isStreamingSyncCheckpointPartiallyComplete(line)) {
589
+ const priority = line.partial_checkpoint_complete.priority;
590
+ this.logger.debug('Partial checkpoint complete', priority);
591
+ const result = await this.options.adapter.syncLocalDatabase(targetCheckpoint, priority);
592
+ if (!result.checkpointValid) {
593
+ // This means checksums failed. Start again with a new checkpoint.
594
+ // TODO: better back-off
595
+ await new Promise((resolve) => setTimeout(resolve, 50));
596
+ return;
597
+ }
598
+ else if (!result.ready) {
599
+ // If we have pending uploads, we can't complete new checkpoints outside of priority 0.
600
+ // We'll resolve this for a complete checkpoint.
601
+ }
602
+ else {
603
+ // We'll keep on downloading, but can report that this priority is synced now.
604
+ this.logger.debug('partial checkpoint validation succeeded');
605
+ // All states with a higher priority can be deleted since this partial sync includes them.
606
+ const priorityStates = this.syncStatus.priorityStatusEntries.filter((s) => s.priority <= priority);
607
+ priorityStates.push({
608
+ priority,
609
+ lastSyncedAt: new Date(),
610
+ hasSynced: true
611
+ });
612
+ this.updateSyncStatus({
613
+ connected: true,
614
+ priorityStatusEntries: priorityStates
615
+ });
616
+ }
617
+ }
618
+ else if (isStreamingSyncCheckpointDiff(line)) {
619
+ // TODO: It may be faster to just keep track of the diff, instead of the entire checkpoint
620
+ if (targetCheckpoint == null) {
621
+ throw new Error('Checkpoint diff without previous checkpoint');
622
+ }
623
+ // New checkpoint - existing validated checkpoint is no longer valid
624
+ pendingValidatedCheckpoint = null;
625
+ const diff = line.checkpoint_diff;
626
+ const newBuckets = new Map();
627
+ for (const checksum of targetCheckpoint.buckets) {
628
+ newBuckets.set(checksum.bucket, checksum);
629
+ }
630
+ for (const checksum of diff.updated_buckets) {
631
+ newBuckets.set(checksum.bucket, checksum);
632
+ }
633
+ for (const bucket of diff.removed_buckets) {
634
+ newBuckets.delete(bucket);
635
+ }
636
+ const newCheckpoint = {
637
+ last_op_id: diff.last_op_id,
638
+ buckets: [...newBuckets.values()],
639
+ write_checkpoint: diff.write_checkpoint
640
+ };
641
+ targetCheckpoint = newCheckpoint;
642
+ await this.updateSyncStatusForStartingCheckpoint(targetCheckpoint);
643
+ bucketMap = new Map();
644
+ newBuckets.forEach((checksum, name) => bucketMap.set(name, {
645
+ name: checksum.bucket,
646
+ priority: checksum.priority ?? FALLBACK_PRIORITY
647
+ }));
648
+ const bucketsToDelete = diff.removed_buckets;
649
+ if (bucketsToDelete.length > 0) {
650
+ this.logger.debug('Remove buckets', bucketsToDelete);
651
+ }
652
+ await this.options.adapter.removeBuckets(bucketsToDelete);
653
+ await this.options.adapter.setTargetCheckpoint(targetCheckpoint);
654
+ }
655
+ else if (isStreamingSyncData(line)) {
656
+ const { data } = line;
657
+ const previousProgress = this.syncStatus.dataFlowStatus.downloadProgress;
658
+ let updatedProgress = null;
659
+ if (previousProgress) {
660
+ updatedProgress = { ...previousProgress };
661
+ const progressForBucket = updatedProgress[data.bucket];
662
+ if (progressForBucket) {
663
+ updatedProgress[data.bucket] = {
664
+ ...progressForBucket,
665
+ since_last: progressForBucket.since_last + data.data.length
666
+ };
667
+ }
668
+ }
669
+ this.updateSyncStatus({
670
+ dataFlow: {
671
+ downloading: true,
672
+ downloadProgress: updatedProgress
673
+ }
674
+ });
675
+ await this.options.adapter.saveSyncData({ buckets: [SyncDataBucket.fromRow(data)] }, usingFixedKeyFormat);
676
+ }
677
+ else if (isStreamingKeepalive(line)) {
678
+ const remaining_seconds = line.token_expires_in;
679
+ if (remaining_seconds == 0) {
680
+ // Connection would be closed automatically right after this
681
+ this.logger.debug('Token expiring; reconnect');
682
+ /**
683
+ * For a rare case where the backend connector does not update the token
684
+ * (uses the same one), this should have some delay.
685
+ */
686
+ await this.delayRetry();
687
+ return;
688
+ }
689
+ else if (remaining_seconds < 30) {
690
+ this.logger.debug('Token will expire soon; reconnect');
691
+ // Pre-emptively refresh the token
692
+ this.options.remote.invalidateCredentials();
693
+ return;
694
+ }
695
+ this.triggerCrudUpload();
696
+ }
697
+ else {
698
+ this.logger.debug('Received unknown sync line', line);
699
+ }
700
+ }
701
+ this.logger.debug('Stream input empty');
702
+ // Connection closed. Likely due to auth issue.
703
+ return;
704
+ }
705
+ async rustSyncIteration(signal, resolvedOptions) {
706
+ const syncImplementation = this;
707
+ const adapter = this.options.adapter;
708
+ const remote = this.options.remote;
709
+ let receivingLines = null;
710
+ let hadSyncLine = false;
711
+ let hideDisconnectOnRestart = false;
712
+ if (signal.aborted) {
713
+ throw new AbortOperation('Connection request has been aborted');
714
+ }
715
+ const abortController = new AbortController();
716
+ signal.addEventListener('abort', () => abortController.abort());
717
+ // Pending sync lines received from the service, as well as local events that trigger a powersync_control
718
+ // invocation (local events include refreshed tokens and completed uploads).
719
+ // This is a single data stream so that we can handle all control calls from a single place.
720
+ let controlInvocations = null;
721
+ async function connect(instr) {
722
+ const syncOptions = {
723
+ path: '/sync/stream',
724
+ abortSignal: abortController.signal,
725
+ data: instr.request
726
+ };
727
+ if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {
728
+ controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {
729
+ if (typeof line == 'string') {
730
+ return {
731
+ command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
732
+ payload: line
733
+ };
734
+ }
735
+ else {
736
+ // Directly enqueued by us
737
+ return line;
738
+ }
739
+ });
740
+ }
741
+ else {
742
+ controlInvocations = await remote.socketStreamRaw({
743
+ ...syncOptions,
744
+ fetchStrategy: resolvedOptions.fetchStrategy
745
+ }, (payload) => {
746
+ if (payload instanceof Uint8Array) {
747
+ return {
748
+ command: PowerSyncControlCommand.PROCESS_BSON_LINE,
749
+ payload: payload
750
+ };
751
+ }
752
+ else {
753
+ // Directly enqueued by us
754
+ return payload;
755
+ }
756
+ });
757
+ }
758
+ // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
759
+ // we're already connected here and can report that.
760
+ syncImplementation.updateSyncStatus({ connected: true });
761
+ try {
762
+ while (!controlInvocations.closed) {
763
+ const line = await controlInvocations.read();
764
+ if (line == null) {
765
+ return;
766
+ }
767
+ await control(line.command, line.payload);
768
+ if (!hadSyncLine) {
769
+ syncImplementation.triggerCrudUpload();
770
+ hadSyncLine = true;
771
+ }
772
+ }
773
+ }
774
+ finally {
775
+ const activeInstructions = controlInvocations;
776
+ // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is
777
+ // refreshed. That would throw after closing (and we can't handle those events either way), so set this back
778
+ // to null.
779
+ controlInvocations = null;
780
+ await activeInstructions.close();
781
+ }
782
+ }
783
+ async function stop() {
784
+ await control(PowerSyncControlCommand.STOP);
785
+ }
786
+ async function control(op, payload) {
787
+ const rawResponse = await adapter.control(op, payload ?? null);
788
+ const logger = syncImplementation.logger;
789
+ logger.trace('powersync_control', op, payload == null || typeof payload == 'string' ? payload : '<bytes>', rawResponse);
790
+ await handleInstructions(JSON.parse(rawResponse));
791
+ }
792
+ async function handleInstruction(instruction) {
793
+ if ('LogLine' in instruction) {
794
+ switch (instruction.LogLine.severity) {
795
+ case 'DEBUG':
796
+ syncImplementation.logger.debug(instruction.LogLine.line);
797
+ break;
798
+ case 'INFO':
799
+ syncImplementation.logger.info(instruction.LogLine.line);
800
+ break;
801
+ case 'WARNING':
802
+ syncImplementation.logger.warn(instruction.LogLine.line);
803
+ break;
804
+ }
805
+ }
806
+ else if ('UpdateSyncStatus' in instruction) {
807
+ syncImplementation.updateSyncStatus(coreStatusToJs(instruction.UpdateSyncStatus.status));
808
+ }
809
+ else if ('EstablishSyncStream' in instruction) {
810
+ if (receivingLines != null) {
811
+ // Already connected, this shouldn't happen during a single iteration.
812
+ throw 'Unexpected request to establish sync stream, already connected';
813
+ }
814
+ receivingLines = connect(instruction.EstablishSyncStream);
815
+ }
816
+ else if ('FetchCredentials' in instruction) {
817
+ if (instruction.FetchCredentials.did_expire) {
818
+ remote.invalidateCredentials();
819
+ }
820
+ else {
821
+ remote.invalidateCredentials();
822
+ // Restart iteration after the credentials have been refreshed.
823
+ remote.fetchCredentials().then((_) => {
824
+ controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
825
+ }, (err) => {
826
+ syncImplementation.logger.warn('Could not prefetch credentials', err);
827
+ });
828
+ }
829
+ }
830
+ else if ('CloseSyncStream' in instruction) {
831
+ abortController.abort();
832
+ hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
833
+ }
834
+ else if ('FlushFileSystem' in instruction) {
835
+ // Not necessary on JS platforms.
836
+ }
837
+ else if ('DidCompleteSync' in instruction) {
838
+ syncImplementation.updateSyncStatus({
839
+ dataFlow: {
840
+ downloadError: undefined
841
+ }
842
+ });
843
+ }
844
+ }
845
+ async function handleInstructions(instructions) {
846
+ for (const instr of instructions) {
847
+ await handleInstruction(instr);
848
+ }
849
+ }
850
+ try {
851
+ const options = {
852
+ parameters: resolvedOptions.params,
853
+ app_metadata: resolvedOptions.appMetadata,
854
+ active_streams: this.activeStreams,
855
+ include_defaults: resolvedOptions.includeDefaultStreams
856
+ };
857
+ if (resolvedOptions.serializedSchema) {
858
+ options.schema = resolvedOptions.serializedSchema;
859
+ }
860
+ await control(PowerSyncControlCommand.START, JSON.stringify(options));
861
+ this.notifyCompletedUploads = () => {
862
+ if (controlInvocations && !controlInvocations?.closed) {
863
+ controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
864
+ }
865
+ };
866
+ this.handleActiveStreamsChange = () => {
867
+ if (controlInvocations && !controlInvocations?.closed) {
868
+ controlInvocations.enqueueData({
869
+ command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
870
+ payload: JSON.stringify(this.activeStreams)
871
+ });
872
+ }
873
+ };
874
+ await receivingLines;
875
+ }
876
+ finally {
877
+ this.notifyCompletedUploads = this.handleActiveStreamsChange = undefined;
878
+ await stop();
879
+ }
880
+ return { immediateRestart: hideDisconnectOnRestart };
881
+ }
882
+ async updateSyncStatusForStartingCheckpoint(checkpoint) {
883
+ const localProgress = await this.options.adapter.getBucketOperationProgress();
884
+ const progress = {};
885
+ let invalidated = false;
886
+ for (const bucket of checkpoint.buckets) {
887
+ const savedProgress = localProgress[bucket.bucket];
888
+ const atLast = savedProgress?.atLast ?? 0;
889
+ const sinceLast = savedProgress?.sinceLast ?? 0;
890
+ progress[bucket.bucket] = {
891
+ // The fallback priority doesn't matter here, but 3 is the one newer versions of the sync service
892
+ // will use by default.
893
+ priority: bucket.priority ?? 3,
894
+ at_last: atLast,
895
+ since_last: sinceLast,
896
+ target_count: bucket.count ?? 0
897
+ };
898
+ if (bucket.count != null && bucket.count < atLast + sinceLast) {
899
+ // Either due to a defrag / sync rule deploy or a compaction operation, the size
900
+ // of the bucket shrank so much that the local ops exceed the ops in the updated
901
+ // bucket. We can't prossibly report progress in this case (it would overshoot 100%).
902
+ invalidated = true;
903
+ }
904
+ }
905
+ if (invalidated) {
906
+ for (const bucket in progress) {
907
+ const bucketProgress = progress[bucket];
908
+ bucketProgress.at_last = 0;
909
+ bucketProgress.since_last = 0;
910
+ }
911
+ }
912
+ this.updateSyncStatus({
913
+ dataFlow: {
914
+ downloading: true,
915
+ downloadProgress: progress
916
+ }
917
+ });
918
+ }
919
+ async applyCheckpoint(checkpoint) {
920
+ let result = await this.options.adapter.syncLocalDatabase(checkpoint);
921
+ if (!result.checkpointValid) {
922
+ this.logger.debug(`Checksum mismatch in checkpoint ${checkpoint.last_op_id}, will reconnect`);
923
+ // This means checksums failed. Start again with a new checkpoint.
924
+ // TODO: better back-off
925
+ await new Promise((resolve) => setTimeout(resolve, 50));
926
+ return { applied: false, endIteration: true };
927
+ }
928
+ else if (!result.ready) {
929
+ this.logger.debug(`Could not apply checkpoint ${checkpoint.last_op_id} due to local data. We will retry applying the checkpoint after that upload is completed.`);
930
+ return { applied: false, endIteration: false };
931
+ }
932
+ this.logger.debug(`Applied checkpoint ${checkpoint.last_op_id}`, checkpoint);
933
+ this.updateSyncStatus({
934
+ connected: true,
935
+ lastSyncedAt: new Date(),
936
+ dataFlow: {
937
+ downloading: false,
938
+ downloadProgress: null,
939
+ downloadError: undefined
940
+ }
941
+ });
942
+ return { applied: true, endIteration: false };
943
+ }
944
+ updateSyncStatus(options) {
945
+ const updatedStatus = new SyncStatus({
946
+ connected: options.connected ?? this.syncStatus.connected,
947
+ connecting: !options.connected && (options.connecting ?? this.syncStatus.connecting),
948
+ lastSyncedAt: options.lastSyncedAt ?? this.syncStatus.lastSyncedAt,
949
+ dataFlow: {
950
+ ...this.syncStatus.dataFlowStatus,
951
+ ...options.dataFlow
952
+ },
953
+ priorityStatusEntries: options.priorityStatusEntries ?? this.syncStatus.priorityStatusEntries,
954
+ clientImplementation: options.clientImplementation ?? this.syncStatus.clientImplementation
955
+ });
956
+ if (!this.syncStatus.isEqual(updatedStatus)) {
957
+ this.syncStatus = updatedStatus;
958
+ // Only trigger this is there was a change
959
+ this.iterateListeners((cb) => cb.statusChanged?.(updatedStatus));
960
+ }
961
+ // trigger this for all updates
962
+ this.iterateListeners((cb) => cb.statusUpdated?.(options));
963
+ }
964
+ async delayRetry(signal) {
965
+ return new Promise((resolve) => {
966
+ if (signal?.aborted) {
967
+ // If the signal is already aborted, resolve immediately
968
+ resolve();
969
+ return;
970
+ }
971
+ const { retryDelayMs } = this.options;
972
+ let timeoutId;
973
+ const endDelay = () => {
974
+ resolve();
975
+ if (timeoutId) {
976
+ clearTimeout(timeoutId);
977
+ timeoutId = undefined;
978
+ }
979
+ signal?.removeEventListener('abort', endDelay);
980
+ };
981
+ signal?.addEventListener('abort', endDelay, { once: true });
982
+ timeoutId = setTimeout(endDelay, retryDelayMs);
983
+ });
984
+ }
985
+ updateSubscriptions(subscriptions) {
986
+ this.activeStreams = subscriptions;
987
+ this.handleActiveStreamsChange?.();
988
+ }
989
+ }
990
+ //# sourceMappingURL=AbstractStreamingSyncImplementation.js.map