@powersync/shared-internals 0.0.0-dev-20260827080125

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 (152) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/websockets.mjs +7558 -0
  4. package/dist/websockets.mjs.map +1 -0
  5. package/dist/websockets.node.mjs +5189 -0
  6. package/dist/websockets.node.mjs.map +1 -0
  7. package/legacy/sync_protocol.d.ts +103 -0
  8. package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
  9. package/lib/client/BasePowerSyncDatabase.js +654 -0
  10. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  11. package/lib/client/ConnectionManager.d.ts +120 -0
  12. package/lib/client/ConnectionManager.js +324 -0
  13. package/lib/client/ConnectionManager.js.map +1 -0
  14. package/lib/client/CustomQuery.d.ts +21 -0
  15. package/lib/client/CustomQuery.js +43 -0
  16. package/lib/client/CustomQuery.js.map +1 -0
  17. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  18. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  19. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  20. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
  21. package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
  22. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  23. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  24. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  25. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  26. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
  27. package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
  28. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  29. package/lib/client/sync/options.d.ts +9 -0
  30. package/lib/client/sync/options.js +17 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
  33. package/lib/client/sync/stream/AbstractRemote.js +270 -0
  34. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  35. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
  36. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
  37. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  38. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  39. package/lib/client/sync/stream/CheckpointState.js +106 -0
  40. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  41. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  42. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  43. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  44. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  45. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  46. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  47. package/lib/client/sync/stream/core-instruction.d.ts +81 -0
  48. package/lib/client/sync/stream/core-instruction.js +4 -0
  49. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  50. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  51. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  52. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  53. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  54. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  55. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  56. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  57. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  58. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  59. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  60. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  61. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  63. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  64. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  66. package/lib/client/watched/WatchedQuery.js +12 -0
  67. package/lib/client/watched/WatchedQuery.js.map +1 -0
  68. package/lib/constants.d.ts +5 -0
  69. package/lib/constants.js +6 -0
  70. package/lib/constants.js.map +1 -0
  71. package/lib/db/ConnectionClosedError.d.ts +12 -0
  72. package/lib/db/ConnectionClosedError.js +23 -0
  73. package/lib/db/ConnectionClosedError.js.map +1 -0
  74. package/lib/db/crud/SyncProgress.d.ts +10 -0
  75. package/lib/db/crud/SyncProgress.js +33 -0
  76. package/lib/db/crud/SyncProgress.js.map +1 -0
  77. package/lib/db/crud/SyncStatus.d.ts +48 -0
  78. package/lib/db/crud/SyncStatus.js +178 -0
  79. package/lib/db/crud/SyncStatus.js.map +1 -0
  80. package/lib/db/openDatabase.d.ts +7 -0
  81. package/lib/db/openDatabase.js +22 -0
  82. package/lib/db/openDatabase.js.map +1 -0
  83. package/lib/index.d.ts +22 -0
  84. package/lib/index.js +22 -0
  85. package/lib/index.js.map +1 -0
  86. package/lib/utils/AbortOperation.d.ts +11 -0
  87. package/lib/utils/AbortOperation.js +21 -0
  88. package/lib/utils/AbortOperation.js.map +1 -0
  89. package/lib/utils/ControlledExecutor.d.ts +31 -0
  90. package/lib/utils/ControlledExecutor.js +58 -0
  91. package/lib/utils/ControlledExecutor.js.map +1 -0
  92. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  93. package/lib/utils/MetaBaseObserver.js +51 -0
  94. package/lib/utils/MetaBaseObserver.js.map +1 -0
  95. package/lib/utils/async.d.ts +46 -0
  96. package/lib/utils/async.js +147 -0
  97. package/lib/utils/async.js.map +1 -0
  98. package/lib/utils/compatibility.d.ts +8 -0
  99. package/lib/utils/compatibility.js +9 -0
  100. package/lib/utils/compatibility.js.map +1 -0
  101. package/lib/utils/mutex.d.ts +42 -0
  102. package/lib/utils/mutex.js +150 -0
  103. package/lib/utils/mutex.js.map +1 -0
  104. package/lib/utils/parseQuery.d.ts +12 -0
  105. package/lib/utils/parseQuery.js +20 -0
  106. package/lib/utils/parseQuery.js.map +1 -0
  107. package/lib/utils/queue.d.ts +16 -0
  108. package/lib/utils/queue.js +42 -0
  109. package/lib/utils/queue.js.map +1 -0
  110. package/lib/utils/stream_transform.d.ts +42 -0
  111. package/lib/utils/stream_transform.js +227 -0
  112. package/lib/utils/stream_transform.js.map +1 -0
  113. package/lib/version.d.ts +1 -0
  114. package/lib/version.js +4 -0
  115. package/lib/version.js.map +1 -0
  116. package/package.json +68 -0
  117. package/src/client/BasePowerSyncDatabase.ts +898 -0
  118. package/src/client/ConnectionManager.ts +441 -0
  119. package/src/client/CustomQuery.ts +60 -0
  120. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  121. package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
  122. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  123. package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
  124. package/src/client/sync/options.ts +25 -0
  125. package/src/client/sync/stream/AbstractRemote.ts +388 -0
  126. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
  127. package/src/client/sync/stream/CheckpointState.ts +136 -0
  128. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  129. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  130. package/src/client/sync/stream/core-instruction.ts +85 -0
  131. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  132. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  133. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  134. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  135. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  136. package/src/client/watched/WatchedQuery.ts +14 -0
  137. package/src/constants.ts +6 -0
  138. package/src/db/ConnectionClosedError.ts +25 -0
  139. package/src/db/crud/SyncProgress.ts +39 -0
  140. package/src/db/crud/SyncStatus.ts +234 -0
  141. package/src/db/openDatabase.ts +23 -0
  142. package/src/index.ts +24 -0
  143. package/src/utils/AbortOperation.ts +19 -0
  144. package/src/utils/ControlledExecutor.ts +81 -0
  145. package/src/utils/MetaBaseObserver.ts +65 -0
  146. package/src/utils/async.ts +185 -0
  147. package/src/utils/compatibility.ts +9 -0
  148. package/src/utils/mutex.ts +186 -0
  149. package/src/utils/parseQuery.ts +31 -0
  150. package/src/utils/queue.ts +48 -0
  151. package/src/utils/stream_transform.ts +276 -0
  152. package/src/version.ts +3 -0
