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

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