@powersync/shared-internals 0.0.0-tmp.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/bundle.cjs +11787 -0
  4. package/dist/bundle.cjs.map +1 -0
  5. package/dist/bundle.mjs +11757 -0
  6. package/dist/bundle.mjs.map +1 -0
  7. package/dist/bundle.node.cjs +9418 -0
  8. package/dist/bundle.node.cjs.map +1 -0
  9. package/dist/bundle.node.mjs +9388 -0
  10. package/dist/bundle.node.mjs.map +1 -0
  11. package/dist/index.d.cts +1159 -0
  12. package/dist/websockets.mjs +7558 -0
  13. package/dist/websockets.mjs.map +1 -0
  14. package/dist/websockets.node.mjs +5189 -0
  15. package/dist/websockets.node.mjs.map +1 -0
  16. package/legacy/sync_protocol.d.ts +103 -0
  17. package/lib/client/BasePowerSyncDatabase.d.ts +147 -0
  18. package/lib/client/BasePowerSyncDatabase.js +622 -0
  19. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  20. package/lib/client/ConnectionManager.d.ts +116 -0
  21. package/lib/client/ConnectionManager.js +306 -0
  22. package/lib/client/ConnectionManager.js.map +1 -0
  23. package/lib/client/CustomQuery.d.ts +21 -0
  24. package/lib/client/CustomQuery.js +43 -0
  25. package/lib/client/CustomQuery.js.map +1 -0
  26. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +42 -0
  27. package/lib/client/sync/bucket/BucketStorageAdapter.js +23 -0
  28. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  29. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  30. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  31. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  32. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +33 -0
  33. package/lib/client/sync/bucket/SqliteBucketStorage.js +166 -0
  34. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  35. package/lib/client/sync/options.d.ts +9 -0
  36. package/lib/client/sync/options.js +16 -0
  37. package/lib/client/sync/options.js.map +1 -0
  38. package/lib/client/sync/stream/AbstractRemote.d.ts +125 -0
  39. package/lib/client/sync/stream/AbstractRemote.js +265 -0
  40. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  41. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +138 -0
  42. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +611 -0
  43. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  44. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  45. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  46. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  47. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  48. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  49. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  50. package/lib/client/sync/stream/core-instruction.d.ts +75 -0
  51. package/lib/client/sync/stream/core-instruction.js +4 -0
  52. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  53. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  54. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  55. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  56. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  57. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  58. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  59. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  60. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  61. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  63. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  64. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  66. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  67. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  68. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  69. package/lib/client/watched/WatchedQuery.js +12 -0
  70. package/lib/client/watched/WatchedQuery.js.map +1 -0
  71. package/lib/constants.d.ts +5 -0
  72. package/lib/constants.js +6 -0
  73. package/lib/constants.js.map +1 -0
  74. package/lib/db/ConnectionClosedError.d.ts +12 -0
  75. package/lib/db/ConnectionClosedError.js +23 -0
  76. package/lib/db/ConnectionClosedError.js.map +1 -0
  77. package/lib/db/crud/SyncProgress.d.ts +10 -0
  78. package/lib/db/crud/SyncProgress.js +33 -0
  79. package/lib/db/crud/SyncProgress.js.map +1 -0
  80. package/lib/db/crud/SyncStatus.d.ts +48 -0
  81. package/lib/db/crud/SyncStatus.js +178 -0
  82. package/lib/db/crud/SyncStatus.js.map +1 -0
  83. package/lib/db/openDatabase.d.ts +7 -0
  84. package/lib/db/openDatabase.js +22 -0
  85. package/lib/db/openDatabase.js.map +1 -0
  86. package/lib/index.d.ts +22 -0
  87. package/lib/index.js +22 -0
  88. package/lib/index.js.map +1 -0
  89. package/lib/utils/AbortOperation.d.ts +11 -0
  90. package/lib/utils/AbortOperation.js +21 -0
  91. package/lib/utils/AbortOperation.js.map +1 -0
  92. package/lib/utils/ControlledExecutor.d.ts +31 -0
  93. package/lib/utils/ControlledExecutor.js +54 -0
  94. package/lib/utils/ControlledExecutor.js.map +1 -0
  95. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  96. package/lib/utils/MetaBaseObserver.js +51 -0
  97. package/lib/utils/MetaBaseObserver.js.map +1 -0
  98. package/lib/utils/async.d.ts +46 -0
  99. package/lib/utils/async.js +147 -0
  100. package/lib/utils/async.js.map +1 -0
  101. package/lib/utils/compatibility.d.ts +8 -0
  102. package/lib/utils/compatibility.js +9 -0
  103. package/lib/utils/compatibility.js.map +1 -0
  104. package/lib/utils/mutex.d.ts +42 -0
  105. package/lib/utils/mutex.js +150 -0
  106. package/lib/utils/mutex.js.map +1 -0
  107. package/lib/utils/parseQuery.d.ts +12 -0
  108. package/lib/utils/parseQuery.js +20 -0
  109. package/lib/utils/parseQuery.js.map +1 -0
  110. package/lib/utils/queue.d.ts +16 -0
  111. package/lib/utils/queue.js +42 -0
  112. package/lib/utils/queue.js.map +1 -0
  113. package/lib/utils/stream_transform.d.ts +41 -0
  114. package/lib/utils/stream_transform.js +211 -0
  115. package/lib/utils/stream_transform.js.map +1 -0
  116. package/lib/version.d.ts +1 -0
  117. package/lib/version.js +4 -0
  118. package/lib/version.js.map +1 -0
  119. package/package.json +65 -0
  120. package/src/client/BasePowerSyncDatabase.ts +853 -0
  121. package/src/client/ConnectionManager.ts +419 -0
  122. package/src/client/CustomQuery.ts +60 -0
  123. package/src/client/sync/bucket/BucketStorageAdapter.ts +51 -0
  124. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  125. package/src/client/sync/bucket/SqliteBucketStorage.ts +213 -0
  126. package/src/client/sync/options.ts +24 -0
  127. package/src/client/sync/stream/AbstractRemote.ts +369 -0
  128. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +795 -0
  129. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  130. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  131. package/src/client/sync/stream/core-instruction.ts +78 -0
  132. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  133. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  134. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  135. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  136. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  137. package/src/client/watched/WatchedQuery.ts +14 -0
  138. package/src/constants.ts +6 -0
  139. package/src/db/ConnectionClosedError.ts +25 -0
  140. package/src/db/crud/SyncProgress.ts +39 -0
  141. package/src/db/crud/SyncStatus.ts +234 -0
  142. package/src/db/openDatabase.ts +23 -0
  143. package/src/index.ts +24 -0
  144. package/src/utils/AbortOperation.ts +19 -0
  145. package/src/utils/ControlledExecutor.ts +78 -0
  146. package/src/utils/MetaBaseObserver.ts +65 -0
  147. package/src/utils/async.ts +185 -0
  148. package/src/utils/compatibility.ts +9 -0
  149. package/src/utils/mutex.ts +186 -0
  150. package/src/utils/parseQuery.ts +31 -0
  151. package/src/utils/queue.ts +48 -0
  152. package/src/utils/stream_transform.ts +260 -0
  153. package/src/version.ts +3 -0