@@ -0,0 +1,270 @@
1
+ import { FetchStrategy, LogLevels } from '@powersync/common';
2
+ import { AbortOperation } from '../../../utils/AbortOperation.js';
3
+ import { doneResult, extractBsonObjects, extractJsonLines } from '../../../utils/stream_transform.js';
4
+ import { EventQueue } from '../../../utils/async.js';
5
+ import { POWERSYNC_JS_VERSION } from '../../../version.js';
6
+ const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
7
+ const webSocketPlatform = {
8
+ LogLevels,
9
+ EventQueue,
10
+ AbortOperation
11
+ };
12
+ export function lazyFetchImplementation(getFetch) {
13
+ let resolved;
14
+ return (request) => {
15
+ const fetch = (resolved ??= getFetch());
16
+ return fetch(request);
17
+ };
18
+ }
19
+ /**
20
+ * @internal
21
+ */
22
+ export class AbstractRemote {
23
+ connector;
24
+ logger;
25
+ credentials = null;
26
+ constructor(connector, logger) {
27
+ this.connector = connector;
28
+ this.logger = logger;
29
+ }
30
+ /**
31
+ * Get credentials currently cached, or fetch new credentials if none are
32
+ * available.
33
+ *
34
+ * These credentials may have expired already.
35
+ */
36
+ async getCredentials() {
37
+ if (this.credentials) {
38
+ return this.credentials;
39
+ }
40
+ return this.prefetchCredentials();
41
+ }
42
+ /**
43
+ * Fetch a new set of credentials and cache it.
44
+ *
45
+ * Until this call succeeds, `getCredentials` will still return the
46
+ * old credentials.
47
+ *
48
+ * This may be called before the current credentials have expired.
49
+ */
50
+ async prefetchCredentials() {
51
+ this.credentials = await this.fetchCredentials();
52
+ return this.credentials;
53
+ }
54
+ /**
55
+ * Get credentials for PowerSync.
56
+ *
57
+ * This should always fetch a fresh set of credentials - don't use cached
58
+ * values.
59
+ */
60
+ async fetchCredentials() {
61
+ const credentials = await this.connector.fetchCredentials();
62
+ if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
63
+ throw new Error(`A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`);
64
+ }
65
+ return credentials;
66
+ }
67
+ /***
68
+ * Immediately invalidate credentials.
69
+ *
70
+ * This may be called when the current credentials have expired.
71
+ */
72
+ invalidateCredentials() {
73
+ this.credentials = null;
74
+ this.connector.invalidateCredentials?.();
75
+ }
76
+ getUserAgent() {
77
+ return `powersync-js/${POWERSYNC_JS_VERSION}`;
78
+ }
79
+ async buildRequest(path) {
80
+ const credentials = await this.getCredentials();
81
+ if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
82
+ throw new Error('PowerSync endpoint not configured');
83
+ }
84
+ else if (credentials?.token == null || credentials?.token == '') {
85
+ const error = new Error(`Not signed in`);
86
+ error.status = 401;
87
+ throw error;
88
+ }
89
+ const userAgent = this.getUserAgent();
90
+ return {
91
+ url: credentials.endpoint + path,
92
+ headers: {
93
+ 'content-type': 'application/json',
94
+ Authorization: `Token ${credentials.token}`,
95
+ 'x-user-agent': userAgent
96
+ },
97
+ userAgent,
98
+ path
99
+ };
100
+ }
101
+ async fetchAndDecodeJson({ path, method = 'GET', headers, body, signal }) {
102
+ const request = await this.buildRequest(path);
103
+ const res = await this.fetch({
104
+ resource: request.url,
105
+ request: {
106
+ method,
107
+ headers: {
108
+ ...headers,
109
+ ...request.headers
110
+ },
111
+ body,
112
+ signal
113
+ },
114
+ expectStreamingResponse: false
115
+ });
116
+ if (res.status === 401) {
117
+ this.invalidateCredentials();
118
+ }
119
+ if (!res.ok) {
120
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
121
+ }
122
+ return res.json();
123
+ }
124
+ /**
125
+ * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
126
+ * builtin, without forcing us to bundle a polyfill with `@powersync/common`.
127
+ */
128
+ createTextDecoder() {
129
+ return new TextDecoder();
130
+ }
131
+ createSocket(url) {
132
+ return new WebSocket(url);
133
+ }
134
+ /**
135
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
136
+ *
137
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
138
+ */
139
+ async socketStreamRaw(options) {
140
+ const support = await this.loadWebSocketSupport(webSocketPlatform);
141
+ const request = await this.buildRequest(options.path);
142
+ request.url = request.url.replace(/^https?:\/\//, function (match) {
143
+ return match === 'https://' ? 'wss://' : 'ws://';
144
+ });
145
+ const { fetchStrategy = FetchStrategy.Buffered, abortSignal, data } = options;
146
+ return await support.webSocketSyncStream({
147
+ remote: this,
148
+ buffered: fetchStrategy == FetchStrategy.Buffered,
149
+ abortSignal,
150
+ requestPayload: data,
151
+ request
152
+ });
153
+ }
154
+ /**
155
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
156
+ * async iterator of byte blobs.
157
+ *
158
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
159
+ */
160
+ async fetchStreamRaw(options) {
161
+ const { data, path, abortSignal } = options;
162
+ const request = await this.buildRequest(path);
163
+ /**
164
+ * This abort controller will abort pending fetch requests.
165
+ * If the request has resolved, it will be used to close the readable stream.
166
+ * Which will cancel the network request.
167
+ *
168
+ * This nested controller is required since:
169
+ * Aborting the active fetch request while it is being consumed seems to throw
170
+ * an unhandled exception on the window level.
171
+ */
172
+ if (abortSignal.aborted) {
173
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
174
+ }
175
+ const controller = new AbortController();
176
+ let reader = null;
177
+ abortSignal.addEventListener('abort', () => {
178
+ const reason = abortSignal.reason ??
179
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
180
+ if (reader == null) {
181
+ // Only abort via the abort controller if the request has not resolved yet
182
+ controller.abort(reason);
183
+ }
184
+ else {
185
+ reader.cancel(reason).catch(() => {
186
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
187
+ // ignore it here.
188
+ });
189
+ }
190
+ });
191
+ let res;
192
+ let responseIsBson = false;
193
+ try {
194
+ const ndJson = 'application/x-ndjson';
195
+ const bson = 'application/vnd.powersync.bson-stream';
196
+ res = await this.fetch({
197
+ resource: request.url,
198
+ request: {
199
+ method: 'POST',
200
+ headers: {
201
+ ...request.headers,
202
+ accept: `${bson};q=0.9,${ndJson};q=0.8`
203
+ },
204
+ body: JSON.stringify(data),
205
+ signal: controller.signal,
206
+ cache: 'no-store'
207
+ },
208
+ expectStreamingResponse: true
209
+ });
210
+ if (!res.ok || !res.body) {
211
+ const text = await res.text();
212
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
213
+ error.status = res.status;
214
+ this.logger.log({
215
+ level: LogLevels.error,
216
+ message: `Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`,
217
+ error
218
+ });
219
+ if (res.status === 401) {
220
+ this.invalidateCredentials();
221
+ }
222
+ throw error;
223
+ }
224
+ const contentType = res.headers.get('content-type');
225
+ responseIsBson = contentType == bson;
226
+ }
227
+ catch (ex) {
228
+ if (ex.name == 'AbortError') {
229
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
230
+ }
231
+ throw ex;
232
+ }
233
+ reader = res.body.getReader();
234
+ const stream = {
235
+ next: async () => {
236
+ if (controller.signal.aborted) {
237
+ return doneResult;
238
+ }
239
+ try {
240
+ return await reader.read();
241
+ }
242
+ catch (ex) {
243
+ if (controller.signal.aborted) {
244
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
245
+ // things working as intended, we can return a done event and consider the exception handled.
246
+ return doneResult;
247
+ }
248
+ throw ex;
249
+ }
250
+ }
251
+ };
252
+ return { isBson: responseIsBson, stream };
253
+ }
254
+ /**
255
+ * Posts a `/sync/stream` request.
256
+ *
257
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
258
+ * `Uint8Array`s.
259
+ */
260
+ async fetchStream(options) {
261
+ const { isBson, stream } = await this.fetchStreamRaw(options);
262
+ if (isBson) {
263
+ return extractBsonObjects(stream);
264
+ }
265
+ else {
266
+ return extractJsonLines(stream, this.createTextDecoder());
267
+ }
268
+ }
269
+ }
270
+ //# sourceMappingURL=AbstractRemote.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AbstractRemote.js","sourceRoot":"","sources":["../../../../src/client/sync/stream/AbstractRemote.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAwB,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAEpG,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAC;AAClE,OAAO,EACL,UAAU,EACV,kBAAkB,EAClB,gBAAgB,EAEjB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAU3D,MAAM,8BAA8B,GAAG,MAAM,CAAC;AAE9C,MAAM,iBAAiB,GAAgC;IACrD,SAAS;IACT,UAAU;IACV,cAAc;CACf,CAAC;AAgBF,MAAM,UAAU,uBAAuB,CAAC,QAAmC;IACzE,IAAI,QAA6B,CAAC;IAElC,OAAO,CAAC,OAAO,EAAE,EAAE;QACjB,MAAM,KAAK,GAAG,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC,CAAC;QACxC,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC,CAAC;AACJ,CAAC;AAyBD;;GAEG;AACH,MAAM,OAAgB,cAAc;IAItB;IACD;IAJD,WAAW,GAAgC,IAAI,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;gBAC7B,CAAC;gBAAC,OAAO,EAAE,EAAE,CAAC;oBACZ,IAAI,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;wBAC9B,sGAAsG;wBACtG,6FAA6F;wBAC7F,OAAO,UAAU,CAAC;oBACpB,CAAC;oBAED,MAAM,EAAE,CAAC;gBACX,CAAC;YACH,CAAC;SACF,CAAC;QAEF,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,CAAC;IAC5C,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,WAAW,CAAC,OAA0B;QAC1C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QAC9D,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,kBAAkB,CAAC,MAAM,CAAC,CAAC;QACpC,CAAC;aAAM,CAAC;YACN,OAAO,gBAAgB,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,CAAC,CAAC;QAC5D,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,156 @@
1
+ import { BaseObserverInterface, BaseListener, Disposable, PowerSyncLogger, SyncStatus, BaseObserver } from '@powersync/common';
2
+ import { BucketStorageAdapter } from '../bucket/BucketStorageAdapter.js';
3
+ import { AbstractRemote } from './AbstractRemote.js';
4
+ import { CoreSyncStatus } from './core-instruction.js';
5
+ import { JavaScriptSyncState, SyncStatusSnapshot } from '../../../db/crud/SyncStatus.js';
6
+ import { ResolvedSyncOptions } from '../options.js';
7
+ /**
8
+ * @internal
9
+ */
10
+ export declare enum LockType {
11
+ CRUD = "crud",
12
+ SYNC = "sync"
13
+ }
14
+ /**
15
+ * Abstract Lock to be implemented by various JS environments
16
+ *
17
+ * @internal
18
+ */
19
+ export interface LockOptions<T> {
20
+ callback: () => Promise<T>;
21
+ type: LockType;
22
+ signal?: AbortSignal;
23
+ }
24
+ /**
25
+ * @internal
26
+ */
27
+ export interface AbstractStreamingSyncImplementationOptions {
28
+ adapter: BucketStorageAdapter;
29
+ subscriptions: SubscribedStream[];
30
+ uploadCrud: () => Promise<void>;
31
+ /**
32
+ * Posts a checkpoint request with the connector, returning null if the connector doesn't support that.
33
+ */
34
+ postCheckpointRequest: (clientId: string, requestId: string) => Promise<string | null> | null;
35
+ /**
36
+ * An identifier for which PowerSync DB this sync implementation is
37
+ * linked to. Most commonly DB name, but not restricted to DB name.
38
+ */
39
+ identifier?: string;
40
+ logger: PowerSyncLogger;
41
+ remote: AbstractRemote;
42
+ /**
43
+ * The serialized schema - mainly used to forward information about raw tables to the sync client.
44
+ */
45
+ serializedSchema: any;
46
+ }
47
+ /**
48
+ * @internal
49
+ */
50
+ export interface StreamingSyncImplementationListener extends BaseListener {
51
+ /**
52
+ * Triggers whenever the status' members have changed in value
53
+ */
54
+ statusChanged?: ((status: SyncStatusSnapshot) => void) | undefined;
55
+ }
56
+ /**
57
+ * @internal
58
+ */
59
+ export interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
60
+ /**
61
+ * Connects to the sync service
62
+ */
63
+ connect(options: ResolvedSyncOptions): Promise<void>;
64
+ /**
65
+ * Disconnects from the sync services.
66
+ * @throws if not connected or if abort is not controlled internally
67
+ */
68
+ disconnect(): Promise<void>;
69
+ isConnected: boolean;
70
+ triggerCrudUpload: () => void;
71
+ waitForReady(): Promise<void>;
72
+ waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
73
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
74
+ markConnectionMayHaveChanged(): void;
75
+ requestCheckpoint(): Promise<bigint>;
76
+ }
77
+ /**
78
+ * @internal
79
+ */
80
+ export type SubscribedStream = {
81
+ name: string;
82
+ params: Record<string, any> | null;
83
+ };
84
+ /**
85
+ * @internal
86
+ */
87
+ export declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
88
+ protected options: AbstractStreamingSyncImplementationOptions;
89
+ protected abortController: AbortController | null;
90
+ protected crudUpdateListener?: () => void;
91
+ protected streamingSyncPromise?: Promise<[void, void, void]>;
92
+ protected logger: PowerSyncLogger;
93
+ protected activeStreams: SubscribedStream[];
94
+ private connectionMayHaveChanged;
95
+ private crudUploadNotifier;
96
+ private checkpoints;
97
+ private notifyCompletedUploads?;
98
+ private handleActiveStreamsChange?;
99
+ syncStatus: SyncStatusSnapshot;
100
+ constructor(options: AbstractStreamingSyncImplementationOptions);
101
+ triggerCrudUpload(): void;
102
+ waitForReady(): Promise<void>;
103
+ waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
104
+ get lastSyncedAt(): Date | undefined;
105
+ get isConnected(): boolean;
106
+ dispose(): Promise<void>;
107
+ abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
108
+ private requestNextCheckpointFromService;
109
+ private requestCheckpointFromService;
110
+ private getLegacyWriteCheckpoint;
111
+ private crudUploadLoop;
112
+ private _uploadAllCrud;
113
+ connect(options: ResolvedSyncOptions): Promise<void>;
114
+ requestCheckpoint(): Promise<bigint>;
115
+ disconnect(): Promise<void>;
116
+ private markAsDisconnected;
117
+ private streamingSync;
118
+ markConnectionMayHaveChanged(): void;
119
+ /**
120
+ * Older versions of the JS SDK used to encode subkeys as JSON in `OplogEntry.toJSON`.
121
+ * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
122
+ * While this is not a problem as long as it's done consistently, it causes issues when a database
123
+ * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
124
+ * is enabled.
125
+ *
126
+ * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
127
+ * migration is only triggered when necessary (for now). The function returns whether the new format
128
+ * should be used, so that the JS SDK is able to write to updated databases.
129
+ *
130
+ * @param requireFixedKeyFormat - Whether we require the new format or also support the old one.
131
+ * The Rust client requires the new subkey format.
132
+ * @returns Whether the database is now using the new, fixed subkey format.
133
+ */
134
+ private requireKeyFormat;
135
+ protected streamingSyncIteration(signal: AbortSignal, options: ResolvedSyncOptions): Promise<RustIterationResult | null>;
136
+ private receiveSyncLines;
137
+ /**
138
+ * Watches the current checkpoint request id to re-request it if we take too long to receive it.
139
+ *
140
+ * This does not require navigator locks: It waits for checkpoints to be seeded, which can only happen in the context
141
+ * of a download loop.
142
+ *
143
+ * Note that requesting checkpoints with ids the service has already seen is a cheap no-op.
144
+ */
145
+ private repostUnacknowledgedCheckpointRequests;
146
+ private seedCheckpointRequestState;
147
+ private rustSyncIteration;
148
+ protected updateSyncStatus(core: CoreSyncStatus | null, jsState?: JavaScriptSyncState): void;
149
+ protected updateJsSyncState(state: JavaScriptSyncState): void;
150
+ private delayRetry;
151
+ updateSubscriptions(subscriptions: SubscribedStream[]): void;
152
+ }
153
+ interface RustIterationResult {
154
+ immediateRestart: boolean;
155
+ }
156
+ export {};