@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
@@ -2,7 +2,7 @@
2
2
  * WatchedAttachmentItem represents an attachment reference in your application's data model.
3
3
  * Use either filename OR fileExtension (not both).
4
4
  *
5
- * @experimental
5
+ * @alpha
6
6
  */
7
7
  export type WatchedAttachmentItem =
8
8
  | {
@@ -10,10 +10,12 @@ export type WatchedAttachmentItem =
10
10
  filename: string;
11
11
  fileExtension?: never;
12
12
  metaData?: string;
13
+ mediaType?: string;
13
14
  }
14
15
  | {
15
16
  id: string;
16
17
  fileExtension: string;
17
18
  filename?: never;
18
19
  metaData?: string;
20
+ mediaType?: string;
19
21
  };
@@ -0,0 +1,540 @@
1
+ import { DBAdapter, DBGetUtils, LockContext, SqlExecutor, Transaction } from '../db/DBAdapter.js';
2
+ import { SyncStatus } from '../db/crud/SyncStatus.js';
3
+ import { Schema } from '../db/schema/Schema.js';
4
+ import { BaseListener, BaseObserverInterface } from '../utils/BaseObserver.js';
5
+ import { WatchedQueryComparator } from './watched/processors/comparators.js';
6
+ import { PowerSyncLogger } from '../utils/Logger.js';
7
+ import { DatabaseSource } from './SQLOpenFactory.js';
8
+ import { TriggerManager } from './triggers/TriggerManager.js';
9
+ import { PowerSyncBackendConnector } from './connection/PowerSyncBackendConnector.js';
10
+ import { SyncOptions } from './sync/options.js';
11
+ import { SyncStream } from './sync/sync-streams.js';
12
+ import { UploadQueueStats } from '../db/crud/UploadQueueStatus.js';
13
+ import { CrudBatch } from './sync/bucket/CrudBatch.js';
14
+ import { CrudTransaction } from './sync/bucket/CrudTransaction.js';
15
+ import { ArrayQueryDefinition, Query } from './Query.js';
16
+ import { WatchCompatibleQuery } from './watched/WatchedQuery.js';
17
+ import { Mutex } from '../utils/mutex.js';
18
+ import { QueryResult } from '../db/QueryResult.js';
19
+
20
+ /**
21
+ * @public
22
+ */
23
+ export interface DisconnectAndClearOptions {
24
+ /** When set to false, data in local-only tables is preserved. */
25
+ clearLocal?: boolean;
26
+ }
27
+
28
+ /**
29
+ * Options required regardless of how a PowerSync database is opened.
30
+ *
31
+ * @public
32
+ */
33
+ export interface BasePowerSyncDatabaseOptions {
34
+ /** Schema used for the local database. */
35
+ schema: Schema;
36
+ logger?: PowerSyncLogger;
37
+ }
38
+
39
+ /**
40
+ * @public
41
+ */
42
+ export type PowerSyncDatabaseOptions = BasePowerSyncDatabaseOptions & DatabaseSource;
43
+
44
+ /**
45
+ * @public
46
+ */
47
+ export interface SQLOnChangeOptions {
48
+ signal?: AbortSignal;
49
+ tables?: string[];
50
+ /** The minimum interval between queries. */
51
+ throttleMs?: number;
52
+ /**
53
+ * Emits an empty result set immediately
54
+ */
55
+ triggerImmediate?: boolean;
56
+ }
57
+
58
+ /**
59
+ * @public
60
+ */
61
+ export interface SQLWatchOptions extends SQLOnChangeOptions {
62
+ /**
63
+ * Optional comparator which will be used to compare the results of the query.
64
+ * The watched query will only yield results if the comparator returns false.
65
+ */
66
+ comparator?: WatchedQueryComparator<QueryResult>;
67
+ }
68
+
69
+ /**
70
+ * @public
71
+ */
72
+ export interface WatchOnChangeEvent {
73
+ changedTables: string[];
74
+ }
75
+
76
+ /**
77
+ * @public
78
+ */
79
+ export interface WatchHandler {
80
+ onResult: (results: QueryResult) => void;
81
+ onError?: (error: Error) => void;
82
+ }
83
+
84
+ /**
85
+ * @public
86
+ */
87
+ export interface WatchOnChangeHandler {
88
+ onChange: (event: WatchOnChangeEvent) => Promise<void> | void;
89
+ }
90
+
91
+ /**
92
+ * @public
93
+ */
94
+ export interface PowerSyncDBListener extends BaseListener {
95
+ initialized: () => void;
96
+ schemaChanged: (schema: Schema) => void;
97
+ statusChanged?: (status: SyncStatus) => void;
98
+ closing: () => Promise<void> | void;
99
+ closed: () => Promise<void> | void;
100
+ }
101
+
102
+ /**
103
+ * @public
104
+ */
105
+ export interface PowerSyncCloseOptions {
106
+ /**
107
+ * Disconnect the sync stream client if connected.
108
+ * This is usually true, but can be false for Web when using
109
+ * multiple tabs and a shared sync provider.
110
+ */
111
+ disconnect?: boolean;
112
+ }
113
+
114
+ /**
115
+ * @public
116
+ */
117
+ export interface PowerSyncDatabaseConstructor<Options> {
118
+ new (options: Options): CommonPowerSyncDatabase;
119
+ }
120
+
121
+ /**
122
+ * @public
123
+ * @deprecated Use {@link CommonPowerSyncDatabase} instead.
124
+ */
125
+ export type AbstractPowerSyncDatabase = CommonPowerSyncDatabase;
126
+
127
+ /**
128
+ * @public
129
+ */
130
+ export interface CommonPowerSyncDatabase extends BaseObserverInterface<PowerSyncDBListener>, SqlExecutor, DBGetUtils {
131
+ /**
132
+ * Returns true if the connection is closed.
133
+ */
134
+ readonly closed: boolean;
135
+ readonly ready: boolean;
136
+
137
+ /**
138
+ * Current connection status.
139
+ */
140
+ readonly currentStatus: SyncStatus;
141
+
142
+ readonly sdkVersion: string;
143
+
144
+ /**
145
+ * @experimental @alpha
146
+ * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
147
+ */
148
+ readonly triggers: TriggerManager;
149
+
150
+ readonly logger: PowerSyncLogger;
151
+
152
+ /**
153
+ * Schema used for the local database.
154
+ */
155
+ readonly schema: Schema;
156
+
157
+ /**
158
+ * The underlying database.
159
+ *
160
+ * For the most part, behavior is the same whether querying on the underlying database, or on {@link CommonPowerSyncDatabase}.
161
+ */
162
+ get database(): DBAdapter;
163
+
164
+ /**
165
+ * Whether a connection to the PowerSync service is currently open.
166
+ */
167
+ get connected(): boolean;
168
+
169
+ get connecting(): boolean;
170
+
171
+ /**
172
+ * @returns A promise which will resolve once initialization is completed.
173
+ */
174
+ waitForReady(): Promise<void>;
175
+
176
+ /**
177
+ * Wait for the first sync operation to complete.
178
+ *
179
+ * @param request - Either an abort signal (after which the promise will complete regardless of
180
+ * whether a full sync was completed) or an object providing an abort signal and a priority target.
181
+ * When a priority target is set, the promise may complete when all buckets with the given (or higher)
182
+ * priorities have been synchronized. This can be earlier than a complete sync.
183
+ * @returns A promise which will resolve once the first full sync has completed.
184
+ */
185
+ waitForFirstSync(request?: AbortSignal | { signal?: AbortSignal; priority?: number }): Promise<void>;
186
+
187
+ /**
188
+ * Waits for the first sync status for which the `status` callback returns a truthy value.
189
+ */
190
+ waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void>;
191
+
192
+ /**
193
+ * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
194
+ *
195
+ * Cannot be used while connected - this should only be called before {@link CommonPowerSyncDatabase.connect}.
196
+ */
197
+ updateSchema(schema: Schema): Promise<void>;
198
+
199
+ /**
200
+ * Wait for initialization to complete.
201
+ * While initializing is automatic, this helps to catch and report initialization errors.
202
+ */
203
+ init(): Promise<void>;
204
+
205
+ /**
206
+ * Connects to stream of events from the PowerSync instance.
207
+ */
208
+ connect(connector: PowerSyncBackendConnector, options?: SyncOptions): Promise<void>;
209
+
210
+ /**
211
+ * Close the sync connection.
212
+ *
213
+ * Use {@link CommonPowerSyncDatabase.connect} to connect again.
214
+ */
215
+ disconnect(): Promise<void>;
216
+
217
+ /**
218
+ * Disconnect and clear the database.
219
+ * Use this when logging out.
220
+ * The database can still be queried after this is called, but the tables
221
+ * would be empty.
222
+ *
223
+ * To preserve data in local-only tables, set clearLocal to false.
224
+ */
225
+ disconnectAndClear(options?: DisconnectAndClearOptions): Promise<void>;
226
+
227
+ /**
228
+ * Create a sync stream to query its status or to subscribe to it.
229
+ *
230
+ * @param name - The name of the stream to subscribe to.
231
+ * @param params - Optional parameters for the stream subscription.
232
+ * @returns A {@link SyncStream} instance that can be subscribed to.
233
+ */
234
+ syncStream(name: string, params?: Record<string, any>): SyncStream;
235
+
236
+ /**
237
+ * Close the database, releasing resources.
238
+ *
239
+ * Also disconnects any active connection.
240
+ *
241
+ * Once close is called, this connection cannot be used again - a new one
242
+ * must be constructed.
243
+ */
244
+ close(options?: PowerSyncCloseOptions): Promise<void>;
245
+
246
+ /**
247
+ * Get upload queue size estimate and count.
248
+ */
249
+ getUploadQueueStats(includeSize?: boolean): Promise<UploadQueueStats>;
250
+
251
+ /**
252
+ * Get a batch of CRUD data to upload.
253
+ *
254
+ * Returns null if there is no data to upload.
255
+ *
256
+ * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
257
+ *
258
+ * Once the data have been successfully uploaded, call {@link CrudBatch.complete} before
259
+ * requesting the next batch.
260
+ *
261
+ * Use the `limit` parameter to specify the maximum number of updates to return in a single
262
+ * batch.
263
+ *
264
+ * This method does include transaction ids in the result, but does not group
265
+ * data by transaction. One batch may contain data from multiple transactions,
266
+ * and a single transaction may be split over multiple batches.
267
+ *
268
+ * @param limit - Maximum number of CRUD entries to include in the batch
269
+ * @returns A batch of CRUD operations to upload, or null if there are none
270
+ */
271
+ getCrudBatch(limit?: number): Promise<CrudBatch | null>;
272
+
273
+ /**
274
+ * Get the next recorded transaction to upload.
275
+ *
276
+ * Returns null if there is no data to upload.
277
+ *
278
+ * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
279
+ *
280
+ * Once the data have been successfully uploaded, call {@link CrudTransaction.complete} before
281
+ * requesting the next transaction.
282
+ *
283
+ * Unlike {@link CommonPowerSyncDatabase.getCrudBatch}, this only returns data from a single transaction at a time.
284
+ * All data for the transaction is loaded into memory.
285
+ *
286
+ * @returns A transaction of CRUD operations to upload, or null if there are none
287
+ */
288
+ getNextCrudTransaction(): Promise<CrudTransaction | null>;
289
+
290
+ /**
291
+ * Returns an async iterator of completed transactions with local writes against the database.
292
+ *
293
+ * This is typically used from the {@link PowerSyncBackendConnector.uploadData} callback. Each entry emitted by the
294
+ * returned iterator is a full transaction containing all local writes made while that transaction was active.
295
+ *
296
+ * Unlike {@link CommonPowerSyncDatabase.getNextCrudTransaction}, which always returns the oldest transaction that hasn't been
297
+ * {@link CrudTransaction.complete}d yet, this iterator can be used to receive multiple transactions. Calling
298
+ * {@link CrudTransaction.complete} will mark that and all prior transactions emitted by the iterator as completed.
299
+ *
300
+ * This can be used to upload multiple transactions in a single batch, e.g with:
301
+ *
302
+ * ```JavaScript
303
+ * let lastTransaction = null;
304
+ * let batch = [];
305
+ *
306
+ * for await (const transaction of database.getCrudTransactions()) {
307
+ * batch.push(...transaction.crud);
308
+ * lastTransaction = transaction;
309
+ *
310
+ * if (batch.length > 10) {
311
+ * break;
312
+ * }
313
+ * }
314
+ * ```
315
+ *
316
+ * If there is no local data to upload, the async iterator complete without emitting any items.
317
+ *
318
+ * Note that iterating over async iterables requires a [polyfill](https://github.com/powersync-ja/powersync-js/tree/main/packages/react-native#babel-plugins-watched-queries)
319
+ * for React Native.
320
+ */
321
+ getCrudTransactions(): AsyncIterable<CrudTransaction, null>;
322
+
323
+ /**
324
+ * Get an unique client id for this database.
325
+ *
326
+ * The id is not reset when the database is cleared, only when the database is deleted.
327
+ *
328
+ * @returns A unique identifier for the database instance
329
+ */
330
+ getClientId(): Promise<string>;
331
+
332
+ /**
333
+ * Takes a read lock, without starting a transaction.
334
+ * In most cases, {@link CommonPowerSyncDatabase.readTransaction} should be used instead.
335
+ */
336
+ readLock<T>(callback: (db: LockContext) => Promise<T>): Promise<T>;
337
+
338
+ /**
339
+ * Takes a global lock, without starting a transaction.
340
+ * In most cases, {@link CommonPowerSyncDatabase.writeTransaction} should be used instead.
341
+ */
342
+ writeLock<T>(callback: (db: LockContext) => Promise<T>): Promise<T>;
343
+
344
+ /**
345
+ * Open a read-only transaction.
346
+ * Read transactions can run concurrently to a write transaction.
347
+ * Changes from any write transaction are not visible to read transactions started before it.
348
+ *
349
+ * @param callback - Function to execute within the transaction
350
+ * @param lockTimeout - Time in milliseconds to wait for a lock before throwing an error
351
+ * @returns The result of the callback
352
+ * @throws Error if the lock cannot be obtained within the timeout period
353
+ */
354
+ readTransaction<T>(callback: (tx: Transaction) => Promise<T>, lockTimeout?: number): Promise<T>;
355
+
356
+ /**
357
+ * Open a read-write transaction.
358
+ * This takes a global lock - only one write transaction can execute against the database at a time.
359
+ * Statements within the transaction must be done on the provided {@link Transaction} interface.
360
+ *
361
+ * @param callback - Function to execute within the transaction
362
+ * @param lockTimeout - Time in milliseconds to wait for a lock before throwing an error
363
+ * @returns The result of the callback
364
+ * @throws Error if the lock cannot be obtained within the timeout period
365
+ */
366
+ writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, lockTimeout?: number): Promise<T>;
367
+
368
+ /**
369
+ * This version of `watch` uses `AsyncGenerator`, for documentation see {@link CommonPowerSyncDatabase.watchWithAsyncGenerator}.
370
+ * Can be overloaded to use a callback handler instead, for documentation see {@link CommonPowerSyncDatabase.watchWithCallback}.
371
+ *
372
+ * @example
373
+ * ```javascript
374
+ * async *attachmentIds() {
375
+ * for await (const result of this.powersync.watch(
376
+ * `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
377
+ * []
378
+ * )) {
379
+ * yield result.rows?._array.map((r) => r.id) ?? [];
380
+ * }
381
+ * }
382
+ * ```
383
+ */
384
+ watch(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
385
+ /**
386
+ * See {@link CommonPowerSyncDatabase.watchWithCallback}.
387
+ *
388
+ * @example
389
+ * ```javascript
390
+ * onAttachmentIdsChange(onResult) {
391
+ * this.powersync.watch(
392
+ * `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
393
+ * [],
394
+ * {
395
+ * onResult: (result) => onResult(result.rows?._array.map((r) => r.id) ?? [])
396
+ * }
397
+ * );
398
+ * }
399
+ * ```
400
+ */
401
+ watch(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
402
+
403
+ /**
404
+ * Allows defining a query which can be used to build a {@link WatchedQuery}.
405
+ * The defined query will be executed with {@link CommonPowerSyncDatabase#getAll}.
406
+ * An optional mapper function can be provided to transform the results.
407
+ *
408
+ * @example
409
+ * ```javascript
410
+ * const watchedTodos = powersync.query({
411
+ * sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
412
+ * parameters: [],
413
+ * mapper: (row) => ({
414
+ * ...row,
415
+ * created_at: new Date(row.created_at as string)
416
+ * })
417
+ * })
418
+ * .watch()
419
+ * // OR use .differentialWatch() for fine-grained watches.
420
+ * ```
421
+ */
422
+ query<RowType>(query: ArrayQueryDefinition<RowType>): Query<RowType>;
423
+
424
+ /**
425
+ * Allows building a {@link WatchedQuery} using an existing {@link WatchCompatibleQuery}.
426
+ * The watched query will use the provided {@link WatchCompatibleQuery.execute} method to query results.
427
+ *
428
+ * @example
429
+ * ```javascript
430
+ *
431
+ * // Potentially a query from an ORM like Drizzle
432
+ * const query = db.select().from(lists);
433
+ *
434
+ * const watchedTodos = powersync.customQuery(query)
435
+ * .watch()
436
+ * // OR use .differentialWatch() for fine-grained watches.
437
+ * ```
438
+ */
439
+ customQuery<RowType>(query: WatchCompatibleQuery<RowType[]>): Query<RowType>;
440
+
441
+ /**
442
+ * Execute a read query every time the source tables are modified.
443
+ * Use {@link SQLOnChangeOptions.throttleMs} to specify the minimum interval between queries.
444
+ * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
445
+ *
446
+ * Note that the `onChange` callback member of the handler is required.
447
+ *
448
+ * @param sql - The SQL query to execute
449
+ * @param parameters - Optional array of parameters to bind to the query
450
+ * @param handler - Callbacks for handling results and errors
451
+ * @param options - Options for configuring watch behavior
452
+ */
453
+ watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
454
+
455
+ /**
456
+ * Execute a read query every time the source tables are modified.
457
+ * Use {@link SQLOnChangeOptions.throttleMs} to specify the minimum interval between queries.
458
+ * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
459
+ *
460
+ * @param sql - The SQL query to execute
461
+ * @param parameters - Optional array of parameters to bind to the query
462
+ * @param options - Options for configuring watch behavior
463
+ * @returns An AsyncIterable that yields QueryResults whenever the data changes
464
+ */
465
+ watchWithAsyncGenerator(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
466
+
467
+ /**
468
+ * Resolves the list of tables that are used in a SQL query.
469
+ * If tables are specified in the options, those are used directly.
470
+ * Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.
471
+ *
472
+ * @param sql - The SQL query to analyze
473
+ * @param parameters - Optional parameters for the SQL query
474
+ * @param options - Optional watch options that may contain explicit table list
475
+ * @returns Array of table names that the query depends on
476
+ */
477
+ resolveTables(sql: string, parameters?: any[], options?: SQLWatchOptions): Promise<string[]>;
478
+
479
+ /**
480
+ * This version of `onChange` uses `AsyncGenerator`, for documentation see {@link CommonPowerSyncDatabase.onChangeWithAsyncGenerator}.
481
+ * Can be overloaded to use a callback handler instead, for documentation see {@link CommonPowerSyncDatabase.onChangeWithCallback}.
482
+ *
483
+ * @example
484
+ * ```javascript
485
+ * async monitorChanges() {
486
+ * for await (const event of this.powersync.onChange({tables: ['todos']})) {
487
+ * console.log('Detected change event:', event);
488
+ * }
489
+ * }
490
+ * ```
491
+ */
492
+ onChange(options?: SQLOnChangeOptions): AsyncIterable<WatchOnChangeEvent>;
493
+ /**
494
+ * See {@link CommonPowerSyncDatabase.onChangeWithCallback}.
495
+ *
496
+ * @example
497
+ * ```javascript
498
+ * monitorChanges() {
499
+ * this.powersync.onChange({
500
+ * onChange: (event) => {
501
+ * console.log('Change detected:', event);
502
+ * }
503
+ * }, { tables: ['todos'] });
504
+ * }
505
+ * ```
506
+ */
507
+ onChange(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
508
+
509
+ /**
510
+ * Invoke the provided callback on any changes to any of the specified tables.
511
+ *
512
+ * This is preferred over {@link CommonPowerSyncDatabase.watchWithCallback} when multiple queries need to be performed
513
+ * together when data is changed.
514
+ *
515
+ * Note that the `onChange` callback member of the handler is required.
516
+ *
517
+ * @param handler - Callbacks for handling change events and errors
518
+ * @param options - Options for configuring watch behavior
519
+ * @returns A dispose function to stop watching for changes
520
+ */
521
+ onChangeWithCallback(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
522
+
523
+ /**
524
+ * Create a Stream of changes to any of the specified tables.
525
+ *
526
+ * This is preferred over {@link CommonPowerSyncDatabase.watchWithAsyncGenerator} when multiple queries need to be
527
+ * performed together when data is changed.
528
+ *
529
+ * Note: do not declare this as `async *onChange` as it will not work in React Native.
530
+ *
531
+ * @param options - Options for configuring watch behavior
532
+ * @returns An AsyncIterable that yields change events whenever the specified tables change
533
+ */
534
+ onChangeWithAsyncGenerator(options?: SQLWatchOptions): AsyncIterable<WatchOnChangeEvent>;
535
+
536
+ /**
537
+ * @internal
538
+ */
539
+ createMutex(): Mutex;
540
+ }
@@ -8,12 +8,16 @@ import { WatchedQueryOptions } from './watched/WatchedQuery.js';
8
8
 
9
9
  /**
10
10
  * Query parameters for {@link ArrayQueryDefinition#parameters}
11
+ *
12
+ * @public
11
13
  */
12
14
  export type QueryParam = string | number | boolean | null | undefined | bigint | Uint8Array;
13
15
 
14
16
  /**
15
17
  * Options for building a query with {@link AbstractPowerSyncDatabase#query}.
16
18
  * This query will be executed with {@link AbstractPowerSyncDatabase#getAll}.
19
+ *
20
+ * @public
17
21
  */
18
22
  export interface ArrayQueryDefinition<RowType = unknown> {
19
23
  sql: string;
@@ -33,6 +37,8 @@ export interface ArrayQueryDefinition<RowType = unknown> {
33
37
 
34
38
  /**
35
39
  * Options for {@link Query#watch}.
40
+ *
41
+ * @public
36
42
  */
37
43
  export interface StandardWatchedQueryOptions<RowType> extends WatchedQueryOptions {
38
44
  /**
@@ -59,6 +65,9 @@ export interface StandardWatchedQueryOptions<RowType> extends WatchedQueryOption
59
65
  placeholderData?: RowType[];
60
66
  }
61
67
 
68
+ /**
69
+ * @public
70
+ */
62
71
  export interface Query<RowType> {
63
72
  /**
64
73
  * Creates a {@link WatchedQuery} which watches and emits results of the linked query.
@@ -1,5 +1,8 @@
1
1
  import { DBAdapter } from '../db/DBAdapter.js';
2
2
 
3
+ /**
4
+ * @public
5
+ */
3
6
  export interface SQLOpenOptions {
4
7
  /**
5
8
  * Filename for the database.
@@ -25,6 +28,9 @@ export interface SQLOpenOptions {
25
28
  debugMode?: boolean;
26
29
  }
27
30
 
31
+ /**
32
+ * @public
33
+ */
28
34
  export interface SQLOpenFactory {
29
35
  /**
30
36
  * Opens a connection adapter to a SQLite DB
@@ -33,23 +39,45 @@ export interface SQLOpenFactory {
33
39
  }
34
40
 
35
41
  /**
36
- * Tests if the input is a {@link SQLOpenOptions}
37
- */
38
- export const isSQLOpenOptions = (test: any): test is SQLOpenOptions => {
39
- // typeof null is `object`, but you cannot use the `in` operator on `null.
40
- return test && typeof test == 'object' && 'dbFilename' in test;
41
- };
42
-
43
- /**
44
- * Tests if input is a {@link SQLOpenFactory}
45
- */
46
- export const isSQLOpenFactory = (test: any): test is SQLOpenFactory => {
47
- return typeof test?.openDB == 'function';
48
- };
49
-
50
- /**
51
- * Tests if input is a {@link DBAdapter}
42
+ * A source describing how to open databases.
43
+ *
44
+ * - A {@link DBAdapter} providing access to an opened SQLite connection pool.
45
+ * - A {@link SQLOpenFactory} which will be used to open a SQLite connection pool lazily.
46
+ * - A {@link SQLOpenOptions} for opening a SQLite connection with a default {@link SQLOpenFactory} for the current
47
+ * platform.
48
+ *
49
+ * For most apps, using the `database` key with {@link SQLOpenOptions} is the easiest and recommended option.
50
+ *
51
+ * @public
52
52
  */
53
- export const isDBAdapter = (test: any): test is DBAdapter => {
54
- return typeof test?.writeTransaction == 'function';
55
- };
53
+ export type DatabaseSource<OpenOptions extends SQLOpenOptions = SQLOpenOptions> =
54
+ | {
55
+ /**
56
+ * Wrap an opened {@link DBAdapter} as a PowerSync database instance.
57
+ *
58
+ * This is primarily useful for testing. On most platforms, PowerSync would open a pool of SQLite connections by
59
+ * default. This option allows using a single in-memory instance instead. It can also be used to customize the
60
+ * database used by default, e.g. to install additional logging on SQL statements by intercepting methods.
61
+ */
62
+ opened: DBAdapter;
63
+ }
64
+ | {
65
+ /**
66
+ * Construct a PowerSync database that will call {@link SQLOpenFactory.openDB} when opened.
67
+ *
68
+ * On most SDKs, passing {@link SQLOpenOptions} is a better option. An exception is React Native, where using an
69
+ * [OP-SQLite factory](https://docs.powersync.com/client-sdks/reference/react-native-and-expo#op-sqlite) is
70
+ * recommended.
71
+ */
72
+ factory: SQLOpenFactory;
73
+ }
74
+ | {
75
+ /**
76
+ * Construct a PowerSync database opening a connection pool from the {@link SQLOpenOptions}.
77
+ *
78
+ * At the very least, options include the {@link SQLOpenOptions.dbFilename} to open. Depending on the PowerSync
79
+ * SDK used, additional options are available. For example, the web SDK allows configuring the virtual file system
80
+ * implementation used to persist files on the web too.
81
+ */
82
+ database: OpenOptions;
83
+ };