@@ -0,0 +1,419 @@
1
+ import {
2
+ BaseObserver,
3
+ LogLevels,
4
+ PowerSyncLogger,
5
+ SyncStatus,
6
+ BaseListener,
7
+ PowerSyncBackendConnector,
8
+ SyncStream,
9
+ SyncStreamDescription,
10
+ SyncStreamSubscribeOptions,
11
+ SyncStreamSubscription,
12
+ SyncOptions,
13
+ SyncStreamConnectionMethod
14
+ } from '@powersync/common';
15
+
16
+ import { StreamingSyncImplementation, SubscribedStream } from './sync/stream/AbstractStreamingSyncImplementation.js';
17
+ import { ResolvedSyncOptions, resolveSyncOptions } from './sync/options.js';
18
+
19
+ /**
20
+ * @internal
21
+ */
22
+ export interface ConnectionManagerSyncImplementationResult {
23
+ sync: StreamingSyncImplementation;
24
+ /**
25
+ * Additional cleanup function which is called after the sync stream implementation
26
+ * is disposed.
27
+ */
28
+ onDispose: () => Promise<void> | void;
29
+ }
30
+
31
+ /**
32
+ * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
33
+ *
34
+ * @internal
35
+ */
36
+ export interface CreateSyncImplementationOptions {
37
+ subscriptions: SubscribedStream[];
38
+ serializedSchema: any;
39
+ }
40
+
41
+ /**
42
+ * @internal
43
+ */
44
+ export interface InternalSubscriptionAdapter {
45
+ firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
46
+ resolveOfflineSyncStatus(): Promise<void>;
47
+ rustSubscriptionsCommand(payload: any): Promise<void>;
48
+ }
49
+
50
+ /**
51
+ * @internal
52
+ */
53
+ export interface ConnectionManagerOptions {
54
+ createSyncImplementation(
55
+ connector: PowerSyncBackendConnector,
56
+ options: CreateSyncImplementationOptions
57
+ ): Promise<ConnectionManagerSyncImplementationResult>;
58
+ readonly defaultConnectionMethod: SyncStreamConnectionMethod;
59
+
60
+ logger: PowerSyncLogger;
61
+ }
62
+
63
+ type StoredConnectionOptions = {
64
+ connector: PowerSyncBackendConnector;
65
+ options: ResolvedSyncOptions;
66
+ schema: any;
67
+ };
68
+
69
+ /**
70
+ * @internal
71
+ */
72
+ export interface ConnectionManagerListener extends BaseListener {
73
+ syncStreamCreated: (sync: StreamingSyncImplementation) => void;
74
+ }
75
+
76
+ /**
77
+ * @internal
78
+ */
79
+ export class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
80
+ /**
81
+ * Tracks active connection attempts
82
+ */
83
+ protected connectingPromise: Promise<void> | null;
84
+ /**
85
+ * Tracks actively instantiating a streaming sync implementation.
86
+ */
87
+ protected syncStreamInitPromise: Promise<void> | null;
88
+ /**
89
+ * Active disconnect operation. Calling disconnect multiple times
90
+ * will resolve to the same operation.
91
+ */
92
+ protected disconnectingPromise: Promise<void> | null;
93
+ /**
94
+ * Tracks the last parameters supplied to `connect` calls.
95
+ * Calling `connect` multiple times in succession will result in:
96
+ * - 1 pending connection operation which will be aborted.
97
+ * - updating the last set of parameters while waiting for the pending
98
+ * attempt to be aborted
99
+ * - internally connecting with the last set of parameters
100
+ */
101
+ protected pendingConnectionOptions: StoredConnectionOptions | null;
102
+
103
+ private currentOptions: ResolvedSyncOptions | null;
104
+
105
+ syncStreamImplementation: StreamingSyncImplementation | null;
106
+
107
+ /**
108
+ * Additional cleanup function which is called after the sync stream implementation
109
+ * is disposed.
110
+ */
111
+ protected syncDisposer: (() => Promise<void> | void) | null;
112
+
113
+ /**
114
+ * Subscriptions managed in this connection manager.
115
+ *
116
+ * On the web, these local subscriptions are merged across tabs by a shared worker.
117
+ */
118
+ private locallyActiveSubscriptions = new Map<string, ActiveSubscription>();
119
+
120
+ constructor(protected options: ConnectionManagerOptions) {
121
+ super();
122
+ this.connectingPromise = null;
123
+ this.syncStreamInitPromise = null;
124
+ this.disconnectingPromise = null;
125
+ this.pendingConnectionOptions = null;
126
+ this.syncStreamImplementation = null;
127
+ this.currentOptions = null;
128
+ this.syncDisposer = null;
129
+ }
130
+
131
+ get connector() {
132
+ return this.pendingConnectionOptions?.connector ?? null;
133
+ }
134
+
135
+ get connectionOptions() {
136
+ return this.currentOptions ?? this.pendingConnectionOptions?.options ?? null;
137
+ }
138
+
139
+ get logger() {
140
+ return this.options.logger;
141
+ }
142
+
143
+ async close() {
144
+ await this.syncStreamImplementation?.dispose();
145
+ await this.syncDisposer?.();
146
+ }
147
+
148
+ async connect(connector: PowerSyncBackendConnector, options: SyncOptions, serializedSchema: any) {
149
+ // Keep track if there were pending operations before this call
150
+ const hadPendingOptions = !!this.pendingConnectionOptions;
151
+
152
+ // Update pending options to the latest values
153
+ this.pendingConnectionOptions = {
154
+ connector,
155
+ options: resolveSyncOptions(options, this.options.defaultConnectionMethod),
156
+ schema: serializedSchema
157
+ };
158
+
159
+ // Disconnecting here provides aborting in progress connection attempts.
160
+ // The connectInternal method will clear pending options once it starts connecting (with the options).
161
+ // We only need to trigger a disconnect here if we have already reached the point of connecting.
162
+ // If we do already have pending options, a disconnect has already been performed.
163
+ // The connectInternal method also does a sanity disconnect to prevent straggler connections.
164
+ // We should also disconnect if we have already completed a connection attempt.
165
+ if (!hadPendingOptions || this.syncStreamImplementation) {
166
+ await this.disconnectInternal();
167
+ }
168
+
169
+ // Triggers a connect which checks if pending options are available after the connect completes.
170
+ // The completion can be for a successful, unsuccessful or aborted connection attempt.
171
+ // If pending options are available another connection will be triggered.
172
+ const checkConnection = async (): Promise<void> => {
173
+ if (this.pendingConnectionOptions) {
174
+ // Pending options have been placed while connecting.
175
+ // Need to reconnect.
176
+ this.connectingPromise = this.connectInternal()
177
+ .catch(() => {})
178
+ .finally(checkConnection);
179
+ return this.connectingPromise;
180
+ } else {
181
+ // Clear the connecting promise, done.
182
+ this.connectingPromise = null;
183
+ return;
184
+ }
185
+ };
186
+
187
+ this.connectingPromise ??= this.connectInternal()
188
+ .catch(() => {})
189
+ .finally(checkConnection);
190
+ return this.connectingPromise;
191
+ }
192
+
193
+ protected async connectInternal() {
194
+ let appliedOptions: ResolvedSyncOptions | null = null;
195
+
196
+ // This method ensures a disconnect before any connection attempt
197
+ await this.disconnectInternal();
198
+
199
+ /**
200
+ * This portion creates a sync implementation which can be racy when disconnecting or
201
+ * if multiple tabs on web are in use.
202
+ * This is protected in an exclusive lock.
203
+ * The promise tracks the creation which is used to synchronize disconnect attempts.
204
+ */
205
+ this.syncStreamInitPromise = new Promise(async (resolve, reject) => {
206
+ try {
207
+ if (!this.pendingConnectionOptions) {
208
+ this.logger.log({
209
+ level: LogLevels.debug,
210
+ message: 'No pending connection options found, not creating sync stream implementation'
211
+ });
212
+ // A disconnect could have cleared this.
213
+ resolve();
214
+ return;
215
+ }
216
+
217
+ if (this.disconnectingPromise) {
218
+ resolve();
219
+ return;
220
+ }
221
+
222
+ const { connector, options, schema } = this.pendingConnectionOptions;
223
+ appliedOptions = options;
224
+ this.currentOptions = options;
225
+
226
+ this.pendingConnectionOptions = null;
227
+
228
+ const { sync, onDispose } = await this.options.createSyncImplementation(connector, {
229
+ subscriptions: this.activeStreams,
230
+ serializedSchema: schema
231
+ });
232
+ this.iterateListeners((l) => l.syncStreamCreated?.(sync));
233
+ this.syncStreamImplementation = sync;
234
+ this.syncDisposer = onDispose;
235
+ await this.syncStreamImplementation.waitForReady();
236
+ resolve();
237
+ } catch (error) {
238
+ reject(error);
239
+ }
240
+ });
241
+
242
+ await this.syncStreamInitPromise;
243
+ this.syncStreamInitPromise = null;
244
+
245
+ if (!appliedOptions) {
246
+ // A disconnect could have cleared the options which did not create a syncStreamImplementation
247
+ return;
248
+ }
249
+
250
+ // It might be possible that a disconnect triggered between the last check
251
+ // and this point. Awaiting here allows the sync stream to be cleared if disconnected.
252
+ await this.disconnectingPromise;
253
+
254
+ this.logger.log({ level: LogLevels.debug, message: 'Attempting to connect to PowerSync instance' });
255
+ await this.syncStreamImplementation?.connect(appliedOptions!);
256
+ }
257
+
258
+ /**
259
+ * Close the sync connection.
260
+ *
261
+ * Use {@link ConnectionManager.connect} to connect again.
262
+ */
263
+ async disconnect() {
264
+ // This will help abort pending connects
265
+ this.pendingConnectionOptions = null;
266
+ this.currentOptions = null;
267
+ await this.disconnectInternal();
268
+ }
269
+
270
+ protected async disconnectInternal(): Promise<void> {
271
+ if (this.disconnectingPromise) {
272
+ // A disconnect is already in progress
273
+ return this.disconnectingPromise;
274
+ }
275
+
276
+ this.disconnectingPromise = this.performDisconnect();
277
+
278
+ await this.disconnectingPromise;
279
+ this.disconnectingPromise = null;
280
+ }
281
+
282
+ protected async performDisconnect() {
283
+ // Wait if a sync stream implementation is being created before closing it
284
+ // (syncStreamImplementation must be assigned before we can properly dispose it)
285
+ await this.syncStreamInitPromise;
286
+
287
+ // Keep reference to the sync stream implementation and disposer
288
+ // The class members will be cleared before we trigger the disconnect
289
+ // to prevent any further calls to the sync stream implementation.
290
+ const sync = this.syncStreamImplementation;
291
+ this.syncStreamImplementation = null;
292
+ const disposer = this.syncDisposer;
293
+ this.syncDisposer = null;
294
+
295
+ await sync?.disconnect();
296
+ await sync?.dispose();
297
+ await disposer?.();
298
+ }
299
+
300
+ stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream {
301
+ const desc = { name, parameters } satisfies SyncStreamDescription;
302
+
303
+ const waitForFirstSync = (abort?: AbortSignal) => {
304
+ return adapter.firstStatusMatching((s) => s.forStream(desc)?.subscription.hasSynced, abort);
305
+ };
306
+
307
+ return {
308
+ ...desc,
309
+ subscribe: async (options?: SyncStreamSubscribeOptions) => {
310
+ // NOTE: We also run this command if a subscription already exists, because this increases the expiry date
311
+ // (relevant if the app is closed before connecting again, where the last subscribe call determines the ttl).
312
+ await adapter.rustSubscriptionsCommand({
313
+ subscribe: {
314
+ stream: {
315
+ name,
316
+ params: parameters
317
+ },
318
+ ttl: options?.ttl,
319
+ priority: options?.priority
320
+ }
321
+ });
322
+
323
+ if (!this.syncStreamImplementation) {
324
+ // We're not connected. So, update the offline sync status to reflect the new subscription.
325
+ // (With an active iteration, the sync client would include it in its state).
326
+ await adapter.resolveOfflineSyncStatus();
327
+ }
328
+
329
+ const key = `${name}|${JSON.stringify(parameters)}`;
330
+ let subscription = this.locallyActiveSubscriptions.get(key);
331
+ if (subscription == null) {
332
+ const clearSubscription = () => {
333
+ this.locallyActiveSubscriptions.delete(key);
334
+ this.subscriptionsMayHaveChanged();
335
+ };
336
+
337
+ subscription = new ActiveSubscription(name, parameters, this.logger, waitForFirstSync, clearSubscription);
338
+ this.locallyActiveSubscriptions.set(key, subscription);
339
+ this.subscriptionsMayHaveChanged();
340
+ }
341
+
342
+ return new SyncStreamSubscriptionHandle(subscription);
343
+ },
344
+ unsubscribeAll: async () => {
345
+ await adapter.rustSubscriptionsCommand({ unsubscribe: { name, params: parameters } });
346
+ this.subscriptionsMayHaveChanged();
347
+ }
348
+ };
349
+ }
350
+
351
+ /**
352
+ * @internal exposed for testing
353
+ */
354
+ get activeStreams() {
355
+ return [...this.locallyActiveSubscriptions.values()].map((a) => ({ name: a.name, params: a.parameters }));
356
+ }
357
+
358
+ private subscriptionsMayHaveChanged() {
359
+ this.syncStreamImplementation?.updateSubscriptions(this.activeStreams);
360
+ }
361
+ }
362
+
363
+ class ActiveSubscription {
364
+ refcount: number = 0;
365
+
366
+ constructor(
367
+ readonly name: string,
368
+ readonly parameters: Record<string, any> | null,
369
+ readonly logger: PowerSyncLogger,
370
+ readonly waitForFirstSync: (abort?: AbortSignal) => Promise<void>,
371
+ private clearSubscription: () => void
372
+ ) {}
373
+
374
+ decrementRefCount() {
375
+ this.refcount--;
376
+ if (this.refcount == 0) {
377
+ this.clearSubscription();
378
+ }
379
+ }
380
+ }
381
+
382
+ class SyncStreamSubscriptionHandle implements SyncStreamSubscription {
383
+ private active: boolean = true;
384
+
385
+ constructor(readonly subscription: ActiveSubscription) {
386
+ subscription.refcount++;
387
+ _finalizer?.register(this, subscription, this);
388
+ }
389
+
390
+ get name() {
391
+ return this.subscription.name;
392
+ }
393
+
394
+ get parameters() {
395
+ return this.subscription.parameters;
396
+ }
397
+
398
+ waitForFirstSync(abort?: AbortSignal): Promise<void> {
399
+ return this.subscription.waitForFirstSync(abort);
400
+ }
401
+
402
+ unsubscribe(): void {
403
+ if (this.active) {
404
+ this.active = false;
405
+ _finalizer?.unregister(this);
406
+ this.subscription.decrementRefCount();
407
+ }
408
+ }
409
+ }
410
+
411
+ const _finalizer =
412
+ 'FinalizationRegistry' in globalThis
413
+ ? new FinalizationRegistry<ActiveSubscription>((sub) => {
414
+ sub.logger.log({
415
+ level: LogLevels.warn,
416
+ message: `A subscription to ${sub.name} with params ${JSON.stringify(sub.parameters)} leaked! Please ensure calling unsubscribe() when you don't need a subscription anymore. For global subscriptions, consider storing them in global fields to avoid this warning.`
417
+ });
418
+ })
419
+ : null;
@@ -0,0 +1,60 @@
1
+ import {
2
+ Query,
3
+ StandardWatchedQueryOptions,
4
+ FalsyComparator,
5
+ WatchCompatibleQuery,
6
+ WatchedQueryOptions,
7
+ DifferentialWatchedQueryOptions
8
+ } from '@powersync/common';
9
+
10
+ import { BasePowerSyncDatabase } from './BasePowerSyncDatabase.js';
11
+ import { DifferentialQueryProcessor } from './watched/DifferentialQueryProcessor.js';
12
+ import { OnChangeQueryProcessor } from './watched/OnChangeQueryProcessor.js';
13
+ import { DEFAULT_WATCH_QUERY_OPTIONS } from './watched/WatchedQuery.js';
14
+
15
+ /**
16
+ * @internal
17
+ */
18
+ export interface CustomQueryOptions<RowType> {
19
+ db: BasePowerSyncDatabase;
20
+ query: WatchCompatibleQuery<RowType[]>;
21
+ }
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ export class CustomQuery<RowType> implements Query<RowType> {
27
+ constructor(protected options: CustomQueryOptions<RowType>) {}
28
+
29
+ protected resolveOptions(options: WatchedQueryOptions): WatchedQueryOptions {
30
+ return {
31
+ reportFetching: options?.reportFetching ?? DEFAULT_WATCH_QUERY_OPTIONS.reportFetching,
32
+ throttleMs: options?.throttleMs ?? DEFAULT_WATCH_QUERY_OPTIONS.throttleMs,
33
+ triggerOnTables: options?.triggerOnTables
34
+ };
35
+ }
36
+
37
+ watch(watchOptions: StandardWatchedQueryOptions<RowType>) {
38
+ return new OnChangeQueryProcessor<RowType[]>({
39
+ db: this.options.db,
40
+ comparator: watchOptions?.comparator ?? FalsyComparator,
41
+ placeholderData: watchOptions?.placeholderData ?? [],
42
+ watchOptions: {
43
+ ...this.resolveOptions(watchOptions),
44
+ query: this.options.query
45
+ }
46
+ });
47
+ }
48
+
49
+ differentialWatch(differentialWatchOptions: DifferentialWatchedQueryOptions<RowType>) {
50
+ return new DifferentialQueryProcessor<RowType>({
51
+ db: this.options.db,
52
+ rowComparator: differentialWatchOptions?.rowComparator,
53
+ placeholderData: differentialWatchOptions?.placeholderData ?? [],
54
+ watchOptions: {
55
+ ...this.resolveOptions(differentialWatchOptions),
56
+ query: this.options.query
57
+ }
58
+ });
59
+ }
60
+ }
@@ -0,0 +1,51 @@
1
+ import { BaseListener, BaseObserverInterface, Disposable, CrudBatch, CrudEntry } from '@powersync/common';
2
+
3
+ export enum PSInternalTable {
4
+ DATA = 'ps_data',
5
+ CRUD = 'ps_crud',
6
+ BUCKETS = 'ps_buckets',
7
+ OPLOG = 'ps_oplog',
8
+ UNTYPED = 'ps_untyped'
9
+ }
10
+
11
+ export enum PowerSyncControlCommand {
12
+ PROCESS_TEXT_LINE = 'line_text',
13
+ PROCESS_BSON_LINE = 'line_binary',
14
+ STOP = 'stop',
15
+ START = 'start',
16
+ NOTIFY_TOKEN_REFRESHED = 'refreshed_token',
17
+ NOTIFY_CRUD_UPLOAD_COMPLETED = 'completed_upload',
18
+ UPDATE_SUBSCRIPTIONS = 'update_subscriptions',
19
+ /**
20
+ * An `established` or `end` event for response streams.
21
+ */
22
+ CONNECTION_STATE = 'connection'
23
+ }
24
+
25
+ export interface BucketStorageListener extends BaseListener {
26
+ crudUpdate: () => void;
27
+ }
28
+
29
+ export interface BucketStorageAdapter extends BaseObserverInterface<BucketStorageListener>, Disposable {
30
+ init(): Promise<void>;
31
+
32
+ hasMigratedSubkeys(): Promise<boolean>;
33
+ migrateToFixedSubkeys(): Promise<void>;
34
+
35
+ nextCrudItem(): Promise<CrudEntry | undefined>;
36
+ hasCrud(): Promise<boolean>;
37
+ getCrudBatch(limit?: number): Promise<CrudBatch | null>;
38
+
39
+ updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
40
+ getMaxOpId(): string;
41
+
42
+ /**
43
+ * Get an unique client id.
44
+ */
45
+ getClientId(): Promise<string>;
46
+
47
+ /**
48
+ * Invokes the `powersync_control` function for the sync client.
49
+ */
50
+ control(op: PowerSyncControlCommand, payload: string | Uint8Array | null): Promise<string>;
51
+ }
@@ -0,0 +1,116 @@
1
+ import { CrudEntry, UpdateType } from '@powersync/common';
2
+
3
+ /**
4
+ * @internal
5
+ */
6
+ export type CrudEntryJSON = {
7
+ id: string;
8
+ data: string;
9
+ tx_id?: number;
10
+ };
11
+
12
+ type CrudEntryDataJSON = {
13
+ data: Record<string, any>;
14
+ old?: Record<string, any>;
15
+ op: UpdateType;
16
+ type: string;
17
+ id: string;
18
+ metadata?: string;
19
+ };
20
+
21
+ /**
22
+ * The output JSON seems to be a third type of JSON, not the same as the input JSON.
23
+ */
24
+ type CrudEntryOutputJSON = {
25
+ op_id: number;
26
+ op: UpdateType;
27
+ type: string;
28
+ id: string;
29
+ tx_id?: number;
30
+ data?: Record<string, any>;
31
+ old?: Record<string, any>;
32
+ metadata?: string;
33
+ };
34
+
35
+ /**
36
+ * A single client-side change.
37
+ *
38
+ * @public
39
+ */
40
+ export class CrudEntryImpl implements CrudEntry {
41
+ clientId: number;
42
+ id: string;
43
+ op: UpdateType;
44
+ opData?: Record<string, any>;
45
+ previousValues?: Record<string, any>;
46
+ table: string;
47
+ transactionId?: number;
48
+ metadata?: string;
49
+
50
+ static fromRow(dbRow: CrudEntryJSON): CrudEntry {
51
+ const data: CrudEntryDataJSON = JSON.parse(dbRow.data);
52
+ return new CrudEntryImpl(
53
+ parseInt(dbRow.id),
54
+ data.op,
55
+ data.type,
56
+ data.id,
57
+ dbRow.tx_id,
58
+ data.data,
59
+ data.old,
60
+ data.metadata
61
+ );
62
+ }
63
+
64
+ constructor(
65
+ clientId: number,
66
+ op: UpdateType,
67
+ table: string,
68
+ id: string,
69
+ transactionId?: number,
70
+ opData?: Record<string, any>,
71
+ previousValues?: Record<string, any>,
72
+ metadata?: string
73
+ ) {
74
+ this.clientId = clientId;
75
+ this.id = id;
76
+ this.op = op;
77
+ this.opData = opData;
78
+ this.table = table;
79
+ this.transactionId = transactionId;
80
+ this.previousValues = previousValues;
81
+ this.metadata = metadata;
82
+ }
83
+
84
+ toJSON(): CrudEntryOutputJSON {
85
+ return {
86
+ op_id: this.clientId,
87
+ op: this.op,
88
+ type: this.table,
89
+ id: this.id,
90
+ tx_id: this.transactionId,
91
+ data: this.opData,
92
+ old: this.previousValues,
93
+ metadata: this.metadata
94
+ };
95
+ }
96
+
97
+ equals(entry: CrudEntry) {
98
+ return JSON.stringify(this.toComparisonArray()) == JSON.stringify(entry.toComparisonArray());
99
+ }
100
+
101
+ /**
102
+ * Generates an array for use in deep comparison operations
103
+ */
104
+ toComparisonArray(): unknown[] {
105
+ return [
106
+ this.transactionId,
107
+ this.clientId,
108
+ this.op,
109
+ this.table,
110
+ this.id,
111
+ this.opData,
112
+ this.previousValues,
113
+ this.metadata
114
+ ];
115
+ }
116
+ }