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