@powersync/common 1.57.1 → 2.0.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 (219) 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 +6 -6
  5. package/lib/attachments/AttachmentQueue.js +9 -8
  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/Schema.d.ts +2 -2
  11. package/lib/attachments/SyncingService.d.ts +2 -2
  12. package/lib/attachments/SyncingService.js +21 -6
  13. package/lib/attachments/SyncingService.js.map +1 -1
  14. package/lib/client/{AbstractPowerSyncDatabase.d.ts → CommonPowerSyncDatabase.d.ts} +56 -232
  15. package/lib/client/CommonPowerSyncDatabase.js +2 -0
  16. package/lib/client/CommonPowerSyncDatabase.js.map +1 -0
  17. package/lib/client/SQLOpenFactory.d.ts +35 -13
  18. package/lib/client/SQLOpenFactory.js +1 -25
  19. package/lib/client/SQLOpenFactory.js.map +1 -1
  20. package/lib/client/compilableQueryWatch.d.ts +2 -2
  21. package/lib/client/compilableQueryWatch.js +1 -2
  22. package/lib/client/compilableQueryWatch.js.map +1 -1
  23. package/lib/client/connection/PowerSyncBackendConnector.d.ts +3 -3
  24. package/lib/client/runOnSchemaChange.d.ts +2 -2
  25. package/lib/client/runOnSchemaChange.js.map +1 -1
  26. package/lib/client/sync/bucket/CrudEntry.d.ts +3 -34
  27. package/lib/client/sync/bucket/CrudEntry.js +0 -99
  28. package/lib/client/sync/bucket/CrudEntry.js.map +1 -1
  29. package/lib/client/sync/options.d.ts +65 -0
  30. package/lib/client/sync/options.js +25 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/sync-streams.d.ts +1 -1
  33. package/lib/client/triggers/TriggerManager.d.ts +9 -38
  34. package/lib/client/watched/GetAllQuery.d.ts +3 -3
  35. package/lib/client/watched/GetAllQuery.js +1 -1
  36. package/lib/client/watched/GetAllQuery.js.map +1 -1
  37. package/lib/client/watched/WatchedQuery.d.ts +2 -10
  38. package/lib/client/watched/WatchedQuery.js +0 -11
  39. package/lib/client/watched/WatchedQuery.js.map +1 -1
  40. package/lib/client/watched/processors/DifferentialQueryProcessor.d.ts +0 -50
  41. package/lib/client/watched/processors/DifferentialQueryProcessor.js +1 -176
  42. package/lib/client/watched/processors/DifferentialQueryProcessor.js.map +1 -1
  43. package/lib/client/watched/processors/OnChangeQueryProcessor.d.ts +0 -22
  44. package/lib/client/watched/processors/OnChangeQueryProcessor.js +1 -82
  45. package/lib/client/watched/processors/OnChangeQueryProcessor.js.map +1 -1
  46. package/lib/db/DBAdapter.d.ts +72 -154
  47. package/lib/db/DBAdapter.js +70 -108
  48. package/lib/db/DBAdapter.js.map +1 -1
  49. package/lib/db/QueryResult.d.ts +104 -0
  50. package/lib/db/QueryResult.js +96 -0
  51. package/lib/db/QueryResult.js.map +1 -0
  52. package/lib/db/crud/SyncProgress.d.ts +1 -13
  53. package/lib/db/crud/SyncProgress.js +1 -62
  54. package/lib/db/crud/SyncProgress.js.map +1 -1
  55. package/lib/db/crud/SyncStatus.d.ts +32 -66
  56. package/lib/db/crud/SyncStatus.js +1 -253
  57. package/lib/db/crud/SyncStatus.js.map +1 -1
  58. package/lib/db/schema/Column.d.ts +0 -7
  59. package/lib/db/schema/Column.js +0 -7
  60. package/lib/db/schema/Column.js.map +1 -1
  61. package/lib/db/schema/Index.d.ts +2 -6
  62. package/lib/db/schema/Index.js +1 -4
  63. package/lib/db/schema/Index.js.map +1 -1
  64. package/lib/db/schema/IndexedColumn.d.ts +2 -6
  65. package/lib/db/schema/IndexedColumn.js +1 -4
  66. package/lib/db/schema/IndexedColumn.js.map +1 -1
  67. package/lib/db/schema/Schema.d.ts +4 -28
  68. package/lib/db/schema/Schema.js.map +1 -1
  69. package/lib/db/schema/Table.d.ts +50 -96
  70. package/lib/db/schema/Table.js +83 -91
  71. package/lib/db/schema/Table.js.map +1 -1
  72. package/lib/index.d.ts +5 -21
  73. package/lib/index.js +5 -22
  74. package/lib/index.js.map +1 -1
  75. package/lib/utils/BaseObserver.d.ts +1 -1
  76. package/lib/utils/BaseObserver.js +1 -1
  77. package/lib/utils/Logger.d.ts +52 -23
  78. package/lib/utils/Logger.js +35 -33
  79. package/lib/utils/Logger.js.map +1 -1
  80. package/lib/utils/MetaBaseObserver.d.ts +11 -11
  81. package/lib/utils/MetaBaseObserver.js +1 -50
  82. package/lib/utils/MetaBaseObserver.js.map +1 -1
  83. package/lib/utils/mutex.d.ts +3 -53
  84. package/lib/utils/mutex.js +1 -156
  85. package/lib/utils/mutex.js.map +1 -1
  86. package/package.json +8 -45
  87. package/src/attachments/AttachmentContext.ts +11 -10
  88. package/src/attachments/AttachmentQueue.ts +15 -14
  89. package/src/attachments/AttachmentService.ts +7 -6
  90. package/src/attachments/Schema.ts +2 -2
  91. package/src/attachments/SyncingService.ts +23 -9
  92. package/src/client/CommonPowerSyncDatabase.ts +540 -0
  93. package/src/client/SQLOpenFactory.ts +38 -22
  94. package/src/client/compilableQueryWatch.ts +3 -4
  95. package/src/client/connection/PowerSyncBackendConnector.ts +3 -3
  96. package/src/client/runOnSchemaChange.ts +2 -2
  97. package/src/client/sync/bucket/CrudEntry.ts +4 -104
  98. package/src/client/sync/options.ts +77 -0
  99. package/src/client/sync/sync-streams.ts +1 -1
  100. package/src/client/triggers/TriggerManager.ts +10 -41
  101. package/src/client/watched/GetAllQuery.ts +3 -3
  102. package/src/client/watched/WatchedQuery.ts +2 -15
  103. package/src/client/watched/processors/DifferentialQueryProcessor.ts +0 -223
  104. package/src/client/watched/processors/OnChangeQueryProcessor.ts +0 -111
  105. package/src/db/DBAdapter.ts +141 -226
  106. package/src/db/QueryResult.ts +195 -0
  107. package/src/db/crud/SyncProgress.ts +2 -42
  108. package/src/db/crud/SyncStatus.ts +45 -220
  109. package/src/db/schema/Column.ts +0 -8
  110. package/src/db/schema/Index.ts +3 -6
  111. package/src/db/schema/IndexedColumn.ts +3 -6
  112. package/src/db/schema/Schema.ts +4 -4
  113. package/src/db/schema/Table.ts +111 -186
  114. package/src/index.ts +5 -21
  115. package/src/utils/BaseObserver.ts +1 -1
  116. package/src/utils/Logger.ts +80 -34
  117. package/src/utils/MetaBaseObserver.ts +14 -60
  118. package/src/utils/mutex.ts +4 -201
  119. package/dist/bundle.cjs +0 -14390
  120. package/dist/bundle.cjs.map +0 -1
  121. package/dist/bundle.mjs +0 -14309
  122. package/dist/bundle.mjs.map +0 -1
  123. package/dist/bundle.node.cjs +0 -12021
  124. package/dist/bundle.node.cjs.map +0 -1
  125. package/dist/bundle.node.mjs +0 -11940
  126. package/dist/bundle.node.mjs.map +0 -1
  127. package/dist/index.d.cts +0 -4651
  128. package/legacy/sync_protocol.d.ts +0 -103
  129. package/lib/client/AbstractPowerSyncDatabase.js +0 -990
  130. package/lib/client/AbstractPowerSyncDatabase.js.map +0 -1
  131. package/lib/client/AbstractPowerSyncOpenFactory.d.ts +0 -28
  132. package/lib/client/AbstractPowerSyncOpenFactory.js +0 -28
  133. package/lib/client/AbstractPowerSyncOpenFactory.js.map +0 -1
  134. package/lib/client/ConnectionManager.d.ts +0 -115
  135. package/lib/client/ConnectionManager.js +0 -294
  136. package/lib/client/ConnectionManager.js.map +0 -1
  137. package/lib/client/CustomQuery.d.ts +0 -22
  138. package/lib/client/CustomQuery.js +0 -43
  139. package/lib/client/CustomQuery.js.map +0 -1
  140. package/lib/client/constants.d.ts +0 -4
  141. package/lib/client/constants.js +0 -5
  142. package/lib/client/constants.js.map +0 -1
  143. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +0 -56
  144. package/lib/client/sync/bucket/BucketStorageAdapter.js +0 -29
  145. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +0 -1
  146. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +0 -37
  147. package/lib/client/sync/bucket/SqliteBucketStorage.js +0 -165
  148. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +0 -1
  149. package/lib/client/sync/stream/AbstractRemote.d.ts +0 -180
  150. package/lib/client/sync/stream/AbstractRemote.js +0 -505
  151. package/lib/client/sync/stream/AbstractRemote.js.map +0 -1
  152. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +0 -265
  153. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +0 -705
  154. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +0 -1
  155. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +0 -15
  156. package/lib/client/sync/stream/WebsocketClientTransport.js +0 -62
  157. package/lib/client/sync/stream/WebsocketClientTransport.js.map +0 -1
  158. package/lib/client/sync/stream/core-instruction.d.ts +0 -77
  159. package/lib/client/sync/stream/core-instruction.js +0 -30
  160. package/lib/client/sync/stream/core-instruction.js.map +0 -1
  161. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +0 -6
  162. package/lib/client/triggers/MemoryTriggerClaimManager.js +0 -21
  163. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +0 -1
  164. package/lib/client/triggers/TriggerManagerImpl.d.ts +0 -39
  165. package/lib/client/triggers/TriggerManagerImpl.js +0 -410
  166. package/lib/client/triggers/TriggerManagerImpl.js.map +0 -1
  167. package/lib/client/watched/processors/AbstractQueryProcessor.d.ts +0 -68
  168. package/lib/client/watched/processors/AbstractQueryProcessor.js +0 -151
  169. package/lib/client/watched/processors/AbstractQueryProcessor.js.map +0 -1
  170. package/lib/db/ConnectionClosedError.d.ts +0 -12
  171. package/lib/db/ConnectionClosedError.js +0 -23
  172. package/lib/db/ConnectionClosedError.js.map +0 -1
  173. package/lib/db/schema/TableV2.d.ts +0 -11
  174. package/lib/db/schema/TableV2.js +0 -11
  175. package/lib/db/schema/TableV2.js.map +0 -1
  176. package/lib/utils/AbortOperation.d.ts +0 -11
  177. package/lib/utils/AbortOperation.js +0 -21
  178. package/lib/utils/AbortOperation.js.map +0 -1
  179. package/lib/utils/ControlledExecutor.d.ts +0 -31
  180. package/lib/utils/ControlledExecutor.js +0 -54
  181. package/lib/utils/ControlledExecutor.js.map +0 -1
  182. package/lib/utils/async.d.ts +0 -46
  183. package/lib/utils/async.js +0 -147
  184. package/lib/utils/async.js.map +0 -1
  185. package/lib/utils/compatibility.d.ts +0 -8
  186. package/lib/utils/compatibility.js +0 -9
  187. package/lib/utils/compatibility.js.map +0 -1
  188. package/lib/utils/parseQuery.d.ts +0 -12
  189. package/lib/utils/parseQuery.js +0 -20
  190. package/lib/utils/parseQuery.js.map +0 -1
  191. package/lib/utils/queue.d.ts +0 -16
  192. package/lib/utils/queue.js +0 -42
  193. package/lib/utils/queue.js.map +0 -1
  194. package/lib/utils/stream_transform.d.ts +0 -41
  195. package/lib/utils/stream_transform.js +0 -211
  196. package/lib/utils/stream_transform.js.map +0 -1
  197. package/src/client/AbstractPowerSyncDatabase.ts +0 -1408
  198. package/src/client/AbstractPowerSyncOpenFactory.ts +0 -45
  199. package/src/client/ConnectionManager.ts +0 -405
  200. package/src/client/CustomQuery.ts +0 -56
  201. package/src/client/constants.ts +0 -4
  202. package/src/client/sync/bucket/BucketStorageAdapter.ts +0 -65
  203. package/src/client/sync/bucket/SqliteBucketStorage.ts +0 -202
  204. package/src/client/sync/stream/AbstractRemote.ts +0 -644
  205. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +0 -970
  206. package/src/client/sync/stream/WebsocketClientTransport.ts +0 -82
  207. package/src/client/sync/stream/core-instruction.ts +0 -109
  208. package/src/client/triggers/MemoryTriggerClaimManager.ts +0 -25
  209. package/src/client/triggers/TriggerManagerImpl.ts +0 -501
  210. package/src/client/watched/processors/AbstractQueryProcessor.ts +0 -226
  211. package/src/db/ConnectionClosedError.ts +0 -25
  212. package/src/db/schema/TableV2.ts +0 -11
  213. package/src/utils/AbortOperation.ts +0 -19
  214. package/src/utils/ControlledExecutor.ts +0 -78
  215. package/src/utils/async.ts +0 -185
  216. package/src/utils/compatibility.ts +0 -9
  217. package/src/utils/parseQuery.ts +0 -31
  218. package/src/utils/queue.ts +0 -48
  219. package/src/utils/stream_transform.ts +0 -260
package/dist/index.d.cts DELETED
@@ -1,4651 +0,0 @@
1
- import Logger, { ILogger, ILogLevel } from 'js-logger';
2
- export { GlobalLogger, ILogHandler, ILogLevel, ILogger, ILoggerOpts } from 'js-logger';
3
- import { fetch } from 'cross-fetch';
4
-
5
- /**
6
- * @public
7
- */
8
- interface Disposable {
9
- dispose: () => Promise<void> | void;
10
- }
11
- /**
12
- * @public
13
- */
14
- type BaseListener = Record<string, ((...event: any) => any) | undefined>;
15
- /**
16
- * @public
17
- */
18
- interface BaseObserverInterface<T extends BaseListener> {
19
- registerListener(listener: Partial<T>): () => void;
20
- }
21
- /**
22
- * @internal
23
- */
24
- declare class BaseObserver<T extends BaseListener = BaseListener> implements BaseObserverInterface<T> {
25
- protected listeners: Set<Partial<T>>;
26
- constructor();
27
- dispose(): void;
28
- /**
29
- * Register a listener for updates to the PowerSync client.
30
- */
31
- registerListener(listener: Partial<T>): () => void;
32
- iterateListeners(cb: (listener: Partial<T>) => any): void;
33
- iterateAsyncListeners(cb: (listener: Partial<T>) => Promise<any>): Promise<void>;
34
- }
35
-
36
- /**
37
- * Set of generic interfaces to allow PowerSync compatibility with
38
- * different SQLite DB implementations.
39
- */
40
-
41
- /**
42
- * TODO most of these types could be exported to a common `types` package
43
- * which is used by the DB adapter libraries as well.
44
- */
45
- /**
46
- * Object returned by SQL Query executions.
47
- *
48
- * @public
49
- */
50
- type QueryResult = {
51
- /** Represents the auto-generated row id if applicable. */
52
- insertId?: number;
53
- /**
54
- * Number of affected rows reported by SQLite for a write query.
55
- *
56
- * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
57
- * `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
58
- * Use a `RETURNING` clause and inspect `rows` when you need to confirm which rows changed.
59
- */
60
- rowsAffected: number;
61
- /** if status is undefined or 0 this object will contain the query results */
62
- rows?: {
63
- /** Raw array with all dataset */
64
- _array: any[];
65
- /** The length of the dataset */
66
- length: number;
67
- /** A convenience function to acess the index based the row object
68
- * @param idx - the row index
69
- * @returns the row structure identified by column names
70
- */
71
- item: (idx: number) => any;
72
- };
73
- };
74
- /**
75
- * @public
76
- */
77
- interface DBGetUtils {
78
- /** Execute a read-only query and return results. */
79
- getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
80
- /** Execute a read-only query and return the first result, or null if the ResultSet is empty. */
81
- getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
82
- /** Execute a read-only query and return the first result, error if the ResultSet is empty. */
83
- get<T>(sql: string, parameters?: any[]): Promise<T>;
84
- }
85
- /**
86
- * @public
87
- */
88
- interface SqlExecutor {
89
- /** Execute a single write statement. */
90
- execute: (query: string, params?: any[] | undefined) => Promise<QueryResult>;
91
- /**
92
- * Execute a single write statement and return raw results.
93
- * Unlike `execute`, which returns an object with structured key-value pairs,
94
- * `executeRaw` returns a nested array of raw values, where each row is
95
- * represented as an array of column values without field names.
96
- *
97
- * Example result:
98
- *
99
- * ```JavaScript
100
- * [ [ '1', 'list 1', '33', 'Post content', '1' ] ]
101
- * ```
102
- *
103
- * Where as `execute`'s `rows._array` would have been:
104
- *
105
- * ```JavaScript
106
- * [ { id: '33', name: 'list 1', content: 'Post content', list_id: '1' } ]
107
- * ```
108
- */
109
- executeRaw: (query: string, params?: any[] | undefined) => Promise<any[][]>;
110
- executeBatch: (query: string, params?: any[][]) => Promise<QueryResult>;
111
- }
112
- /**
113
- * @public
114
- */
115
- interface LockContext extends SqlExecutor, DBGetUtils {
116
- /**
117
- * How the connection has been opened.
118
- *
119
- * `writer` indicates that the lock context is capable of writing to the database.
120
- * `queryOnly` indicates that the lock context has been opened in a readwrite mode, but a `PRAGMA query_only = TRUE`
121
- * disabled writes.
122
- * `readOnly` indicates that the lock context has been opened by passing `SQLITE_OPEN_READONLY` to `sqlite3_open_v2`.
123
- */
124
- connectionType?: 'writer' | 'queryOnly' | 'readOnly';
125
- }
126
- /**
127
- * Implements {@link DBGetUtils} on a {@link SqlExecutor}.
128
- *
129
- * @internal
130
- */
131
- declare function DBGetUtilsDefaultMixin<TBase extends new (...args: any[]) => Omit<SqlExecutor, 'executeBatch'>>(Base: TBase): {
132
- new (...args: any[]): {
133
- getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
134
- getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
135
- get<T>(sql: string, parameters?: any[]): Promise<T>;
136
- executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
137
- execute: (query: string, params?: any[] | undefined) => Promise<QueryResult>;
138
- executeRaw: (query: string, params?: any[] | undefined) => Promise<any[][]>;
139
- };
140
- } & TBase;
141
- /**
142
- * @public
143
- */
144
- interface Transaction extends LockContext {
145
- /** Commit multiple changes to the local DB using the Transaction context. */
146
- commit: () => Promise<QueryResult>;
147
- /** Roll back multiple attempted changes using the Transaction context. */
148
- rollback: () => Promise<QueryResult>;
149
- }
150
- /**
151
- * Update table operation numbers from SQLite
152
- *
153
- * @public
154
- */
155
- declare enum RowUpdateType {
156
- SQLITE_INSERT = 18,
157
- SQLITE_DELETE = 9,
158
- SQLITE_UPDATE = 23
159
- }
160
- /**
161
- * @public
162
- */
163
- interface TableUpdateOperation {
164
- opType: RowUpdateType;
165
- rowId: number;
166
- }
167
- /**
168
- * Notification of an update to one or more tables, for the purpose of realtime change notifications.
169
- *
170
- * @public
171
- */
172
- interface UpdateNotification extends TableUpdateOperation {
173
- table: string;
174
- }
175
- /**
176
- * @public
177
- */
178
- interface BatchedUpdateNotification {
179
- rawUpdates: UpdateNotification[];
180
- tables: string[];
181
- groupedUpdates: Record<string, TableUpdateOperation[]>;
182
- }
183
- /**
184
- * @public
185
- */
186
- interface DBAdapterListener extends BaseListener {
187
- /**
188
- * Listener for table updates.
189
- * Allows for single table updates in order to maintain API compatibility
190
- * without the need for a major version bump
191
- * The DB adapter can also batch update notifications if supported.
192
- */
193
- tablesUpdated: (updateNotification: BatchedUpdateNotification | UpdateNotification) => void;
194
- }
195
- /**
196
- * @public
197
- */
198
- interface DBLockOptions {
199
- timeoutMs?: number;
200
- }
201
- /**
202
- * @public
203
- */
204
- interface ConnectionPool extends BaseObserverInterface<DBAdapterListener> {
205
- name: string;
206
- close: () => void | Promise<void>;
207
- readLock: <T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions) => Promise<T>;
208
- writeLock: <T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions) => Promise<T>;
209
- /**
210
- * This method refreshes the schema information across all connections. This is for advanced use cases, and should generally not be needed.
211
- */
212
- refreshSchema: () => Promise<void>;
213
- }
214
- /**
215
- * @public
216
- */
217
- interface DBAdapter extends ConnectionPool, SqlExecutor, DBGetUtils {
218
- readTransaction: <T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions) => Promise<T>;
219
- writeTransaction: <T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions) => Promise<T>;
220
- }
221
- /**
222
- * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool#readLock} and
223
- * {@link ConnectionPool#writeLock}.
224
- *
225
- * @internal
226
- */
227
- declare function DBAdapterDefaultMixin<TBase extends new (...args: any[]) => ConnectionPool>(Base: TBase): {
228
- new (...args: any[]): {
229
- readTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T>;
230
- writeTransaction<T>(fn: (tx: Transaction) => Promise<T>, options?: DBLockOptions): Promise<T>;
231
- getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
232
- getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
233
- get<T>(sql: string, parameters?: any[]): Promise<T>;
234
- execute(query: string, params?: any[]): Promise<QueryResult>;
235
- executeRaw(query: string, params?: any[]): Promise<any[][]>;
236
- executeBatch(query: string, params?: any[][]): Promise<QueryResult>;
237
- name: string;
238
- close: () => void | Promise<void>;
239
- readLock: <T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions) => Promise<T>;
240
- writeLock: <T>(fn: (tx: LockContext) => Promise<T>, options?: DBLockOptions) => Promise<T>;
241
- /**
242
- * This method refreshes the schema information across all connections. This is for advanced use cases, and should generally not be needed.
243
- */
244
- refreshSchema: () => Promise<void>;
245
- registerListener(listener: Partial<DBAdapterListener>): () => void;
246
- };
247
- } & TBase;
248
- /**
249
- * @internal
250
- */
251
- declare function isBatchedUpdateNotification(update: BatchedUpdateNotification | UpdateNotification): update is BatchedUpdateNotification;
252
- /**
253
- * @internal
254
- */
255
- declare function extractTableUpdates(update: BatchedUpdateNotification | UpdateNotification): string[];
256
-
257
- /**
258
- * 64-bit unsigned integer stored as a string in base-10.
259
- *
260
- * Not sortable as a string.
261
- *
262
- * @public
263
- */
264
- type OpId = string;
265
- /**
266
- * Type of local change.
267
- *
268
- * @public
269
- */
270
- declare enum UpdateType {
271
- /** Insert or replace existing row. All non-null columns are included in the data. Generated by INSERT statements. */
272
- PUT = "PUT",
273
- /** Update existing row. Contains the id, and value of each changed column. Generated by UPDATE statements. */
274
- PATCH = "PATCH",
275
- /** Delete existing row. Contains the id. Generated by DELETE statements. */
276
- DELETE = "DELETE"
277
- }
278
- /**
279
- * @internal
280
- */
281
- type CrudEntryJSON = {
282
- id: string;
283
- data: string;
284
- tx_id?: number;
285
- };
286
- /**
287
- * The output JSON seems to be a third type of JSON, not the same as the input JSON.
288
- */
289
- type CrudEntryOutputJSON = {
290
- op_id: number;
291
- op: UpdateType;
292
- type: string;
293
- id: string;
294
- tx_id?: number;
295
- data?: Record<string, any>;
296
- old?: Record<string, any>;
297
- metadata?: string;
298
- };
299
- /**
300
- * A single client-side change.
301
- *
302
- * @public
303
- */
304
- declare class CrudEntry {
305
- /**
306
- * Auto-incrementing client-side id.
307
- */
308
- clientId: number;
309
- /**
310
- * ID of the changed row.
311
- */
312
- id: string;
313
- /**
314
- * Type of change.
315
- */
316
- op: UpdateType;
317
- /**
318
- * Data associated with the change.
319
- */
320
- opData?: Record<string, any>;
321
- /**
322
- * For tables where the `trackPreviousValues` option has been enabled, this tracks previous values for
323
- * `UPDATE` and `DELETE` statements.
324
- */
325
- previousValues?: Record<string, any>;
326
- /**
327
- * Table that contained the change.
328
- */
329
- table: string;
330
- /**
331
- * Auto-incrementing transaction id. This is the same for all operations within the same transaction.
332
- */
333
- transactionId?: number;
334
- /**
335
- * Client-side metadata attached with this write.
336
- *
337
- * This field is only available when the `trackMetadata` option was set to `true` when creating a table
338
- * and the insert or update statement set the `_metadata` column.
339
- */
340
- metadata?: string;
341
- static fromRow(dbRow: CrudEntryJSON): CrudEntry;
342
- constructor(clientId: number, op: UpdateType, table: string, id: string, transactionId?: number, opData?: Record<string, any>, previousValues?: Record<string, any>, metadata?: string);
343
- /**
344
- * Converts the change to JSON format.
345
- */
346
- toJSON(): CrudEntryOutputJSON;
347
- equals(entry: CrudEntry): boolean;
348
- /**
349
- * The hash code for this object.
350
- * @deprecated This should not be necessary in the JS SDK.
351
- * Use the @see CrudEntry#equals method instead.
352
- * TODO remove in the next major release.
353
- */
354
- hashCode(): string;
355
- /**
356
- * Generates an array for use in deep comparison operations
357
- */
358
- toComparisonArray(): (string | number | Record<string, any> | undefined)[];
359
- }
360
-
361
- /**
362
- * A batch of client-side changes.
363
- *
364
- * @public
365
- */
366
- declare class CrudBatch {
367
- /**
368
- * List of client-side changes.
369
- */
370
- crud: CrudEntry[];
371
- /**
372
- * true if there are more changes in the local queue.
373
- */
374
- haveMore: boolean;
375
- /**
376
- * Call to remove the changes from the local queue, once successfully uploaded.
377
- */
378
- complete: (writeCheckpoint?: string) => Promise<void>;
379
- constructor(
380
- /**
381
- * List of client-side changes.
382
- */
383
- crud: CrudEntry[],
384
- /**
385
- * true if there are more changes in the local queue.
386
- */
387
- haveMore: boolean,
388
- /**
389
- * Call to remove the changes from the local queue, once successfully uploaded.
390
- */
391
- complete: (writeCheckpoint?: string) => Promise<void>);
392
- }
393
-
394
- /**
395
- * @internal
396
- */
397
- declare enum PSInternalTable {
398
- DATA = "ps_data",
399
- CRUD = "ps_crud",
400
- BUCKETS = "ps_buckets",
401
- OPLOG = "ps_oplog",
402
- UNTYPED = "ps_untyped"
403
- }
404
- /**
405
- * @internal
406
- */
407
- declare enum PowerSyncControlCommand {
408
- PROCESS_TEXT_LINE = "line_text",
409
- PROCESS_BSON_LINE = "line_binary",
410
- STOP = "stop",
411
- START = "start",
412
- NOTIFY_TOKEN_REFRESHED = "refreshed_token",
413
- NOTIFY_CRUD_UPLOAD_COMPLETED = "completed_upload",
414
- UPDATE_SUBSCRIPTIONS = "update_subscriptions",
415
- /**
416
- * An `established` or `end` event for response streams.
417
- */
418
- CONNECTION_STATE = "connection"
419
- }
420
- /**
421
- * @internal
422
- */
423
- interface BucketStorageListener extends BaseListener {
424
- crudUpdate: () => void;
425
- }
426
- /**
427
- * @internal
428
- */
429
- interface BucketStorageAdapter extends BaseObserverInterface<BucketStorageListener>, Disposable {
430
- init(): Promise<void>;
431
- hasMigratedSubkeys(): Promise<boolean>;
432
- migrateToFixedSubkeys(): Promise<void>;
433
- nextCrudItem(): Promise<CrudEntry | undefined>;
434
- hasCrud(): Promise<boolean>;
435
- getCrudBatch(limit?: number): Promise<CrudBatch | null>;
436
- updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
437
- getMaxOpId(): string;
438
- /**
439
- * Get an unique client id.
440
- */
441
- getClientId(): Promise<string>;
442
- /**
443
- * Invokes the `powersync_control` function for the sync client.
444
- */
445
- control(op: PowerSyncControlCommand, payload: string | Uint8Array | null): Promise<string>;
446
- }
447
-
448
- /**
449
- * @public
450
- */
451
- interface PowerSyncCredentials {
452
- endpoint: string;
453
- token: string;
454
- expiresAt?: Date;
455
- }
456
-
457
- /**
458
- * An async iterator that can't be cancelled.
459
- *
460
- * To keep data flow simple, we always pass an explicit cancellation token when subscribing to async streams. Once the
461
- * `AbortSignal` aborts, iterators are supposed to clean up and then emit a final `{done: true}` event. This means
462
- * that there's no way to distinguish between streams that have completed normally and streams that have been cancelled,
463
- * but that is acceptable for our uses of this.
464
- *
465
- * @internal
466
- */
467
- type SimpleAsyncIterator<T> = Pick<AsyncIterator<T>, 'next'>;
468
-
469
- /**
470
- * @internal
471
- */
472
- type RemoteConnector = {
473
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
474
- invalidateCredentials?: () => void;
475
- };
476
- /**
477
- * @internal
478
- */
479
- declare const DEFAULT_REMOTE_LOGGER: Logger.ILogger;
480
- /**
481
- * @internal
482
- */
483
- type SyncStreamOptions = {
484
- path: string;
485
- data: unknown;
486
- headers?: Record<string, string>;
487
- abortSignal: AbortSignal;
488
- fetchOptions?: Request;
489
- };
490
- /**
491
- * @public
492
- */
493
- declare enum FetchStrategy {
494
- /**
495
- * Queues multiple sync events before processing, reducing round-trips.
496
- * This comes at the cost of more processing overhead, which may cause ACK timeouts on older/weaker devices for big enough datasets.
497
- */
498
- Buffered = "buffered",
499
- /**
500
- * Processes each sync event immediately before requesting the next.
501
- * This reduces processing overhead and improves real-time responsiveness.
502
- */
503
- Sequential = "sequential"
504
- }
505
- /**
506
- * @internal
507
- */
508
- type SocketSyncStreamOptions = SyncStreamOptions & {
509
- fetchStrategy: FetchStrategy;
510
- };
511
- /**
512
- * @internal
513
- */
514
- type FetchImplementation = typeof fetch;
515
- /**
516
- * Class wrapper for providing a fetch implementation.
517
- * The class wrapper is used to distinguish the fetchImplementation
518
- * option in [AbstractRemoteOptions] from the general fetch method
519
- * which is typeof "function"
520
- *
521
- * @internal
522
- */
523
- declare class FetchImplementationProvider {
524
- getFetch(): FetchImplementation;
525
- }
526
- /**
527
- * @internal
528
- */
529
- type AbstractRemoteOptions = {
530
- /**
531
- * Transforms the PowerSync base URL which might contain
532
- * `http(s)://` to the corresponding WebSocket variant
533
- * e.g. `ws(s)://`
534
- */
535
- socketUrlTransformer: (url: string) => string;
536
- /**
537
- * Optionally provide the fetch implementation to use.
538
- * Note that this usually needs to be bound to the global scope.
539
- * Binding should be done before passing here.
540
- */
541
- fetchImplementation: FetchImplementation | FetchImplementationProvider;
542
- /**
543
- * Optional options to pass directly to all `fetch` calls.
544
- *
545
- * This can include fields such as `dispatcher` (e.g. for proxy support),
546
- * `cache`, or any other fetch-compatible options.
547
- */
548
- fetchOptions?: {};
549
- };
550
- /**
551
- * @internal
552
- */
553
- declare const DEFAULT_REMOTE_OPTIONS: AbstractRemoteOptions;
554
- /**
555
- * @internal
556
- */
557
- declare abstract class AbstractRemote {
558
- protected connector: RemoteConnector;
559
- protected logger: ILogger;
560
- protected credentials: PowerSyncCredentials | null;
561
- protected options: AbstractRemoteOptions;
562
- constructor(connector: RemoteConnector, logger?: ILogger, options?: Partial<AbstractRemoteOptions>);
563
- /**
564
- * @returns a fetch implementation (function)
565
- * which can be called to perform fetch requests
566
- */
567
- get fetch(): FetchImplementation;
568
- /**
569
- * Get credentials currently cached, or fetch new credentials if none are
570
- * available.
571
- *
572
- * These credentials may have expired already.
573
- */
574
- getCredentials(): Promise<PowerSyncCredentials | null>;
575
- /**
576
- * Fetch a new set of credentials and cache it.
577
- *
578
- * Until this call succeeds, `getCredentials` will still return the
579
- * old credentials.
580
- *
581
- * This may be called before the current credentials have expired.
582
- */
583
- prefetchCredentials(): Promise<PowerSyncCredentials | null>;
584
- /**
585
- * Get credentials for PowerSync.
586
- *
587
- * This should always fetch a fresh set of credentials - don't use cached
588
- * values.
589
- */
590
- fetchCredentials(): Promise<PowerSyncCredentials | null>;
591
- /***
592
- * Immediately invalidate credentials.
593
- *
594
- * This may be called when the current credentials have expired.
595
- */
596
- invalidateCredentials(): void;
597
- getUserAgent(): string;
598
- protected buildRequest(path: string): Promise<{
599
- url: string;
600
- headers: {
601
- 'content-type': string;
602
- Authorization: string;
603
- 'x-user-agent': string;
604
- };
605
- }>;
606
- post(path: string, data: any, headers?: Record<string, string>): Promise<any>;
607
- get(path: string, headers?: Record<string, string>): Promise<any>;
608
- /**
609
- * @returns A text decoder decoding UTF-8. This is a method to allow patching it for Hermes which doesn't support the
610
- * builtin, without forcing us to bundle a polyfill with `@powersync/common`.
611
- */
612
- createTextDecoder(): TextDecoder;
613
- protected createSocket(url: string): WebSocket;
614
- /**
615
- * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
616
- *
617
- * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
618
- */
619
- socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>>;
620
- /**
621
- * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
622
- * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
623
- *
624
- * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
625
- */
626
- protected get supportsStreamingBinaryResponses(): boolean;
627
- /**
628
- * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
629
- * async iterator of byte blobs.
630
- *
631
- * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
632
- */
633
- protected fetchStreamRaw(options: SyncStreamOptions): Promise<{
634
- isBson: boolean;
635
- stream: SimpleAsyncIterator<Uint8Array>;
636
- }>;
637
- /**
638
- * Posts a `/sync/stream` request.
639
- *
640
- * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
641
- * `Uint8Array`s.
642
- */
643
- fetchStream(options: SyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array | string>>;
644
- }
645
-
646
- type JSONValue = string | number | boolean | null | undefined | JSONObject | JSONArray;
647
- interface JSONObject {
648
- [key: string]: JSONValue;
649
- }
650
- type JSONArray = JSONValue[];
651
- /**
652
- * @public
653
- */
654
- type StreamingSyncRequestParameterType = JSONValue;
655
-
656
- /**
657
- * @internal
658
- */
659
- declare enum LockType {
660
- CRUD = "crud",
661
- SYNC = "sync"
662
- }
663
- /**
664
- * @public
665
- */
666
- declare enum SyncStreamConnectionMethod {
667
- HTTP = "http",
668
- WEB_SOCKET = "web-socket"
669
- }
670
- /**
671
- * @deprecated Deprecated since {@link SyncClientImplementation.RUST} is the only option.
672
- * @public
673
- */
674
- declare enum SyncClientImplementation {
675
- /**
676
- * This implementation offloads the sync line decoding and handling into the PowerSync
677
- * core extension.
678
- *
679
- * This is the only option, as an older JavaScript client implementation has been removed from the SDK.
680
- *
681
- * ## Compatibility warning
682
- *
683
- * The Rust sync client stores sync data in a format that is slightly different than the one used
684
- * by the old JavaScript client. When adopting the {@link SyncClientImplementation.RUST} client on existing databases,
685
- * the PowerSync SDK will migrate the format automatically.
686
- *
687
- * SDK versions supporting both the JavaScript and the Rust client support both formats with the JavaScript client
688
- * implementaiton. However, downgrading to an SDK version that only supports the JavaScript client would not be
689
- * possible anymore. Problematic SDK versions have been released before 2025-06-09.
690
- */
691
- RUST = "rust"
692
- }
693
- /**
694
- * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
695
- *
696
- * @deprecated Deprecated since {@link SyncClientImplementation.RUST} is the only option.
697
- * @public
698
- */
699
- declare const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
700
- /**
701
- * Abstract Lock to be implemented by various JS environments
702
- *
703
- * @internal
704
- */
705
- interface LockOptions<T> {
706
- callback: () => Promise<T>;
707
- type: LockType;
708
- signal?: AbortSignal;
709
- }
710
- /**
711
- * @internal
712
- */
713
- interface AbstractStreamingSyncImplementationOptions extends RequiredAdditionalConnectionOptions {
714
- adapter: BucketStorageAdapter;
715
- subscriptions: SubscribedStream[];
716
- uploadCrud: () => Promise<void>;
717
- /**
718
- * An identifier for which PowerSync DB this sync implementation is
719
- * linked to. Most commonly DB name, but not restricted to DB name.
720
- */
721
- identifier?: string;
722
- logger?: ILogger;
723
- remote: AbstractRemote;
724
- }
725
- /**
726
- * @internal
727
- */
728
- interface StreamingSyncImplementationListener extends BaseListener {
729
- /**
730
- * Triggered whenever a status update has been attempted to be made or
731
- * refreshed.
732
- */
733
- statusUpdated?: ((statusUpdate: SyncStatusOptions) => void) | undefined;
734
- /**
735
- * Triggers whenever the status' members have changed in value
736
- */
737
- statusChanged?: ((status: SyncStatus) => void) | undefined;
738
- }
739
- /**
740
- * Configurable options to be used when connecting to the PowerSync
741
- * backend instance.
742
- *
743
- * @public
744
- */
745
- type PowerSyncConnectionOptions = Omit<InternalConnectionOptions, 'serializedSchema'>;
746
- /**
747
- * @internal
748
- */
749
- interface InternalConnectionOptions extends BaseConnectionOptions, AdditionalConnectionOptions {
750
- }
751
- /** @public */
752
- interface BaseConnectionOptions {
753
- /**
754
- * A set of metadata to be included in service logs.
755
- */
756
- appMetadata?: Record<string, string>;
757
- /**
758
- * @deprecated The Rust sync client is used unconditionally, so this option can't be configured.
759
- */
760
- clientImplementation?: SyncClientImplementation;
761
- /**
762
- * The connection method to use when streaming updates from
763
- * the PowerSync backend instance.
764
- * Defaults to a HTTP streaming connection.
765
- */
766
- connectionMethod?: SyncStreamConnectionMethod;
767
- /**
768
- * The fetch strategy to use when streaming updates from the PowerSync backend instance.
769
- */
770
- fetchStrategy?: FetchStrategy;
771
- /**
772
- * These parameters are passed to the sync rules, and will be available under the`user_parameters` object.
773
- */
774
- params?: Record<string, StreamingSyncRequestParameterType>;
775
- /**
776
- * Whether to include streams that have `auto_subscribe: true` in their definition.
777
- *
778
- * This defaults to `true`.
779
- */
780
- includeDefaultStreams?: boolean;
781
- /**
782
- * The serialized schema - mainly used to forward information about raw tables to the sync client.
783
- */
784
- serializedSchema?: any;
785
- }
786
- /** @internal */
787
- interface AdditionalConnectionOptions {
788
- /**
789
- * Delay for retrying sync streaming operations
790
- * from the PowerSync backend after an error occurs.
791
- */
792
- retryDelayMs?: number;
793
- /**
794
- * Backend Connector CRUD operations are throttled
795
- * to occur at most every `crudUploadThrottleMs`
796
- * milliseconds.
797
- */
798
- crudUploadThrottleMs?: number;
799
- }
800
- /** @internal */
801
- interface RequiredAdditionalConnectionOptions extends Required<AdditionalConnectionOptions> {
802
- subscriptions: SubscribedStream[];
803
- }
804
- /**
805
- * @internal
806
- */
807
- interface StreamingSyncImplementation extends BaseObserverInterface<StreamingSyncImplementationListener>, Disposable {
808
- /**
809
- * Connects to the sync service
810
- */
811
- connect(options?: InternalConnectionOptions): Promise<void>;
812
- /**
813
- * Disconnects from the sync services.
814
- * @throws if not connected or if abort is not controlled internally
815
- */
816
- disconnect(): Promise<void>;
817
- getWriteCheckpoint: () => Promise<string>;
818
- isConnected: boolean;
819
- syncStatus: SyncStatus;
820
- triggerCrudUpload: () => void;
821
- waitForReady(): Promise<void>;
822
- waitForStatus(status: SyncStatusOptions): Promise<void>;
823
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
824
- updateSubscriptions(subscriptions: SubscribedStream[]): void;
825
- markConnectionMayHaveChanged(): void;
826
- }
827
- /**
828
- * @internal
829
- */
830
- declare const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
831
- /**
832
- * @internal
833
- */
834
- declare const DEFAULT_RETRY_DELAY_MS = 5000;
835
- /**
836
- * @internal
837
- */
838
- declare const DEFAULT_STREAMING_SYNC_OPTIONS: {
839
- retryDelayMs: number;
840
- crudUploadThrottleMs: number;
841
- };
842
- /**
843
- * @internal
844
- */
845
- type RequiredPowerSyncConnectionOptions = Required<BaseConnectionOptions>;
846
- /**
847
- * @internal
848
- */
849
- declare const DEFAULT_STREAM_CONNECTION_OPTIONS: RequiredPowerSyncConnectionOptions;
850
- /**
851
- * @internal
852
- */
853
- type SubscribedStream = {
854
- name: string;
855
- params: Record<string, any> | null;
856
- };
857
- /**
858
- * @internal
859
- */
860
- declare abstract class AbstractStreamingSyncImplementation extends BaseObserver<StreamingSyncImplementationListener> implements StreamingSyncImplementation {
861
- protected options: AbstractStreamingSyncImplementationOptions;
862
- protected abortController: AbortController | null;
863
- protected crudUpdateListener?: () => void;
864
- protected streamingSyncPromise?: Promise<[void, void]>;
865
- protected logger: ILogger;
866
- private activeStreams;
867
- private connectionMayHaveChanged;
868
- private crudUploadNotifier;
869
- private notifyCompletedUploads?;
870
- private handleActiveStreamsChange?;
871
- syncStatus: SyncStatus;
872
- constructor(options: AbstractStreamingSyncImplementationOptions);
873
- triggerCrudUpload(): void;
874
- waitForReady(): Promise<void>;
875
- waitForStatus(status: SyncStatusOptions): Promise<void>;
876
- waitUntilStatusMatches(predicate: (status: SyncStatus) => boolean): Promise<void>;
877
- get lastSyncedAt(): Date | undefined;
878
- get isConnected(): boolean;
879
- dispose(): Promise<void>;
880
- abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
881
- getWriteCheckpoint(): Promise<string>;
882
- private crudUploadLoop;
883
- private _uploadAllCrud;
884
- connect(options?: PowerSyncConnectionOptions): Promise<void>;
885
- disconnect(): Promise<void>;
886
- private streamingSync;
887
- markConnectionMayHaveChanged(): void;
888
- /**
889
- * Older versions of the JS SDK used to encode subkeys as JSON in `OplogEntry.toJSON`.
890
- * Because subkeys are always strings, this leads to quotes being added around them in `ps_oplog`.
891
- * While this is not a problem as long as it's done consistently, it causes issues when a database
892
- * created by the JS SDK is used with other SDKs, or (more likely) when the new Rust sync client
893
- * is enabled.
894
- *
895
- * So, we add a migration from the old key format (with quotes) to the new one (no quotes). The
896
- * migration is only triggered when necessary (for now). The function returns whether the new format
897
- * should be used, so that the JS SDK is able to write to updated databases.
898
- *
899
- * @param requireFixedKeyFormat - Whether we require the new format or also support the old one.
900
- * The Rust client requires the new subkey format.
901
- * @returns Whether the database is now using the new, fixed subkey format.
902
- */
903
- private requireKeyFormat;
904
- protected streamingSyncIteration(signal: AbortSignal, options?: PowerSyncConnectionOptions): Promise<RustIterationResult | null>;
905
- private receiveSyncLines;
906
- private rustSyncIteration;
907
- protected updateSyncStatus(options: SyncStatusOptions): void;
908
- private delayRetry;
909
- updateSubscriptions(subscriptions: SubscribedStream[]): void;
910
- }
911
- interface RustIterationResult {
912
- immediateRestart: boolean;
913
- }
914
-
915
- interface CoreStreamSubscription {
916
- progress: {
917
- total: number;
918
- downloaded: number;
919
- };
920
- name: string;
921
- parameters: any;
922
- priority: number | null;
923
- active: boolean;
924
- is_default: boolean;
925
- has_explicit_subscription: boolean;
926
- expires_at: number | null;
927
- last_synced_at: number | null;
928
- }
929
- interface BucketProgress {
930
- priority: number;
931
- at_last: number;
932
- since_last: number;
933
- target_count: number;
934
- }
935
-
936
- /**
937
- * A description of a sync stream, consisting of its {@link SyncStreamDescription.name} and the
938
- * {@link SyncStreamDescription.parameters} used when subscribing.
939
- *
940
- * @public
941
- */
942
- interface SyncStreamDescription {
943
- /**
944
- * The name of the stream as it appears in the stream definition for the PowerSync service.
945
- */
946
- name: string;
947
- /**
948
- * The parameters used to subscribe to the stream, if any.
949
- *
950
- * The same stream can be subscribed to multiple times with different parameters.
951
- */
952
- parameters: Record<string, any> | null;
953
- }
954
- /**
955
- * Information about a subscribed sync stream.
956
- *
957
- * This includes the {@link SyncStreamDescription}, along with information about the current sync status.
958
- *
959
- * @public
960
- */
961
- interface SyncSubscriptionDescription extends SyncStreamDescription {
962
- active: boolean;
963
- /**
964
- * Whether this stream subscription is included by default, regardless of whether the stream has explicitly been
965
- * subscribed to or not.
966
- *
967
- * It's possible for both {@link SyncSubscriptionDescription.isDefault} and
968
- * {@link SyncSubscriptionDescription.hasExplicitSubscription} to be true at the same time - this happens when a
969
- * default stream was subscribed explicitly.
970
- */
971
- isDefault: boolean;
972
- /**
973
- * Whether this stream has been subscribed to explicitly.
974
- *
975
- * It's possible for both {@link SyncSubscriptionDescription.isDefault} and
976
- * {@link SyncSubscriptionDescription.hasExplicitSubscription} to be true at the same time - this happens when a
977
- * default stream was subscribed explicitly.
978
- */
979
- hasExplicitSubscription: boolean;
980
- /**
981
- * For sync streams that have a time-to-live, the current time at which the stream would expire if not subscribed to
982
- * again.
983
- */
984
- expiresAt: Date | null;
985
- /**
986
- * Whether this stream subscription has been synced at least once.
987
- */
988
- hasSynced: boolean;
989
- /**
990
- * If {@link SyncSubscriptionDescription.hasSynced} is true, the last time data from this stream has been synced.
991
- */
992
- lastSyncedAt: Date | null;
993
- }
994
- /**
995
- * @public
996
- */
997
- interface SyncStreamSubscribeOptions {
998
- /**
999
- * A "time to live" for this stream subscription, in seconds.
1000
- *
1001
- * The TTL control when a stream gets evicted after not having an active {@link SyncStreamSubscription} object
1002
- * attached to it.
1003
- */
1004
- ttl?: number;
1005
- /**
1006
- * A priority to assign to this subscription. This overrides the default priority that may have been set on streams.
1007
- *
1008
- * For details on priorities, see [priotized sync](https://docs.powersync.com/usage/use-case-examples/prioritized-sync).
1009
- */
1010
- priority?: 0 | 1 | 2 | 3;
1011
- }
1012
- /**
1013
- * A handle to a {@link SyncStreamDescription} that allows subscribing to the stream.
1014
- *
1015
- * To obtain an instance of {@link SyncStream}, call {@link AbstractPowerSyncDatabase.syncStream}.
1016
- *
1017
- * @public
1018
- */
1019
- interface SyncStream extends SyncStreamDescription {
1020
- /**
1021
- * Adds a subscription to this stream, requesting it to be included when connecting to the sync service.
1022
- *
1023
- * You should keep a reference to the returned {@link SyncStreamSubscription} object along as you need data for that
1024
- * stream. As soon as {@link SyncStreamSubscription.unsubscribe} is called for all subscriptions on this stream
1025
- * (including subscriptions created on other tabs), the {@link SyncStreamSubscribeOptions.ttl} starts ticking and will
1026
- * eventually evict the stream (unless {@link SyncStream.subscribe} is called again).
1027
- */
1028
- subscribe(options?: SyncStreamSubscribeOptions): Promise<SyncStreamSubscription>;
1029
- /**
1030
- * Clears all subscriptions attached to this stream and resets the TTL for the stream.
1031
- *
1032
- * This is a potentially dangerous operations, as it interferes with other stream subscriptions.
1033
- */
1034
- unsubscribeAll(): Promise<void>;
1035
- }
1036
- /**
1037
- * @public
1038
- */
1039
- interface SyncStreamSubscription extends SyncStreamDescription {
1040
- /**
1041
- * A promise that resolves once data from in this sync stream has been synced and applied.
1042
- */
1043
- waitForFirstSync(abort?: AbortSignal): Promise<void>;
1044
- /**
1045
- * Removes this stream subscription.
1046
- */
1047
- unsubscribe(): void;
1048
- }
1049
-
1050
- /** @internal */
1051
- type InternalProgressInformation = Record<string, BucketProgress>;
1052
- /**
1053
- * Information about a progressing download made by the PowerSync SDK.
1054
- *
1055
- * To obtain these values, use {@link SyncProgress}, available through
1056
- * {@link SyncStatus#downloadProgress}.
1057
- *
1058
- * @public
1059
- */
1060
- interface ProgressWithOperations {
1061
- /**
1062
- * The total amount of operations to download for the current sync iteration
1063
- * to complete.
1064
- */
1065
- totalOperations: number;
1066
- /**
1067
- * The amount of operations that have already been downloaded.
1068
- */
1069
- downloadedOperations: number;
1070
- /**
1071
- * Relative progress, as {@link ProgressWithOperations.downloadedOperations} of
1072
- * {@link ProgressWithOperations.totalOperations}.
1073
- *
1074
- * This will be a number between `0.0` and `1.0` (inclusive).
1075
- *
1076
- * When this number reaches `1.0`, all changes have been received from the sync service.
1077
- * Actually applying these changes happens before the `downloadProgress` field is cleared from
1078
- * {@link SyncStatus}, so progress can stay at `1.0` for a short while before completing.
1079
- */
1080
- downloadedFraction: number;
1081
- }
1082
- /**
1083
- * Provides realtime progress on how PowerSync is downloading rows.
1084
- *
1085
- * The progress until the next complete sync is available through the fields on {@link ProgressWithOperations},
1086
- * which this class implements.
1087
- * Additionally, the {@link SyncProgress.untilPriority} method can be used to otbain progress towards
1088
- * a specific priority (instead of the progress for the entire download).
1089
- *
1090
- * The reported progress always reflects the status towards the end of a sync iteration (after
1091
- * which a consistent snapshot of all buckets is available locally).
1092
- *
1093
- * In rare cases (in particular, when a [compacting](https://docs.powersync.com/usage/lifecycle-maintenance/compacting-buckets)
1094
- * operation takes place between syncs), it's possible for the returned numbers to be slightly
1095
- * inaccurate. For this reason, {@link SyncProgress} should be seen as an approximation of progress.
1096
- * The information returned is good enough to build progress bars, but not exact enough to track
1097
- * individual download counts.
1098
- *
1099
- * Also note that data is downloaded in bulk, which means that individual counters are unlikely
1100
- * to be updated one-by-one.
1101
- *
1102
- * @public
1103
- */
1104
- declare class SyncProgress implements ProgressWithOperations {
1105
- protected internal: InternalProgressInformation;
1106
- totalOperations: number;
1107
- downloadedOperations: number;
1108
- downloadedFraction: number;
1109
- constructor(internal: InternalProgressInformation);
1110
- /**
1111
- * Returns download progress towards all data up until the specified priority being received.
1112
- *
1113
- * The returned {@link ProgressWithOperations} tracks the target amount of operations that need
1114
- * to be downloaded in total and how many of them have already been received.
1115
- */
1116
- untilPriority(priority: number): ProgressWithOperations;
1117
- }
1118
-
1119
- /**
1120
- * @public
1121
- */
1122
- type SyncDataFlowStatus = Partial<{
1123
- downloading: boolean;
1124
- uploading: boolean;
1125
- /**
1126
- * Error during downloading (including connecting).
1127
- *
1128
- * Cleared on the next successful data download.
1129
- */
1130
- downloadError?: Error;
1131
- /**
1132
- * Error during uploading.
1133
- * Cleared on the next successful upload.
1134
- */
1135
- uploadError?: Error;
1136
- /**
1137
- * Internal information about how far we are downloading operations in buckets.
1138
- *
1139
- * @internal Please use the {@link SyncStatus#downloadProgress} property to track sync progress.
1140
- */
1141
- downloadProgress: InternalProgressInformation | null;
1142
- /**
1143
- * @internal
1144
- */
1145
- internalStreamSubscriptions: CoreStreamSubscription[] | null;
1146
- }>;
1147
- /**
1148
- * @public
1149
- */
1150
- interface SyncPriorityStatus {
1151
- priority: number;
1152
- lastSyncedAt?: Date;
1153
- hasSynced?: boolean;
1154
- }
1155
- /**
1156
- * @internal
1157
- */
1158
- type SyncStatusOptions = {
1159
- connected?: boolean;
1160
- connecting?: boolean;
1161
- dataFlow?: SyncDataFlowStatus;
1162
- lastSyncedAt?: Date;
1163
- hasSynced?: boolean;
1164
- priorityStatusEntries?: SyncPriorityStatus[];
1165
- /**
1166
- * @deprecated This field is no longer set, since {@link SyncClientImplementation.RUST} is the only option.
1167
- */
1168
- clientImplementation?: SyncClientImplementation;
1169
- };
1170
- /**
1171
- * @public
1172
- */
1173
- declare class SyncStatus {
1174
- protected options: SyncStatusOptions;
1175
- constructor(options: SyncStatusOptions);
1176
- /**
1177
- * Returns the used sync client implementation (either the one implemented in JavaScript or the newer Rust-based
1178
- * implementation).
1179
- *
1180
- * This information is only available after a connection has been requested.
1181
- *
1182
- * @deprecated This always returns the Rust client (the only option).
1183
- */
1184
- get clientImplementation(): SyncClientImplementation | undefined;
1185
- /**
1186
- * Indicates if the client is currently connected to the PowerSync service.
1187
- *
1188
- * @returns True if connected, false otherwise. Defaults to false if not specified.
1189
- */
1190
- get connected(): boolean;
1191
- /**
1192
- * Indicates if the client is in the process of establishing a connection to the PowerSync service.
1193
- *
1194
- * @returns True if connecting, false otherwise. Defaults to false if not specified.
1195
- */
1196
- get connecting(): boolean;
1197
- /**
1198
- * Time that a last sync has fully completed, if any.
1199
- * This timestamp is reset to null after a restart of the PowerSync service.
1200
- *
1201
- * @returns The timestamp of the last successful sync, or undefined if no sync has completed.
1202
- */
1203
- get lastSyncedAt(): Date | undefined;
1204
- /**
1205
- * Indicates whether there has been at least one full sync completed since initialization.
1206
- *
1207
- * @returns True if at least one sync has completed, false if no sync has completed,
1208
- * or undefined when the state is still being loaded from the database.
1209
- */
1210
- get hasSynced(): boolean | undefined;
1211
- /**
1212
- * Provides the current data flow status regarding uploads and downloads.
1213
- *
1214
- * @returns An object containing:
1215
- * - downloading: True if actively downloading changes (only when connected is also true)
1216
- * - uploading: True if actively uploading changes
1217
- * Defaults to `{downloading: false, uploading: false}` if not specified.
1218
- */
1219
- get dataFlowStatus(): SyncDataFlowStatus;
1220
- /**
1221
- * All sync streams currently being tracked in the database.
1222
- *
1223
- * This returns null when the database is currently being opened and we don't have reliable information about all
1224
- * included streams yet.
1225
- */
1226
- get syncStreams(): SyncStreamStatus[] | undefined;
1227
- /**
1228
- * If the `stream` appears in {@link SyncStatus.syncStreams}, returns the current status for that stream.
1229
- */
1230
- forStream(stream: SyncStreamDescription): SyncStreamStatus | undefined;
1231
- /**
1232
- * Provides sync status information for all bucket priorities, sorted by priority (highest first).
1233
- *
1234
- * @returns An array of status entries for different sync priority levels,
1235
- * sorted with highest priorities (lower numbers) first.
1236
- */
1237
- get priorityStatusEntries(): SyncPriorityStatus[];
1238
- /**
1239
- * A realtime progress report on how many operations have been downloaded and
1240
- * how many are necessary in total to complete the next sync iteration.
1241
- *
1242
- * This field is only set when {@link SyncDataFlowStatus#downloading} is also true.
1243
- */
1244
- get downloadProgress(): SyncProgress | null;
1245
- /**
1246
- * Reports the sync status (a pair of {@link SyncStatus#hasSynced} and {@link SyncStatus#lastSyncedAt} fields)
1247
- * for a specific bucket priority level.
1248
- *
1249
- * When buckets with different priorities are declared, PowerSync may choose to synchronize higher-priority
1250
- * buckets first. When a consistent view over all buckets for all priorities up until the given priority is
1251
- * reached, PowerSync makes data from those buckets available before lower-priority buckets have finished
1252
- * syncing.
1253
- *
1254
- * This method returns the status for the requested priority or the next higher priority level that has
1255
- * status information available. This is because when PowerSync makes data for a given priority available,
1256
- * all buckets in higher-priorities are guaranteed to be consistent with that checkpoint.
1257
- *
1258
- * For example, if PowerSync just finished synchronizing buckets in priority level 3, calling this method
1259
- * with a priority of 1 may return information for priority level 3.
1260
- *
1261
- * @param priority - The bucket priority for which the status should be reported
1262
- * @returns Status information for the requested priority level or the next higher level with available status
1263
- */
1264
- statusForPriority(priority: number): SyncPriorityStatus;
1265
- /**
1266
- * Compares this SyncStatus instance with another to determine if they are equal.
1267
- * Equality is determined by comparing the serialized JSON representation of both instances.
1268
- *
1269
- * @param status - The SyncStatus instance to compare against
1270
- * @returns True if the instances are considered equal, false otherwise
1271
- */
1272
- isEqual(status: SyncStatus): boolean;
1273
- /**
1274
- * Creates a human-readable string representation of the current sync status.
1275
- * Includes information about connection state, sync completion, and data flow.
1276
- *
1277
- * @returns A string representation of the sync status
1278
- */
1279
- getMessage(): string;
1280
- /**
1281
- * Serializes the SyncStatus instance to a plain object.
1282
- *
1283
- * @returns A plain object representation of the sync status
1284
- */
1285
- toJSON(): SyncStatusOptions;
1286
- /**
1287
- * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
1288
- * This explicitly serializes errors in the SyncStatus.
1289
- */
1290
- protected serializeError(error?: Error): Error | undefined;
1291
- private static comparePriorities;
1292
- }
1293
- /**
1294
- * Information about a sync stream subscription.
1295
- *
1296
- * @public
1297
- */
1298
- interface SyncStreamStatus {
1299
- progress: ProgressWithOperations | null;
1300
- subscription: SyncSubscriptionDescription;
1301
- priority: number | null;
1302
- }
1303
-
1304
- /**
1305
- * @public
1306
- */
1307
- declare class UploadQueueStats {
1308
- /**
1309
- * Number of records in the upload queue.
1310
- */
1311
- count: number;
1312
- /**
1313
- * Size of the upload queue in bytes.
1314
- */
1315
- size: number | null;
1316
- constructor(
1317
- /**
1318
- * Number of records in the upload queue.
1319
- */
1320
- count: number,
1321
- /**
1322
- * Size of the upload queue in bytes.
1323
- */
1324
- size?: number | null);
1325
- toString(): string;
1326
- }
1327
-
1328
- /**
1329
- * @see https://www.sqlite.org/lang_expr.html#castexpr
1330
- * @public
1331
- */
1332
- declare enum ColumnType {
1333
- TEXT = "TEXT",
1334
- INTEGER = "INTEGER",
1335
- REAL = "REAL"
1336
- }
1337
- /**
1338
- * @public
1339
- */
1340
- interface ColumnOptions {
1341
- name: string;
1342
- type?: ColumnType;
1343
- }
1344
- /**
1345
- * @public
1346
- */
1347
- type BaseColumnType<T extends number | string | null> = {
1348
- type: ColumnType;
1349
- };
1350
- /**
1351
- * @public
1352
- */
1353
- type ColumnsType = Record<string, BaseColumnType<any>>;
1354
- /**
1355
- * @public
1356
- */
1357
- type ExtractColumnValueType<T extends BaseColumnType<any>> = T extends BaseColumnType<infer R> ? R : unknown;
1358
- /**
1359
- * powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
1360
- * In earlier versions this was limited to 63.
1361
- *
1362
- * @internal
1363
- */
1364
- declare const MAX_AMOUNT_OF_COLUMNS = 1999;
1365
- /**
1366
- * @public
1367
- */
1368
- declare const column: {
1369
- text: BaseColumnType<string | null>;
1370
- integer: BaseColumnType<number | null>;
1371
- real: BaseColumnType<number | null>;
1372
- };
1373
- /**
1374
- * @public
1375
- */
1376
- declare class Column {
1377
- protected options: ColumnOptions;
1378
- constructor(options: ColumnOptions);
1379
- get name(): string;
1380
- get type(): ColumnType | undefined;
1381
- toJSON(): {
1382
- name: string;
1383
- type: ColumnType | undefined;
1384
- };
1385
- }
1386
-
1387
- /**
1388
- * @public
1389
- */
1390
- interface IndexColumnOptions {
1391
- name: string;
1392
- ascending?: boolean;
1393
- }
1394
- /**
1395
- * @internal
1396
- */
1397
- declare const DEFAULT_INDEX_COLUMN_OPTIONS: Partial<IndexColumnOptions>;
1398
- /**
1399
- * @public
1400
- */
1401
- declare class IndexedColumn {
1402
- protected options: IndexColumnOptions;
1403
- static createAscending(column: string): IndexedColumn;
1404
- constructor(options: IndexColumnOptions);
1405
- get name(): string;
1406
- get ascending(): boolean | undefined;
1407
- toJSON(table: Table): {
1408
- name: string;
1409
- ascending: boolean | undefined;
1410
- type: ColumnType;
1411
- };
1412
- }
1413
-
1414
- /**
1415
- * @public
1416
- */
1417
- interface IndexOptions {
1418
- name: string;
1419
- columns?: IndexedColumn[];
1420
- }
1421
- /**
1422
- * @internal
1423
- */
1424
- declare const DEFAULT_INDEX_OPTIONS: Partial<IndexOptions>;
1425
- /**
1426
- * @public
1427
- */
1428
- declare class Index {
1429
- protected options: IndexOptions;
1430
- static createAscending(options: IndexOptions, columnNames: string[]): Index;
1431
- constructor(options: IndexOptions);
1432
- get name(): string;
1433
- get columns(): IndexedColumn[];
1434
- toJSON(table: Table): {
1435
- name: string;
1436
- columns: {
1437
- name: string;
1438
- ascending: boolean | undefined;
1439
- type: ColumnType;
1440
- }[];
1441
- };
1442
- }
1443
-
1444
- /**
1445
- Generate a new table from the columns and indexes
1446
- @deprecated You should use {@link Table} instead as it now allows TableV2 syntax.
1447
- This will be removed in the next major release.
1448
-
1449
- @public
1450
- */
1451
- declare class TableV2<Columns extends ColumnsType = ColumnsType> extends Table<Columns> {
1452
- }
1453
-
1454
- /**
1455
- * Options that apply both to JSON-based tables and raw tables.
1456
- *
1457
- * @public
1458
- */
1459
- interface TableOrRawTableOptions {
1460
- localOnly?: boolean;
1461
- insertOnly?: boolean;
1462
- trackPrevious?: boolean | TrackPreviousOptions;
1463
- trackMetadata?: boolean;
1464
- ignoreEmptyUpdates?: boolean;
1465
- }
1466
- interface SharedTableOptions extends TableOrRawTableOptions {
1467
- viewName?: string;
1468
- }
1469
- /** Whether to include previous column values when PowerSync tracks local changes.
1470
- *
1471
- * Including old values may be helpful for some backend connector implementations, which is
1472
- * why it can be enabled on per-table or per-columm basis.
1473
- *
1474
- * @public
1475
- */
1476
- interface TrackPreviousOptions {
1477
- /** When defined, a list of column names for which old values should be tracked. */
1478
- columns?: string[];
1479
- /** When enabled, only include values that have actually been changed by an update. */
1480
- onlyWhenChanged?: boolean;
1481
- }
1482
- /**
1483
- * @public
1484
- */
1485
- interface TableOptions extends SharedTableOptions {
1486
- /**
1487
- * The synced table name, matching sync rules
1488
- */
1489
- name: string;
1490
- columns: Column[];
1491
- indexes?: Index[];
1492
- }
1493
- /**
1494
- * @public
1495
- */
1496
- type RowType<T extends TableV2<any>> = {
1497
- [K in keyof T['columnMap']]: ExtractColumnValueType<T['columnMap'][K]>;
1498
- } & {
1499
- id: string;
1500
- };
1501
- /**
1502
- * @public
1503
- */
1504
- type IndexShorthand = Record<string, string[]>;
1505
- /**
1506
- * @public
1507
- */
1508
- interface TableV2Options extends SharedTableOptions {
1509
- indexes?: IndexShorthand;
1510
- }
1511
- /**
1512
- * @internal
1513
- */
1514
- declare const DEFAULT_TABLE_OPTIONS: {
1515
- indexes: never[];
1516
- insertOnly: boolean;
1517
- localOnly: boolean;
1518
- trackPrevious: boolean;
1519
- trackMetadata: boolean;
1520
- ignoreEmptyUpdates: boolean;
1521
- };
1522
- /**
1523
- * @internal
1524
- */
1525
- declare const InvalidSQLCharacters: RegExp;
1526
- /**
1527
- * @public
1528
- */
1529
- declare class Table<Columns extends ColumnsType = ColumnsType> {
1530
- protected options: TableOptions;
1531
- protected _mappedColumns: Columns;
1532
- static createLocalOnly(options: TableOptions): Table<ColumnsType>;
1533
- static createInsertOnly(options: TableOptions): Table<ColumnsType>;
1534
- /**
1535
- * Create a table.
1536
- * @deprecated This was only only included for TableV2 and is no longer necessary.
1537
- * Prefer to use new Table() directly.
1538
- *
1539
- * TODO remove in the next major release.
1540
- */
1541
- static createTable(name: string, table: Table): Table<ColumnsType>;
1542
- /**
1543
- * Creates a new Table instance.
1544
- *
1545
- * This constructor supports two different versions:
1546
- * 1. New constructor: Using a Columns object and an optional TableV2Options object
1547
- * 2. Deprecated constructor: Using a TableOptions object (will be removed in the next major release)
1548
- *
1549
- * @param columns - Either a Columns object (for V2 syntax) or a TableOptions object (for V1 syntax)
1550
- * @param options - Optional configuration options for V2 syntax
1551
- *
1552
- * @example
1553
- * ```javascript
1554
- * // New Constructor
1555
- * const table = new Table(
1556
- * {
1557
- * name: column.text,
1558
- * age: column.integer
1559
- * },
1560
- * { indexes: { nameIndex: ['name'] } }
1561
- * );
1562
- *```
1563
- *
1564
- *
1565
- * @example
1566
- * ```javascript
1567
- * // Deprecated Constructor
1568
- * const table = new Table({
1569
- * name: 'users',
1570
- * columns: [
1571
- * new Column({ name: 'name', type: ColumnType.TEXT }),
1572
- * new Column({ name: 'age', type: ColumnType.INTEGER })
1573
- * ]
1574
- * });
1575
- *```
1576
- */
1577
- constructor(columns: Columns, options?: TableV2Options);
1578
- /**
1579
- * @deprecated This constructor will be removed in the next major release.
1580
- * Use the new constructor shown below instead as this does not show types.
1581
- * @example
1582
- * <caption>Use this instead</caption>
1583
- * ```javascript
1584
- * const table = new Table(
1585
- * {
1586
- * name: column.text,
1587
- * age: column.integer
1588
- * },
1589
- * { indexes: { nameIndex: ['name'] } }
1590
- * );
1591
- *```
1592
- */
1593
- constructor(options: TableOptions);
1594
- copyWithName(name: string): Table;
1595
- private isTableV1;
1596
- private initTableV1;
1597
- private initTableV2;
1598
- private applyDefaultOptions;
1599
- get name(): string;
1600
- get viewNameOverride(): string | undefined;
1601
- get viewName(): string;
1602
- get columns(): Column[];
1603
- get columnMap(): Columns;
1604
- get indexes(): Index[];
1605
- get localOnly(): boolean;
1606
- get insertOnly(): boolean;
1607
- get trackPrevious(): boolean | TrackPreviousOptions;
1608
- get trackMetadata(): boolean;
1609
- get ignoreEmptyUpdates(): boolean;
1610
- get internalName(): string;
1611
- get validName(): boolean;
1612
- validate(): void;
1613
- toJSON(): {
1614
- local_only: boolean | undefined;
1615
- insert_only: boolean | undefined;
1616
- include_old: any;
1617
- include_old_only_when_changed: boolean;
1618
- include_metadata: boolean | undefined;
1619
- ignore_empty_update: boolean | undefined;
1620
- name: string;
1621
- view_name: string;
1622
- columns: {
1623
- name: string;
1624
- type: ColumnType | undefined;
1625
- }[];
1626
- indexes: {
1627
- name: string;
1628
- columns: {
1629
- name: string;
1630
- ascending: boolean | undefined;
1631
- type: ColumnType;
1632
- }[];
1633
- }[];
1634
- };
1635
- }
1636
-
1637
- /**
1638
- * Instructs PowerSync to sync data into a "raw" table.
1639
- *
1640
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
1641
- * using client-side table and column constraints.
1642
- *
1643
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
1644
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables} for details and an example on
1645
- * using raw tables.
1646
- *
1647
- * @public
1648
- */
1649
- type RawTableType = RawTableTypeWithStatements | InferredRawTableType;
1650
- interface RawTableTypeWithStatements {
1651
- /**
1652
- * The statement to run when PowerSync detects that a row needs to be inserted or updated.
1653
- */
1654
- put: PendingStatement;
1655
- /**
1656
- * The statement to run when PowerSync detects that a row needs to be deleted.
1657
- */
1658
- delete: PendingStatement;
1659
- /**
1660
- * An optional statement to run when `disconnectAndClear()` is called on a PowerSync database.
1661
- */
1662
- clear?: string;
1663
- }
1664
- /**
1665
- * The schema of a {@link RawTableType} in the local database.
1666
- *
1667
- * This information is optional when declaring raw tables. However, providing it allows the sync client to infer `put`
1668
- * and `delete` statements automatically.
1669
- */
1670
- interface RawTableSchema extends TableOrRawTableOptions {
1671
- /**
1672
- * The actual name of the raw table in the local schema.
1673
- *
1674
- * Unlike {@link RawTable.name}, which describes the name of synced tables to match, this reflects the SQLite table
1675
- * name. This is used to infer {@link RawTableType.put} and {@link RawTableType.delete} statements for the sync
1676
- * client. It can also be used to auto-generate triggers forwarding writes on raw tables into the CRUD upload queue
1677
- * (using the `powersync_create_raw_table_crud_trigger` SQL function).
1678
- *
1679
- * When absent, defaults to {@link RawTable.name}.
1680
- */
1681
- tableName?: string;
1682
- /**
1683
- * An optional filter of columns that should be synced.
1684
- *
1685
- * By default, all columns in a raw table are considered for sync. If a filter is specified, PowerSync treats
1686
- * unmatched columns as local-only and will not attempt to sync them.
1687
- */
1688
- syncedColumns?: string[];
1689
- }
1690
- interface InferredRawTableType extends Partial<RawTableTypeWithStatements> {
1691
- schema: RawTableSchema;
1692
- }
1693
- /**
1694
- * A parameter to use as part of {@link PendingStatement}.
1695
- *
1696
- * For delete statements, only the `"Id"` value is supported - the sync client will replace it with the id of the row to
1697
- * be synced.
1698
- *
1699
- * For insert and replace operations, the values of columns in the table are available as parameters through
1700
- * `{Column: 'name'}`.
1701
- * The `"Rest"` parameter gets resolved to a JSON object covering all values from the synced row that haven't been
1702
- * covered by a `Column` parameter.
1703
- *
1704
- * @public
1705
- */
1706
- type PendingStatementParameter = 'Id' | {
1707
- Column: string;
1708
- } | 'Rest';
1709
- /**
1710
- * A statement that the PowerSync client should use to insert or delete data into a table managed by the user.
1711
- *
1712
- * @public
1713
- */
1714
- type PendingStatement = {
1715
- sql: string;
1716
- params: PendingStatementParameter[];
1717
- };
1718
- /**
1719
- * @internal
1720
- */
1721
- type RawTable<T extends RawTableType = RawTableType> = T & {
1722
- /**
1723
- * The name of the table.
1724
- *
1725
- * This does not have to match the actual table name in the schema - {@link RawTableType.put} and
1726
- * {@link RawTableType.delete} are free to use another table. Instead, this name is used by the sync client to
1727
- * recognize that operations on this table (as it appears in the source / backend database) are to be handled
1728
- * specially.
1729
- */
1730
- name: string;
1731
- };
1732
-
1733
- type SchemaType = Record<string, Table<any>>;
1734
- /**
1735
- * @public
1736
- */
1737
- type SchemaTableType<S extends SchemaType> = {
1738
- [K in keyof S]: RowType<S[K]>;
1739
- };
1740
- /**
1741
- * A schema is a collection of tables. It is used to define the structure of a database.
1742
- *
1743
- * @public
1744
- */
1745
- declare class Schema<S extends SchemaType = SchemaType> {
1746
- readonly types: SchemaTableType<S>;
1747
- readonly props: S;
1748
- readonly tables: Table[];
1749
- readonly rawTables: RawTable[];
1750
- constructor(tables: Table[] | S);
1751
- /**
1752
- * Adds raw tables to this schema. Raw tables are identified by their name, but entirely managed by the application
1753
- * developer instead of automatically by PowerSync.
1754
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
1755
- * using client-side table and column constraints.
1756
- *
1757
- * @param tables - An object of (table name, raw table definition) entries.
1758
- */
1759
- withRawTables(tables: Record<string, RawTableType>): void;
1760
- validate(): void;
1761
- toJSON(): {
1762
- tables: {
1763
- local_only: boolean | undefined;
1764
- insert_only: boolean | undefined;
1765
- include_old: any;
1766
- include_old_only_when_changed: boolean;
1767
- include_metadata: boolean | undefined;
1768
- ignore_empty_update: boolean | undefined;
1769
- name: string;
1770
- view_name: string;
1771
- columns: {
1772
- name: string;
1773
- type: ColumnType | undefined;
1774
- }[];
1775
- indexes: {
1776
- name: string;
1777
- columns: {
1778
- name: string;
1779
- ascending: boolean | undefined;
1780
- type: ColumnType;
1781
- }[];
1782
- }[];
1783
- }[];
1784
- raw_tables: unknown[];
1785
- };
1786
- /**
1787
- * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
1788
- *
1789
- * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
1790
- * to define triggers for this table.
1791
- */
1792
- static rawTableToJson(table: RawTable): unknown;
1793
- }
1794
-
1795
- /**
1796
- * @public
1797
- */
1798
- interface PowerSyncBackendConnector {
1799
- /** Allows the PowerSync client to retrieve an authentication token from your backend
1800
- * which is used to authenticate against the PowerSync service.
1801
- *
1802
- * This should always fetch a fresh set of credentials - don't use cached
1803
- * values.
1804
- *
1805
- * Return null if the user is not signed in. Throw an error if credentials
1806
- * cannot be fetched due to a network error or other temporary error.
1807
- *
1808
- * This token is kept for the duration of a sync connection.
1809
- */
1810
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
1811
- /** Upload local changes to the app backend.
1812
- *
1813
- * Use {@link AbstractPowerSyncDatabase.getCrudBatch} to get a batch of changes to upload.
1814
- *
1815
- * Any thrown errors will result in a retry after the configured wait period (default: 5 seconds).
1816
- */
1817
- uploadData: (database: AbstractPowerSyncDatabase) => Promise<void>;
1818
- }
1819
-
1820
- /**
1821
- * @internal
1822
- */
1823
- interface ConnectionManagerSyncImplementationResult {
1824
- sync: StreamingSyncImplementation;
1825
- /**
1826
- * Additional cleanup function which is called after the sync stream implementation
1827
- * is disposed.
1828
- */
1829
- onDispose: () => Promise<void> | void;
1830
- }
1831
- /**
1832
- * The subset of {@link AbstractStreamingSyncImplementationOptions} managed by the connection manager.
1833
- *
1834
- * @internal
1835
- */
1836
- interface CreateSyncImplementationOptions extends AdditionalConnectionOptions {
1837
- subscriptions: SubscribedStream[];
1838
- }
1839
- /**
1840
- * @internal
1841
- */
1842
- interface InternalSubscriptionAdapter {
1843
- firstStatusMatching(predicate: (status: SyncStatus) => any, abort?: AbortSignal): Promise<void>;
1844
- resolveOfflineSyncStatus(): Promise<void>;
1845
- rustSubscriptionsCommand(payload: any): Promise<void>;
1846
- }
1847
- /**
1848
- * @internal
1849
- */
1850
- interface ConnectionManagerOptions {
1851
- createSyncImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions): Promise<ConnectionManagerSyncImplementationResult>;
1852
- logger: ILogger;
1853
- }
1854
- type StoredConnectionOptions = {
1855
- connector: PowerSyncBackendConnector;
1856
- options: InternalConnectionOptions;
1857
- };
1858
- /**
1859
- * @internal
1860
- */
1861
- interface ConnectionManagerListener extends BaseListener {
1862
- syncStreamCreated: (sync: StreamingSyncImplementation) => void;
1863
- }
1864
- /**
1865
- * @internal
1866
- */
1867
- declare class ConnectionManager extends BaseObserver<ConnectionManagerListener> {
1868
- protected options: ConnectionManagerOptions;
1869
- /**
1870
- * Tracks active connection attempts
1871
- */
1872
- protected connectingPromise: Promise<void> | null;
1873
- /**
1874
- * Tracks actively instantiating a streaming sync implementation.
1875
- */
1876
- protected syncStreamInitPromise: Promise<void> | null;
1877
- /**
1878
- * Active disconnect operation. Calling disconnect multiple times
1879
- * will resolve to the same operation.
1880
- */
1881
- protected disconnectingPromise: Promise<void> | null;
1882
- /**
1883
- * Tracks the last parameters supplied to `connect` calls.
1884
- * Calling `connect` multiple times in succession will result in:
1885
- * - 1 pending connection operation which will be aborted.
1886
- * - updating the last set of parameters while waiting for the pending
1887
- * attempt to be aborted
1888
- * - internally connecting with the last set of parameters
1889
- */
1890
- protected pendingConnectionOptions: StoredConnectionOptions | null;
1891
- syncStreamImplementation: StreamingSyncImplementation | null;
1892
- /**
1893
- * Additional cleanup function which is called after the sync stream implementation
1894
- * is disposed.
1895
- */
1896
- protected syncDisposer: (() => Promise<void> | void) | null;
1897
- /**
1898
- * Subscriptions managed in this connection manager.
1899
- *
1900
- * On the web, these local subscriptions are merged across tabs by a shared worker.
1901
- */
1902
- private locallyActiveSubscriptions;
1903
- constructor(options: ConnectionManagerOptions);
1904
- get connector(): PowerSyncBackendConnector | null;
1905
- get connectionOptions(): InternalConnectionOptions | null;
1906
- get logger(): ILogger;
1907
- close(): Promise<void>;
1908
- connect(connector: PowerSyncBackendConnector, options: InternalConnectionOptions): Promise<void>;
1909
- protected connectInternal(): Promise<void>;
1910
- /**
1911
- * Close the sync connection.
1912
- *
1913
- * Use {@link ConnectionManager.connect} to connect again.
1914
- */
1915
- disconnect(): Promise<void>;
1916
- protected disconnectInternal(): Promise<void>;
1917
- protected performDisconnect(): Promise<void>;
1918
- stream(adapter: InternalSubscriptionAdapter, name: string, parameters: Record<string, any> | null): SyncStream;
1919
- /**
1920
- * @internal exposed for testing
1921
- */
1922
- get activeStreams(): {
1923
- name: string;
1924
- params: Record<string, any> | null;
1925
- }[];
1926
- private subscriptionsMayHaveChanged;
1927
- }
1928
-
1929
- /**
1930
- * A basic comparator for incrementally watched queries. This performs a single comparison which
1931
- * determines if the result set has changed. The {@link WatchedQuery} will only emit the new result
1932
- * if a change has been detected.
1933
- *
1934
- * @public
1935
- */
1936
- interface WatchedQueryComparator<Data> {
1937
- checkEquality: (current: Data, previous: Data) => boolean;
1938
- }
1939
- /**
1940
- * Options for {@link ArrayComparator}
1941
- *
1942
- * @public
1943
- */
1944
- type ArrayComparatorOptions<ItemType> = {
1945
- /**
1946
- * Returns a string to uniquely identify an item in the array.
1947
- */
1948
- compareBy: (item: ItemType) => string;
1949
- };
1950
- /**
1951
- * An efficient comparator for {@link WatchedQuery} created with {@link Query#watch}. This has the ability to determine if a query
1952
- * result has changes without necessarily processing all items in the result.
1953
- *
1954
- * @public
1955
- */
1956
- declare class ArrayComparator<ItemType> implements WatchedQueryComparator<ItemType[]> {
1957
- protected options: ArrayComparatorOptions<ItemType>;
1958
- constructor(options: ArrayComparatorOptions<ItemType>);
1959
- checkEquality(current: ItemType[], previous: ItemType[]): boolean;
1960
- }
1961
- /**
1962
- * Watched query comparator that always reports changed result sets.
1963
- *
1964
- * @public
1965
- */
1966
- declare const FalsyComparator: WatchedQueryComparator<unknown>;
1967
-
1968
- /**
1969
- * @public
1970
- */
1971
- interface CompilableQuery<T> {
1972
- execute(): Promise<T[]>;
1973
- compile(): CompiledQuery;
1974
- }
1975
- /**
1976
- * @public
1977
- */
1978
- interface CompiledQuery {
1979
- readonly sql: string;
1980
- readonly parameters: ReadonlyArray<unknown>;
1981
- }
1982
-
1983
- /**
1984
- * Represents the counts of listeners for each event type in a BaseListener.
1985
- */
1986
- type ListenerCounts<Listener extends BaseListener> = Partial<Record<keyof Listener, number>> & {
1987
- total: number;
1988
- };
1989
- /**
1990
- * Meta listener which reports the counts of listeners for each event type.
1991
- */
1992
- interface MetaListener<ParentListener extends BaseListener> extends BaseListener {
1993
- listenersChanged?: (counts: ListenerCounts<ParentListener>) => void;
1994
- }
1995
- interface ListenerMetaManager<Listener extends BaseListener> extends BaseObserverInterface<MetaListener<Listener>> {
1996
- counts: ListenerCounts<Listener>;
1997
- }
1998
- interface MetaBaseObserverInterface<Listener extends BaseListener> extends BaseObserverInterface<Listener> {
1999
- listenerMeta: ListenerMetaManager<Listener>;
2000
- }
2001
- /**
2002
- * A BaseObserver that tracks the counts of listeners for each event type.
2003
- */
2004
- declare class MetaBaseObserver<Listener extends BaseListener> extends BaseObserver<Listener> implements MetaBaseObserverInterface<Listener> {
2005
- protected get listenerCounts(): ListenerCounts<Listener>;
2006
- get listenerMeta(): ListenerMetaManager<Listener>;
2007
- protected metaListener: BaseObserver<MetaListener<Listener>>;
2008
- constructor();
2009
- registerListener(listener: Partial<Listener>): () => void;
2010
- }
2011
-
2012
- /**
2013
- * State for {@link WatchedQuery} instances.
2014
- *
2015
- * @public
2016
- */
2017
- interface WatchedQueryState<Data> {
2018
- /**
2019
- * Indicates the initial loading state (hard loading).
2020
- * Loading becomes false once the first set of results from the watched query is available or an error occurs.
2021
- */
2022
- readonly isLoading: boolean;
2023
- /**
2024
- * Indicates whether the query is currently fetching data, is true during the initial load
2025
- * and any time when the query is re-evaluating (useful for large queries).
2026
- */
2027
- readonly isFetching: boolean;
2028
- /**
2029
- * The last error that occurred while executing the query.
2030
- */
2031
- readonly error: Error | null;
2032
- /**
2033
- * The last time the query was updated.
2034
- */
2035
- readonly lastUpdated: Date | null;
2036
- /**
2037
- * The last data returned by the query.
2038
- */
2039
- readonly data: Data;
2040
- }
2041
- /**
2042
- * Options provided to the `execute` method of a {@link WatchCompatibleQuery}.
2043
- *
2044
- * @public
2045
- */
2046
- interface WatchExecuteOptions {
2047
- sql: string;
2048
- parameters: any[];
2049
- db: AbstractPowerSyncDatabase;
2050
- }
2051
- /**
2052
- *
2053
- * @public
2054
- */
2055
- interface WatchCompatibleQuery<ResultType> {
2056
- execute(options: WatchExecuteOptions): Promise<ResultType>;
2057
- compile(): CompiledQuery;
2058
- }
2059
- /**
2060
- * @public
2061
- */
2062
- interface WatchedQueryOptions {
2063
- /** The minimum interval between queries. */
2064
- throttleMs?: number;
2065
- /**
2066
- * If true (default) the watched query will update its state to report
2067
- * on the fetching state of the query.
2068
- * Setting to false reduces the number of state changes if the fetch status
2069
- * is not relevant to the consumer.
2070
- */
2071
- reportFetching?: boolean;
2072
- /**
2073
- * By default, watched queries requery the database on any change to any dependent table of the query.
2074
- * Supplying an override here can be used to limit the tables which trigger querying the database.
2075
- */
2076
- triggerOnTables?: string[];
2077
- }
2078
- /**
2079
- * @public
2080
- */
2081
- declare enum WatchedQueryListenerEvent {
2082
- ON_DATA = "onData",
2083
- ON_ERROR = "onError",
2084
- ON_STATE_CHANGE = "onStateChange",
2085
- SETTINGS_WILL_UPDATE = "settingsWillUpdate",
2086
- CLOSED = "closed"
2087
- }
2088
- /**
2089
- * @public
2090
- */
2091
- interface WatchedQueryListener<Data> extends BaseListener {
2092
- [WatchedQueryListenerEvent.ON_DATA]?: (data: Data) => void | Promise<void>;
2093
- [WatchedQueryListenerEvent.ON_ERROR]?: (error: Error) => void | Promise<void>;
2094
- [WatchedQueryListenerEvent.ON_STATE_CHANGE]?: (state: WatchedQueryState<Data>) => void | Promise<void>;
2095
- [WatchedQueryListenerEvent.SETTINGS_WILL_UPDATE]?: () => void;
2096
- [WatchedQueryListenerEvent.CLOSED]?: () => void | Promise<void>;
2097
- }
2098
- /**
2099
- * @internal
2100
- */
2101
- declare const DEFAULT_WATCH_THROTTLE_MS = 30;
2102
- /**
2103
- * @internal
2104
- */
2105
- declare const DEFAULT_WATCH_QUERY_OPTIONS: WatchedQueryOptions;
2106
- /**
2107
- * @public
2108
- */
2109
- interface WatchedQuery<Data = unknown, Settings extends WatchedQueryOptions = WatchedQueryOptions, Listener extends WatchedQueryListener<Data> = WatchedQueryListener<Data>> extends MetaBaseObserverInterface<Listener> {
2110
- /**
2111
- * Current state of the watched query.
2112
- */
2113
- readonly state: WatchedQueryState<Data>;
2114
- readonly closed: boolean;
2115
- /**
2116
- * Subscribe to watched query events.
2117
- * @returns A function to unsubscribe from the events.
2118
- */
2119
- registerListener(listener: Listener): () => void;
2120
- /**
2121
- * Updates the underlying query options.
2122
- * This will trigger a re-evaluation of the query and update the state.
2123
- */
2124
- updateSettings(options: Settings): Promise<void>;
2125
- /**
2126
- * Close the watched query and end all subscriptions.
2127
- */
2128
- close(): Promise<void>;
2129
- }
2130
-
2131
- /**
2132
- * @internal
2133
- */
2134
- interface AbstractQueryProcessorOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
2135
- db: AbstractPowerSyncDatabase;
2136
- watchOptions: Settings;
2137
- placeholderData: Data;
2138
- }
2139
- /**
2140
- * @internal
2141
- */
2142
- interface LinkQueryOptions<Data, Settings extends WatchedQueryOptions = WatchedQueryOptions> {
2143
- abortSignal: AbortSignal;
2144
- settings: Settings;
2145
- }
2146
- type MutableDeep<T> = T extends ReadonlyArray<infer U> ? U[] : T;
2147
- /**
2148
- * @internal Mutable version of {@link WatchedQueryState}.
2149
- * This is used internally to allow updates to the state.
2150
- */
2151
- type MutableWatchedQueryState<Data> = {
2152
- -readonly [P in keyof WatchedQueryState<Data>]: MutableDeep<WatchedQueryState<Data>[P]>;
2153
- };
2154
- type WatchedQueryProcessorListener<Data> = WatchedQueryListener<Data>;
2155
- /**
2156
- * Performs underlying watching and yields a stream of results.
2157
- * @internal
2158
- */
2159
- declare abstract class AbstractQueryProcessor<Data = unknown[], Settings extends WatchedQueryOptions = WatchedQueryOptions> extends MetaBaseObserver<WatchedQueryProcessorListener<Data>> implements WatchedQuery<Data, Settings> {
2160
- protected options: AbstractQueryProcessorOptions<Data, Settings>;
2161
- readonly state: WatchedQueryState<Data>;
2162
- protected abortController: AbortController;
2163
- protected initialized: Promise<void>;
2164
- protected _closed: boolean;
2165
- protected disposeListeners: (() => void) | null;
2166
- get closed(): boolean;
2167
- constructor(options: AbstractQueryProcessorOptions<Data, Settings>);
2168
- protected constructInitialState(): WatchedQueryState<Data>;
2169
- protected get reportFetching(): boolean;
2170
- protected updateSettingsInternal(settings: Settings, signal: AbortSignal): Promise<void>;
2171
- /**
2172
- * Updates the underlying query.
2173
- */
2174
- updateSettings(settings: Settings): Promise<void>;
2175
- /**
2176
- * This method is used to link a query to the subscribers of this listener class.
2177
- * This method should perform actual query watching and report results via {@link AbstractQueryProcessor.updateState} method.
2178
- */
2179
- protected abstract linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
2180
- protected updateState(update: Partial<MutableWatchedQueryState<Data>>): Promise<void>;
2181
- /**
2182
- * Configures base DB listeners and links the query to listeners.
2183
- */
2184
- protected init(signal: AbortSignal): Promise<void>;
2185
- close(): Promise<void>;
2186
- /**
2187
- * Runs a callback and reports errors to the error listeners.
2188
- */
2189
- protected runWithReporting<T>(callback: () => Promise<T>): Promise<void>;
2190
- /**
2191
- * Iterate listeners and reports errors to onError handlers.
2192
- */
2193
- protected iterateAsyncListenersWithError(callback: (listener: Partial<WatchedQueryProcessorListener<Data>>) => Promise<void> | void): Promise<void>;
2194
- }
2195
-
2196
- /**
2197
- * Represents an updated row in a differential watched query.
2198
- * It contains both the current and previous state of the row.
2199
- *
2200
- * @public
2201
- */
2202
- interface WatchedQueryRowDifferential<RowType> {
2203
- readonly current: RowType;
2204
- readonly previous: RowType;
2205
- }
2206
- /**
2207
- * Represents the result of a watched query that has been diffed.
2208
- * {@link DifferentialWatchedQueryState#diff} is of the {@link WatchedQueryDifferential} form.
2209
- *
2210
- * @public
2211
- */
2212
- interface WatchedQueryDifferential<RowType> {
2213
- readonly added: ReadonlyArray<Readonly<RowType>>;
2214
- /**
2215
- * The entire current result set.
2216
- * Array item object references are preserved between updates if the item is unchanged.
2217
- *
2218
- * e.g. In the query
2219
- * ```sql
2220
- * SELECT name, make FROM assets ORDER BY make ASC;
2221
- * ```
2222
- *
2223
- * If a previous result set contains an item (A) `{name: 'pc', make: 'Cool PC'}` and
2224
- * an update has been made which adds another item (B) to the result set (the item A is unchanged) - then
2225
- * the updated result set will be contain the same object reference, to item A, as the previous result set.
2226
- * This is regardless of the item A's position in the updated result set.
2227
- */
2228
- readonly all: ReadonlyArray<Readonly<RowType>>;
2229
- readonly removed: ReadonlyArray<Readonly<RowType>>;
2230
- readonly updated: ReadonlyArray<WatchedQueryRowDifferential<Readonly<RowType>>>;
2231
- readonly unchanged: ReadonlyArray<Readonly<RowType>>;
2232
- }
2233
- /**
2234
- * Row comparator for differentially watched queries which keys and compares items in the result set.
2235
- *
2236
- * @public
2237
- */
2238
- interface DifferentialWatchedQueryComparator<RowType> {
2239
- /**
2240
- * Generates a unique key for the item.
2241
- */
2242
- keyBy: (item: RowType) => string;
2243
- /**
2244
- * Generates a token for comparing items with matching keys.
2245
- */
2246
- compareBy: (item: RowType) => string;
2247
- }
2248
- /**
2249
- * Options for building a differential watched query with the {@link Query} builder.
2250
- *
2251
- * @public
2252
- */
2253
- interface DifferentialWatchedQueryOptions<RowType> extends WatchedQueryOptions {
2254
- /**
2255
- * Initial result data which is presented while the initial loading is executing.
2256
- */
2257
- placeholderData?: RowType[];
2258
- /**
2259
- * Row comparator used to identify and compare rows in the result set.
2260
- * If not provided, the default comparator will be used which keys items by their `id` property if available,
2261
- * otherwise it uses JSON stringification of the entire item for keying and comparison.
2262
- * @defaultValue {@link DEFAULT_ROW_COMPARATOR}
2263
- */
2264
- rowComparator?: DifferentialWatchedQueryComparator<RowType>;
2265
- }
2266
- /**
2267
- * Settings for differential incremental watched queries using.
2268
- *
2269
- * @public
2270
- */
2271
- interface DifferentialWatchedQuerySettings<RowType> extends DifferentialWatchedQueryOptions<RowType> {
2272
- /**
2273
- * The query here must return an array of items that can be differentiated.
2274
- */
2275
- query: WatchCompatibleQuery<RowType[]>;
2276
- }
2277
- /**
2278
- * @public
2279
- */
2280
- interface DifferentialWatchedQueryListener<RowType> extends WatchedQueryListener<ReadonlyArray<Readonly<RowType>>> {
2281
- onDiff?: (diff: WatchedQueryDifferential<RowType>) => void | Promise<void>;
2282
- }
2283
- /**
2284
- * @public
2285
- */
2286
- type DifferentialWatchedQuery<RowType> = WatchedQuery<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>, DifferentialWatchedQueryListener<RowType>>;
2287
- /**
2288
- * @internal
2289
- */
2290
- interface DifferentialQueryProcessorOptions<RowType> extends AbstractQueryProcessorOptions<RowType[], DifferentialWatchedQuerySettings<RowType>> {
2291
- rowComparator?: DifferentialWatchedQueryComparator<RowType>;
2292
- }
2293
- type DataHashMap<RowType> = Map<string, {
2294
- hash: string;
2295
- item: RowType;
2296
- }>;
2297
- /**
2298
- * An empty differential result set.
2299
- * This is used as the initial state for differential incrementally watched queries.
2300
- *
2301
- * @internal
2302
- */
2303
- declare const EMPTY_DIFFERENTIAL: {
2304
- added: never[];
2305
- all: never[];
2306
- removed: never[];
2307
- updated: never[];
2308
- unchanged: never[];
2309
- };
2310
- /**
2311
- * Default implementation of the {@link DifferentialWatchedQueryComparator} for watched queries.
2312
- * It keys items by their `id` property if available, alternatively it uses JSON stringification
2313
- * of the entire item for the key and comparison.
2314
- *
2315
- * @internal
2316
- */
2317
- declare const DEFAULT_ROW_COMPARATOR: DifferentialWatchedQueryComparator<any>;
2318
- /**
2319
- * Uses the PowerSync onChange event to trigger watched queries.
2320
- * Results are emitted on every change of the relevant tables.
2321
- * @internal
2322
- */
2323
- declare class DifferentialQueryProcessor<RowType> extends AbstractQueryProcessor<ReadonlyArray<Readonly<RowType>>, DifferentialWatchedQuerySettings<RowType>> implements DifferentialWatchedQuery<RowType> {
2324
- protected options: DifferentialQueryProcessorOptions<RowType>;
2325
- protected comparator: DifferentialWatchedQueryComparator<RowType>;
2326
- constructor(options: DifferentialQueryProcessorOptions<RowType>);
2327
- protected differentiate(current: RowType[], previousMap: DataHashMap<RowType>): {
2328
- diff: WatchedQueryDifferential<RowType>;
2329
- map: DataHashMap<RowType>;
2330
- hasChanged: boolean;
2331
- };
2332
- protected linkQuery(options: LinkQueryOptions<WatchedQueryDifferential<RowType>>): Promise<void>;
2333
- }
2334
-
2335
- /**
2336
- * Settings for {@link WatchedQuery} instances created via {@link Query#watch}.
2337
- *
2338
- * @public
2339
- */
2340
- interface WatchedQuerySettings<DataType> extends WatchedQueryOptions {
2341
- query: WatchCompatibleQuery<DataType>;
2342
- }
2343
- /**
2344
- * {@link WatchedQuery} returned from {@link Query#watch}.
2345
- *
2346
- * @public
2347
- */
2348
- type StandardWatchedQuery<DataType> = WatchedQuery<DataType, WatchedQuerySettings<DataType>>;
2349
- /**
2350
- * @internal
2351
- */
2352
- interface OnChangeQueryProcessorOptions<Data> extends AbstractQueryProcessorOptions<Data, WatchedQuerySettings<Data>> {
2353
- comparator?: WatchedQueryComparator<Data>;
2354
- }
2355
- /**
2356
- * Uses the PowerSync onChange event to trigger watched queries.
2357
- * Results are emitted on every change of the relevant tables.
2358
- * @internal
2359
- */
2360
- declare class OnChangeQueryProcessor<Data> extends AbstractQueryProcessor<Data, WatchedQuerySettings<Data>> {
2361
- protected options: OnChangeQueryProcessorOptions<Data>;
2362
- constructor(options: OnChangeQueryProcessorOptions<Data>);
2363
- /**
2364
- * @returns If the sets are equal
2365
- */
2366
- protected checkEquality(current: Data, previous: Data): boolean;
2367
- protected linkQuery(options: LinkQueryOptions<Data>): Promise<void>;
2368
- }
2369
-
2370
- /**
2371
- * Query parameters for {@link ArrayQueryDefinition#parameters}
2372
- *
2373
- * @public
2374
- */
2375
- type QueryParam = string | number | boolean | null | undefined | bigint | Uint8Array;
2376
- /**
2377
- * Options for building a query with {@link AbstractPowerSyncDatabase#query}.
2378
- * This query will be executed with {@link AbstractPowerSyncDatabase#getAll}.
2379
- *
2380
- * @public
2381
- */
2382
- interface ArrayQueryDefinition<RowType = unknown> {
2383
- sql: string;
2384
- parameters?: ReadonlyArray<Readonly<QueryParam>>;
2385
- /**
2386
- * Maps the raw SQLite row to a custom typed object.
2387
- * @example
2388
- * ```javascript
2389
- * mapper: (row) => ({
2390
- * ...row,
2391
- * created_at: new Date(row.created_at as string),
2392
- * })
2393
- * ```
2394
- */
2395
- mapper?: (row: Record<string, unknown>) => RowType;
2396
- }
2397
- /**
2398
- * Options for {@link Query#watch}.
2399
- *
2400
- * @public
2401
- */
2402
- interface StandardWatchedQueryOptions<RowType> extends WatchedQueryOptions {
2403
- /**
2404
- * The underlying watched query implementation (re)evaluates the query on any SQLite table change.
2405
- *
2406
- * Providing this optional comparator can be used to filter duplicate result set emissions when the result set is unchanged.
2407
- * The comparator compares the previous and current result set.
2408
- *
2409
- * For an efficient comparator see {@link ArrayComparator}.
2410
- *
2411
- * @example
2412
- * ```javascript
2413
- * comparator: new ArrayComparator({
2414
- * compareBy: (item) => JSON.stringify(item)
2415
- * })
2416
- * ```
2417
- */
2418
- comparator?: WatchedQueryComparator<RowType[]>;
2419
- /**
2420
- * The initial data state reported while the query is loading for the first time.
2421
- * @default []
2422
- */
2423
- placeholderData?: RowType[];
2424
- }
2425
- /**
2426
- * @public
2427
- */
2428
- interface Query<RowType> {
2429
- /**
2430
- * Creates a {@link WatchedQuery} which watches and emits results of the linked query.
2431
- *
2432
- * By default the returned watched query will emit changes whenever a change to the underlying SQLite tables is made.
2433
- * These changes might not be relevant to the query, but the query will emit a new result set.
2434
- *
2435
- * A {@link StandardWatchedQueryOptions#comparator} can be provided to limit the data emissions. The watched query will still
2436
- * query the underlying DB on underlying table changes, but the result will only be emitted if the comparator detects a change in the results.
2437
- *
2438
- * The comparator in this method is optimized and returns early as soon as it detects a change. Each data emission will correlate to a change in the result set,
2439
- * but note that the result set will not maintain internal object references to the previous result set. If internal object references are needed,
2440
- * consider using {@link Query#differentialWatch} instead.
2441
- */
2442
- watch(options?: StandardWatchedQueryOptions<RowType>): StandardWatchedQuery<ReadonlyArray<Readonly<RowType>>>;
2443
- /**
2444
- * Creates a {@link WatchedQuery} which watches and emits results of the linked query.
2445
- *
2446
- * This query method watches for changes in the underlying SQLite tables and runs the query on each table change.
2447
- * The difference between the current and previous result set is computed.
2448
- * The watched query will not emit changes if the result set is identical to the previous result set.
2449
- *
2450
- * If the result set is different, the watched query will emit the new result set and emit a detailed diff of the changes via the `onData` and `onDiff` listeners.
2451
- *
2452
- * The deep differentiation allows maintaining result set object references between result emissions.
2453
- * The {@link DifferentialWatchedQuery#state} `data` array will contain the previous row references for unchanged rows.
2454
- *
2455
- * @example
2456
- * ```javascript
2457
- * const watchedLists = powerSync.query({sql: 'SELECT * FROM lists'})
2458
- * .differentialWatch();
2459
- *
2460
- * const disposeListener = watchedLists.registerListener({
2461
- * onData: (lists) => {
2462
- * console.log('The latest result set for the query is', lists);
2463
- * },
2464
- * onDiff: (diff) => {
2465
- * console.log('The lists result set has changed since the last emission', diff.added, diff.removed, diff.updated, diff.all)
2466
- * }
2467
- * })
2468
- * ```
2469
- */
2470
- differentialWatch(options?: DifferentialWatchedQueryOptions<RowType>): DifferentialWatchedQuery<RowType>;
2471
- }
2472
-
2473
- /**
2474
- * @public
2475
- */
2476
- interface SQLOpenOptions {
2477
- /**
2478
- * Filename for the database.
2479
- */
2480
- dbFilename: string;
2481
- /**
2482
- * Directory where the database file is located.
2483
- *
2484
- * When set, the directory must exist when the database is opened, it will
2485
- * not be created automatically.
2486
- */
2487
- dbLocation?: string;
2488
- /**
2489
- * Enable debugMode to log queries to the performance timeline.
2490
- *
2491
- * Defaults to false.
2492
- *
2493
- * To enable in development builds, use:
2494
- *
2495
- * debugMode: process.env.NODE_ENV !== 'production'
2496
- */
2497
- debugMode?: boolean;
2498
- }
2499
- /**
2500
- * @public
2501
- */
2502
- interface SQLOpenFactory {
2503
- /**
2504
- * Opens a connection adapter to a SQLite DB
2505
- */
2506
- openDB(): DBAdapter;
2507
- }
2508
- /**
2509
- * Tests if the input is a {@link SQLOpenOptions}
2510
- *
2511
- * @internal
2512
- */
2513
- declare const isSQLOpenOptions: (test: any) => test is SQLOpenOptions;
2514
- /**
2515
- * Tests if input is a {@link SQLOpenFactory}
2516
- *
2517
- * @internal
2518
- */
2519
- declare const isSQLOpenFactory: (test: any) => test is SQLOpenFactory;
2520
- /**
2521
- * Tests if input is a {@link DBAdapter}
2522
- *
2523
- * @internal
2524
- */
2525
- declare const isDBAdapter: (test: any) => test is DBAdapter;
2526
-
2527
- /**
2528
- * @public
2529
- */
2530
- declare class CrudTransaction extends CrudBatch {
2531
- /**
2532
- * List of client-side changes.
2533
- */
2534
- crud: CrudEntry[];
2535
- /**
2536
- * Call to remove the changes from the local queue, once successfully uploaded.
2537
- */
2538
- complete: (checkpoint?: string) => Promise<void>;
2539
- /**
2540
- * If null, this contains a list of changes recorded without an explicit transaction associated.
2541
- */
2542
- transactionId?: number | undefined;
2543
- constructor(
2544
- /**
2545
- * List of client-side changes.
2546
- */
2547
- crud: CrudEntry[],
2548
- /**
2549
- * Call to remove the changes from the local queue, once successfully uploaded.
2550
- */
2551
- complete: (checkpoint?: string) => Promise<void>,
2552
- /**
2553
- * If null, this contains a list of changes recorded without an explicit transaction associated.
2554
- */
2555
- transactionId?: number | undefined);
2556
- }
2557
-
2558
- /**
2559
- * SQLite operations to track changes for with {@link TriggerManager}
2560
- *
2561
- * @experimental @alpha
2562
- */
2563
- declare enum DiffTriggerOperation {
2564
- INSERT = "INSERT",
2565
- UPDATE = "UPDATE",
2566
- DELETE = "DELETE"
2567
- }
2568
- /**
2569
- * @experimental @alpha
2570
- * Diffs created by {@link TriggerManager#createDiffTrigger} are stored in a temporary table.
2571
- * This is the base record structure for all diff records.
2572
- *
2573
- * @template TOperationId - The type for `operation_id`. Defaults to `number` as returned by default SQLite database queries.
2574
- * Use `string` for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2575
- */
2576
- interface BaseTriggerDiffRecord<TOperationId extends string | number = number> {
2577
- /**
2578
- * The modified row's `id` column value.
2579
- */
2580
- id: string;
2581
- /**
2582
- * The operation performed which created this record.
2583
- */
2584
- operation: DiffTriggerOperation;
2585
- /**
2586
- * Auto-incrementing primary key for the operation.
2587
- * Defaults to number as returned by database queries (wa-sqlite returns lower 32 bits).
2588
- * Can be string for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2589
- */
2590
- operation_id: TOperationId;
2591
- /**
2592
- * Time the change operation was recorded.
2593
- * This is in ISO 8601 format, e.g. `2023-10-01T12:00:00.000Z`.
2594
- */
2595
- timestamp: string;
2596
- }
2597
- /**
2598
- * @experimental @alpha
2599
- * Represents a diff record for a SQLite UPDATE operation.
2600
- * This record contains the new value and optionally the previous value.
2601
- * Values are stored as JSON strings.
2602
- */
2603
- interface TriggerDiffUpdateRecord<TOperationId extends string | number = number> extends BaseTriggerDiffRecord<TOperationId> {
2604
- operation: DiffTriggerOperation.UPDATE;
2605
- /**
2606
- * The updated state of the row in JSON string format.
2607
- */
2608
- value: string;
2609
- /**
2610
- * The previous value of the row in JSON string format.
2611
- */
2612
- previous_value: string;
2613
- }
2614
- /**
2615
- * @experimental @alpha
2616
- * Represents a diff record for a SQLite INSERT operation.
2617
- * This record contains the new value represented as a JSON string.
2618
- */
2619
- interface TriggerDiffInsertRecord<TOperationId extends string | number = number> extends BaseTriggerDiffRecord<TOperationId> {
2620
- operation: DiffTriggerOperation.INSERT;
2621
- /**
2622
- * The value of the row, at the time of INSERT, in JSON string format.
2623
- */
2624
- value: string;
2625
- }
2626
- /**
2627
- * @experimental @alpha
2628
- * Represents a diff record for a SQLite DELETE operation.
2629
- * This record contains the new value represented as a JSON string.
2630
- */
2631
- interface TriggerDiffDeleteRecord<TOperationId extends string | number = number> extends BaseTriggerDiffRecord<TOperationId> {
2632
- operation: DiffTriggerOperation.DELETE;
2633
- /**
2634
- * The value of the row, before the DELETE operation, in JSON string format.
2635
- */
2636
- value: string;
2637
- }
2638
- /**
2639
- * @experimental @alpha
2640
- * Diffs created by {@link TriggerManager#createDiffTrigger} are stored in a temporary table.
2641
- * This is the record structure for all diff records.
2642
- *
2643
- * Querying the DIFF table directly with {@link TriggerDiffHandlerContext#withDiff} will return records
2644
- * with the structure of this type.
2645
- *
2646
- * @template TOperationId - The type for `operation_id`. Defaults to `number` as returned by database queries.
2647
- * Use `string` for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2648
- *
2649
- * @example
2650
- * ```typescript
2651
- * // Default: operation_id is number
2652
- * const diffs = await context.withDiff<TriggerDiffRecord>('SELECT * FROM DIFF');
2653
- *
2654
- * // With string operation_id for full precision
2655
- * const diffsWithString = await context.withDiff<TriggerDiffRecord<string>>(
2656
- * 'SELECT * FROM DIFF',
2657
- * undefined,
2658
- * { castOperationIdAsText: true }
2659
- * );
2660
- * ```
2661
- */
2662
- type TriggerDiffRecord<TOperationId extends string | number = number> = TriggerDiffUpdateRecord<TOperationId> | TriggerDiffInsertRecord<TOperationId> | TriggerDiffDeleteRecord<TOperationId>;
2663
- /**
2664
- * @experimental @alpha
2665
- * Querying the DIFF table directly with {@link TriggerDiffHandlerContext#withExtractedDiff} will return records
2666
- * with the tracked columns extracted from the JSON value.
2667
- * This type represents the structure of such records.
2668
- *
2669
- * @template T - The type for the extracted columns from the tracked JSON value.
2670
- * @template TOperationId - The type for `operation_id`. Defaults to `number` as returned by database queries.
2671
- * Use `string` for full 64-bit precision when using `{ castOperationIdAsText: true }` option.
2672
- *
2673
- * @example
2674
- * ```typescript
2675
- * // Default: operation_id is number
2676
- * const diffs = await context.withExtractedDiff<ExtractedTriggerDiffRecord<{id: string, name: string}>>('SELECT * FROM DIFF');
2677
- *
2678
- * // With string operation_id for full precision
2679
- * const diffsWithString = await context.withExtractedDiff<ExtractedTriggerDiffRecord<{id: string, name: string}, string>>(
2680
- * 'SELECT * FROM DIFF',
2681
- * undefined,
2682
- * { castOperationIdAsText: true }
2683
- * );
2684
- * ```
2685
- */
2686
- type ExtractedTriggerDiffRecord<T, TOperationId extends string | number = number> = T & {
2687
- [K in keyof Omit<BaseTriggerDiffRecord<TOperationId>, 'id'> as `__${string & K}`]: TriggerDiffRecord<TOperationId>[K];
2688
- } & {
2689
- __previous_value?: string;
2690
- };
2691
- /**
2692
- * @experimental @alpha
2693
- * Hooks used in the creation of a table diff trigger.
2694
- */
2695
- interface TriggerCreationHooks {
2696
- /**
2697
- * Executed inside a write lock before the trigger is created.
2698
- */
2699
- beforeCreate?: (context: LockContext) => Promise<void>;
2700
- }
2701
- /**
2702
- * Common interface for options used in creating a diff trigger.
2703
- */
2704
- interface BaseCreateDiffTriggerOptions {
2705
- /**
2706
- * PowerSync source table/view to trigger and track changes from.
2707
- * This should be present in the PowerSync database's schema.
2708
- */
2709
- source: string;
2710
- /**
2711
- * Columns to track and report changes for.
2712
- * Defaults to all columns in the source table.
2713
- * Use an empty array to track only the ID and operation.
2714
- */
2715
- columns?: string[];
2716
- /**
2717
- * Condition to filter when the triggers should fire.
2718
- * This corresponds to a SQLite [WHEN](https://sqlite.org/lang_createtrigger.html) clause in the trigger body.
2719
- * This is useful for only triggering on specific conditions.
2720
- * For example, you can use it to only trigger on certain values in the NEW row.
2721
- * Note that for PowerSync the row data is stored in a JSON column named `data`.
2722
- * The row id is available in the `id` column.
2723
- *
2724
- * NB! The WHEN clauses here are added directly to the SQLite trigger creation SQL.
2725
- * Any user input strings here should be sanitized externally. The {@link when} string template function performs
2726
- * some basic sanitization, extra external sanitization is recommended.
2727
- *
2728
- * @example
2729
- * {
2730
- * 'INSERT': sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(list.id)}`,
2731
- * 'INSERT': `TRUE`,
2732
- * 'UPDATE': sanitizeSQL`NEW.id = 'abcd' AND json_extract(NEW.data, '$.status') = 'active'`,
2733
- * 'DELETE': sanitizeSQL`json_extract(OLD.data, '$.list_id') = 'abcd'`
2734
- * }
2735
- */
2736
- when: Partial<Record<DiffTriggerOperation, string>>;
2737
- /**
2738
- * Hooks which allow execution during the trigger creation process.
2739
- */
2740
- hooks?: TriggerCreationHooks;
2741
- /**
2742
- * Use storage-backed (non-TEMP) tables and triggers that persist across sessions.
2743
- * These resources are still automatically disposed when no longer claimed.
2744
- */
2745
- useStorage?: boolean;
2746
- }
2747
- /**
2748
- * @experimental @alpha
2749
- * Options for {@link TriggerManager#createDiffTrigger}.
2750
- */
2751
- interface CreateDiffTriggerOptions extends BaseCreateDiffTriggerOptions {
2752
- /**
2753
- * Destination table to send changes to.
2754
- * This table is created internally as a SQLite temporary table.
2755
- * This table will be dropped once the trigger is removed.
2756
- */
2757
- destination: string;
2758
- /**
2759
- * Context to use for the setup operation.
2760
- * This is useful for when the setup operation needs to be executed in a specific context.
2761
- */
2762
- setupContext?: LockContext;
2763
- }
2764
- /**
2765
- * @experimental @alpha
2766
- * Options for {@link TriggerRemoveCallback}.
2767
- */
2768
- interface TriggerRemoveCallbackOptions {
2769
- context?: LockContext;
2770
- }
2771
- /**
2772
- * @experimental @alpha
2773
- * Callback to drop a trigger after it has been created.
2774
- */
2775
- type TriggerRemoveCallback = (options?: TriggerRemoveCallbackOptions) => Promise<void>;
2776
- /**
2777
- * @experimental @alpha
2778
- * Options for {@link TriggerDiffHandlerContext#withDiff}.
2779
- */
2780
- interface WithDiffOptions {
2781
- /**
2782
- * If true, casts `operation_id` as TEXT in the internal CTE to preserve full 64-bit precision.
2783
- * Use this when you need to ensure `operation_id` is treated as a string to avoid precision loss
2784
- * for values exceeding JavaScript's Number.MAX_SAFE_INTEGER.
2785
- *
2786
- * When enabled, use {@link TriggerDiffRecord}<string> to type the result correctly.
2787
- */
2788
- castOperationIdAsText?: boolean;
2789
- }
2790
- /**
2791
- * @experimental @alpha
2792
- * Context for the `onChange` handler provided to {@link TriggerManager#trackTableDiff}.
2793
- */
2794
- interface TriggerDiffHandlerContext extends LockContext {
2795
- /**
2796
- * The name of the temporary destination table created by the trigger.
2797
- */
2798
- destinationTable: string;
2799
- /**
2800
- * Allows querying the database with access to the table containing DIFF records.
2801
- * The diff table is accessible via the `DIFF` accessor.
2802
- *
2803
- * The `DIFF` table is of the form described in {@link TriggerManager#createDiffTrigger}
2804
- * ```sql
2805
- * CREATE TEMP DIFF (
2806
- * operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
2807
- * id TEXT,
2808
- * operation TEXT,
2809
- * timestamp TEXT,
2810
- * value TEXT,
2811
- * previous_value TEXT
2812
- * );
2813
- * ```
2814
- *
2815
- * Note that the `value` and `previous_value` columns store the row state in JSON string format.
2816
- * To access the row state in an extracted form see {@link TriggerDiffHandlerContext#withExtractedDiff}.
2817
- *
2818
- * @example
2819
- * ```sql
2820
- * --- This fetches the current state of `todo` rows which have a diff operation present.
2821
- * --- The state of the row at the time of the operation is accessible in the DIFF records.
2822
- * SELECT
2823
- * todos.*
2824
- * FROM
2825
- * DIFF
2826
- * JOIN todos ON DIFF.id = todos.id
2827
- * WHERE json_extract(DIFF.value, '$.status') = 'active'
2828
- * ```
2829
- *
2830
- * @example
2831
- * ```typescript
2832
- * // With operation_id cast as TEXT for full precision
2833
- * const diffs = await context.withDiff<TriggerDiffRecord<string>>(
2834
- * 'SELECT * FROM DIFF',
2835
- * undefined,
2836
- * { castOperationIdAsText: true }
2837
- * );
2838
- * // diffs[0].operation_id is now typed as string
2839
- * ```
2840
- */
2841
- withDiff: <T = any>(query: string, params?: ReadonlyArray<Readonly<any>>, options?: WithDiffOptions) => Promise<T[]>;
2842
- /**
2843
- * Allows querying the database with access to the table containing diff records.
2844
- * The diff table is accessible via the `DIFF` accessor.
2845
- *
2846
- * This is similar to {@link TriggerDiffHandlerContext#withDiff} but extracts the row columns from the tracked JSON value. The diff operation
2847
- * data is aliased as `__` columns to avoid column conflicts.
2848
- *
2849
- * For {@link DiffTriggerOperation#DELETE} operations the previous_value columns are extracted for convenience.
2850
- *
2851
- *
2852
- * ```sql
2853
- * CREATE TEMP TABLE DIFF (
2854
- * id TEXT,
2855
- * replicated_column_1 COLUMN_TYPE,
2856
- * replicated_column_2 COLUMN_TYPE,
2857
- * __operation TEXT,
2858
- * __timestamp TEXT,
2859
- * __previous_value TEXT
2860
- * );
2861
- * ```
2862
- *
2863
- * @example
2864
- * ```sql
2865
- * SELECT
2866
- * todos.*
2867
- * FROM
2868
- * DIFF
2869
- * JOIN todos ON DIFF.id = todos.id
2870
- * --- The todo column names are extracted from json and are available as DIFF.name
2871
- * WHERE DIFF.name = 'example'
2872
- * ```
2873
- */
2874
- withExtractedDiff: <T = any>(query: string, params?: ReadonlyArray<Readonly<any>>) => Promise<T[]>;
2875
- }
2876
- /**
2877
- * @experimental @alpha
2878
- * Options for tracking changes to a table with {@link TriggerManager#trackTableDiff}.
2879
- */
2880
- interface TrackDiffOptions extends BaseCreateDiffTriggerOptions {
2881
- /**
2882
- * Handler for processing diff operations.
2883
- * Automatically invoked once diff items are present.
2884
- * Diff items are automatically cleared after the handler is invoked.
2885
- */
2886
- onChange: (context: TriggerDiffHandlerContext) => Promise<void>;
2887
- /**
2888
- * The minimum interval, in milliseconds, between {@link TrackDiffOptions.onChange} invocations.
2889
- * @default {@link DEFAULT_WATCH_THROTTLE_MS}
2890
- */
2891
- throttleMs?: number;
2892
- }
2893
- /**
2894
- * @experimental @alpha
2895
- */
2896
- interface TriggerManager {
2897
- /**
2898
- * @experimental
2899
- * Creates a temporary trigger which tracks changes to a source table
2900
- * and writes changes to a destination table.
2901
- * The temporary destination table is created internally and will be dropped when the trigger is removed.
2902
- * The temporary destination table is created with the structure:
2903
- *
2904
- * ```sql
2905
- * CREATE TEMP TABLE ${destination} (
2906
- * operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
2907
- * id TEXT,
2908
- * operation TEXT,
2909
- * timestamp TEXT,
2910
- * value TEXT,
2911
- * previous_value TEXT
2912
- * );
2913
- * ```
2914
- * The `value` column contains the JSON representation of the row's value at the change.
2915
- *
2916
- * For {@link DiffTriggerOperation#UPDATE} operations the `previous_value` column contains the previous value of the changed row
2917
- * in a JSON format.
2918
- *
2919
- * NB: The triggers created by this method might be invalidated by {@link AbstractPowerSyncDatabase#updateSchema} calls.
2920
- * These triggers should manually be dropped and recreated when updating the schema.
2921
- *
2922
- * @returns A callback to remove the trigger and drop the destination table.
2923
- *
2924
- * @example
2925
- * ```javascript
2926
- * const dispose = await database.triggers.createDiffTrigger({
2927
- * source: 'lists',
2928
- * destination: 'ps_temp_lists_diff',
2929
- * columns: ['name'],
2930
- * when: {
2931
- * [DiffTriggerOperation.INSERT]: 'TRUE',
2932
- * [DiffTriggerOperation.UPDATE]: 'TRUE',
2933
- * [DiffTriggerOperation.DELETE]: 'TRUE'
2934
- * }
2935
- * });
2936
- * ```
2937
- */
2938
- createDiffTrigger(options: CreateDiffTriggerOptions): Promise<TriggerRemoveCallback>;
2939
- /**
2940
- * @experimental
2941
- * Tracks changes for a table. Triggering a provided handler on changes.
2942
- * Uses {@link TriggerManager.createDiffTrigger} internally to create a temporary destination table.
2943
- *
2944
- * @returns A callback to cleanup the trigger and stop tracking changes.
2945
- *
2946
- * NB: The triggers created by this method might be invalidated by {@link AbstractPowerSyncDatabase#updateSchema} calls.
2947
- * These triggers should manually be dropped and recreated when updating the schema.
2948
- *
2949
- * @example
2950
- * ```javascript
2951
- * const dispose = database.triggers.trackTableDiff({
2952
- * source: 'todos',
2953
- * columns: ['list_id'],
2954
- * when: {
2955
- * [DiffTriggerOperation.INSERT]: sanitizeSQL`json_extract(NEW.data, '$.list_id') = ${sanitizeUUID(someIdVariable)}`
2956
- * },
2957
- * onChange: async (context) => {
2958
- * // Fetches the todo records that were inserted during this diff
2959
- * const newTodos = await context.withDiff<Database['todos']>(`
2960
- * SELECT
2961
- * todos.*
2962
- * FROM
2963
- * DIFF
2964
- * JOIN todos ON DIFF.id = todos.id
2965
- * `);
2966
- *
2967
- * // Process newly created todos
2968
- * },
2969
- * hooks: {
2970
- * beforeCreate: async (lockContext) => {
2971
- * // This hook is executed inside the write lock before the trigger is created.
2972
- * // It can be used to synchronize the current state of the table with processor logic.
2973
- * // Any changes after this callback are guaranteed to trigger the `onChange` handler.
2974
- *
2975
- * // Read the current state of the todos table
2976
- * const currentTodos = await lockContext.getAll<Database['todos']>(
2977
- * `
2978
- * SELECT
2979
- * *
2980
- * FROM
2981
- * todos
2982
- * WHERE
2983
- * list_id = ?
2984
- * `,
2985
- * ['123']
2986
- * );
2987
- *
2988
- * // Process existing todos
2989
- * }
2990
- * }
2991
- * });
2992
- * ```
2993
- */
2994
- trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback>;
2995
- }
2996
- /**
2997
- * @experimental
2998
- * @internal
2999
- * Manages claims on persisted SQLite triggers and destination tables to enable proper cleanup
3000
- * when they are no longer actively in use.
3001
- *
3002
- * When using persisted triggers (especially for OPFS multi-tab scenarios), we need a reliable way to determine which resources are still actively in use across different connections/tabs so stale resources can be safely cleaned up without interfering with active triggers.
3003
- *
3004
- * A cleanup process runs
3005
- * on database creation (and every 2 minutes) that:
3006
- * 1. Queries for existing managed persisted resources
3007
- * 2. Checks with the claim manager if any consumer is actively using those resources
3008
- * 3. Deletes unused resources
3009
- */
3010
- interface TriggerClaimManager {
3011
- /**
3012
- * Obtains or marks a claim on a certain identifier.
3013
- * @returns a callback to release the claim.
3014
- */
3015
- obtainClaim: (identifier: string) => Promise<() => Promise<void>>;
3016
- /**
3017
- * Checks if a claim is present for an identifier.
3018
- */
3019
- checkClaim: (identifier: string) => Promise<boolean>;
3020
- }
3021
- /**
3022
- * @experimental
3023
- * @internal
3024
- */
3025
- interface TriggerManagerConfig {
3026
- claimManager: TriggerClaimManager;
3027
- }
3028
-
3029
- type TriggerManagerImplOptions = TriggerManagerConfig & {
3030
- db: AbstractPowerSyncDatabase;
3031
- schema: Schema;
3032
- };
3033
- type TriggerManagerImplConfiguration = {
3034
- useStorageByDefault: boolean;
3035
- };
3036
- /**
3037
- * @internal
3038
- * @experimental
3039
- */
3040
- declare class TriggerManagerImpl implements TriggerManager {
3041
- protected options: TriggerManagerImplOptions;
3042
- protected schema: Schema;
3043
- protected defaultConfig: TriggerManagerImplConfiguration;
3044
- protected cleanupTimeout: ReturnType<typeof setTimeout> | null;
3045
- protected isDisposed: boolean;
3046
- constructor(options: TriggerManagerImplOptions);
3047
- protected get db(): AbstractPowerSyncDatabase;
3048
- protected getUUID(ctx?: LockContext): Promise<string>;
3049
- protected removeTriggers(tx: LockContext, triggerIds: string[]): Promise<void>;
3050
- dispose(): void;
3051
- /**
3052
- * Updates default config settings for platform specific use-cases.
3053
- */
3054
- updateDefaults(config: TriggerManagerImplConfiguration): void;
3055
- protected generateTriggerName(operation: DiffTriggerOperation, destinationTable: string, triggerId: string): string;
3056
- /**
3057
- * Cleanup any SQLite triggers or tables that are no longer in use.
3058
- */
3059
- cleanupResources(): Promise<void>;
3060
- createDiffTrigger(options: CreateDiffTriggerOptions): Promise<(options?: TriggerRemoveCallbackOptions) => Promise<void>>;
3061
- trackTableDiff(options: TrackDiffOptions): Promise<TriggerRemoveCallback>;
3062
- }
3063
-
3064
- /**
3065
- * @internal
3066
- */
3067
- type UnlockFn = () => void;
3068
- /**
3069
- * An asynchronous semaphore implementation with associated items per lease.
3070
- *
3071
- * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3072
- */
3073
- declare class Semaphore<T> {
3074
- private readonly available;
3075
- readonly size: number;
3076
- private firstWaiter?;
3077
- private lastWaiter?;
3078
- constructor(elements: Iterable<T>);
3079
- private addWaiter;
3080
- private deactivateWaiter;
3081
- private requestPermits;
3082
- /**
3083
- * Requests a single item from the pool.
3084
- *
3085
- * The returned `release` callback must be invoked to return the item into the pool.
3086
- */
3087
- requestOne(abort?: AbortSignal): Promise<{
3088
- item: T;
3089
- release: UnlockFn;
3090
- }>;
3091
- /**
3092
- * Requests access to all items from the pool.
3093
- *
3094
- * The returned `release` callback must be invoked to return items into the pool.
3095
- */
3096
- requestAll(abort?: AbortSignal): Promise<{
3097
- items: T[];
3098
- release: UnlockFn;
3099
- }>;
3100
- }
3101
- /**
3102
- * An asynchronous mutex implementation.
3103
- *
3104
- * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3105
- */
3106
- declare class Mutex {
3107
- private inner;
3108
- acquire(abort?: AbortSignal): Promise<UnlockFn>;
3109
- runExclusive<T>(fn: () => PromiseLike<T> | T, abort?: AbortSignal): Promise<T>;
3110
- }
3111
- /**
3112
- * Creates a signal aborting after the set timeout.
3113
- *
3114
- * @internal
3115
- */
3116
- declare function timeoutSignal(timeout: number): AbortSignal;
3117
- /**
3118
- * @internal
3119
- */
3120
- declare function timeoutSignal(timeout?: number): AbortSignal | undefined;
3121
-
3122
- /**
3123
- * @public
3124
- */
3125
- interface DisconnectAndClearOptions {
3126
- /** When set to false, data in local-only tables is preserved. */
3127
- clearLocal?: boolean;
3128
- }
3129
- /**
3130
- * @public
3131
- */
3132
- interface BasePowerSyncDatabaseOptions extends AdditionalConnectionOptions {
3133
- /** Schema used for the local database. */
3134
- schema: Schema;
3135
- /**
3136
- * @deprecated Use {@link AdditionalConnectionOptions.retryDelayMs} instead as this will be removed in future
3137
- * releases.
3138
- */
3139
- retryDelay?: number;
3140
- logger?: ILogger;
3141
- }
3142
- /**
3143
- * @public
3144
- */
3145
- interface PowerSyncDatabaseOptions extends BasePowerSyncDatabaseOptions {
3146
- /**
3147
- * Source for a SQLite database connection.
3148
- * This can be either:
3149
- * - A {@link DBAdapter} if providing an instantiated SQLite connection
3150
- * - A {@link SQLOpenFactory} which will be used to open a SQLite connection
3151
- * - {@link SQLOpenOptions} for opening a SQLite connection with a default {@link SQLOpenFactory}
3152
- */
3153
- database: DBAdapter | SQLOpenFactory | SQLOpenOptions;
3154
- }
3155
- /**
3156
- * @public
3157
- */
3158
- interface PowerSyncDatabaseOptionsWithDBAdapter extends BasePowerSyncDatabaseOptions {
3159
- database: DBAdapter;
3160
- }
3161
- /**
3162
- * @public
3163
- */
3164
- interface PowerSyncDatabaseOptionsWithOpenFactory extends BasePowerSyncDatabaseOptions {
3165
- database: SQLOpenFactory;
3166
- }
3167
- /**
3168
- * @public
3169
- */
3170
- interface PowerSyncDatabaseOptionsWithSettings extends BasePowerSyncDatabaseOptions {
3171
- database: SQLOpenOptions;
3172
- }
3173
- /**
3174
- * @public
3175
- */
3176
- interface SQLOnChangeOptions {
3177
- signal?: AbortSignal;
3178
- tables?: string[];
3179
- /** The minimum interval between queries. */
3180
- throttleMs?: number;
3181
- /**
3182
- * @deprecated All tables specified in {@link SQLOnChangeOptions.tables} will be watched, including PowerSync tables
3183
- * with prefixes.
3184
- *
3185
- * Allows for watching any SQL table
3186
- * by not removing PowerSync table name prefixes
3187
- */
3188
- rawTableNames?: boolean;
3189
- /**
3190
- * Emits an empty result set immediately
3191
- */
3192
- triggerImmediate?: boolean;
3193
- }
3194
- /**
3195
- * @public
3196
- */
3197
- interface SQLWatchOptions extends SQLOnChangeOptions {
3198
- /**
3199
- * Optional comparator which will be used to compare the results of the query.
3200
- * The watched query will only yield results if the comparator returns false.
3201
- */
3202
- comparator?: WatchedQueryComparator<QueryResult>;
3203
- }
3204
- /**
3205
- * @public
3206
- */
3207
- interface WatchOnChangeEvent {
3208
- changedTables: string[];
3209
- }
3210
- /**
3211
- * @public
3212
- */
3213
- interface WatchHandler {
3214
- onResult: (results: QueryResult) => void;
3215
- onError?: (error: Error) => void;
3216
- }
3217
- /**
3218
- * @public
3219
- */
3220
- interface WatchOnChangeHandler {
3221
- onChange: (event: WatchOnChangeEvent) => Promise<void> | void;
3222
- onError?: (error: Error) => void;
3223
- }
3224
- /**
3225
- * @public
3226
- */
3227
- interface PowerSyncDBListener extends StreamingSyncImplementationListener {
3228
- initialized: () => void;
3229
- schemaChanged: (schema: Schema) => void;
3230
- closing: () => Promise<void> | void;
3231
- closed: () => Promise<void> | void;
3232
- }
3233
- /**
3234
- * @public
3235
- */
3236
- interface PowerSyncCloseOptions {
3237
- /**
3238
- * Disconnect the sync stream client if connected.
3239
- * This is usually true, but can be false for Web when using
3240
- * multiple tabs and a shared sync provider.
3241
- */
3242
- disconnect?: boolean;
3243
- }
3244
- /**
3245
- * @internal
3246
- */
3247
- declare const DEFAULT_POWERSYNC_CLOSE_OPTIONS: PowerSyncCloseOptions;
3248
- /**
3249
- * @internal
3250
- */
3251
- declare const DEFAULT_POWERSYNC_DB_OPTIONS: {
3252
- retryDelayMs: number;
3253
- crudUploadThrottleMs: number;
3254
- };
3255
- /**
3256
- * @internal
3257
- */
3258
- declare const DEFAULT_CRUD_BATCH_LIMIT = 100;
3259
- /**
3260
- * Requesting nested or recursive locks can block the application in some circumstances.
3261
- * This default lock timeout will act as a failsafe to throw an error if a lock cannot
3262
- * be obtained.
3263
- *
3264
- * @internal
3265
- */
3266
- declare const DEFAULT_LOCK_TIMEOUT_MS = 120000;
3267
- /**
3268
- * Tests if the input is a {@link PowerSyncDatabaseOptionsWithSettings}
3269
- * @internal
3270
- */
3271
- declare const isPowerSyncDatabaseOptionsWithSettings: (test: any) => test is PowerSyncDatabaseOptionsWithSettings;
3272
- /**
3273
- * @public
3274
- */
3275
- declare abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDBListener> {
3276
- protected options: PowerSyncDatabaseOptions;
3277
- /**
3278
- * Returns true if the connection is closed.
3279
- */
3280
- closed: boolean;
3281
- ready: boolean;
3282
- /**
3283
- * Current connection status.
3284
- */
3285
- currentStatus: SyncStatus;
3286
- sdkVersion: string;
3287
- protected bucketStorageAdapter: BucketStorageAdapter;
3288
- protected _isReadyPromise: Promise<void>;
3289
- protected connectionManager: ConnectionManager;
3290
- private subscriptions;
3291
- get syncStreamImplementation(): StreamingSyncImplementation | null;
3292
- /**
3293
- * The connector used to connect to the PowerSync service.
3294
- *
3295
- * @returns The connector used to connect to the PowerSync service or null if `connect()` has not been called.
3296
- */
3297
- get connector(): PowerSyncBackendConnector | null;
3298
- /**
3299
- * The resolved connection options used to connect to the PowerSync service.
3300
- *
3301
- * @returns The resolved connection options used to connect to the PowerSync service or null if `connect()` has not been called.
3302
- */
3303
- get connectionOptions(): InternalConnectionOptions | null;
3304
- protected _schema: Schema;
3305
- private _database;
3306
- protected runExclusiveMutex: Mutex;
3307
- /**
3308
- * @experimental
3309
- * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
3310
- */
3311
- readonly triggers: TriggerManager;
3312
- protected triggersImpl: TriggerManagerImpl;
3313
- logger: ILogger;
3314
- constructor(options: PowerSyncDatabaseOptionsWithDBAdapter);
3315
- constructor(options: PowerSyncDatabaseOptionsWithOpenFactory);
3316
- constructor(options: PowerSyncDatabaseOptionsWithSettings);
3317
- constructor(options: PowerSyncDatabaseOptions);
3318
- /**
3319
- * Schema used for the local database.
3320
- */
3321
- get schema(): Schema<{
3322
- [x: string]: Table<any>;
3323
- }>;
3324
- /**
3325
- * The underlying database.
3326
- *
3327
- * For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.
3328
- */
3329
- get database(): DBAdapter;
3330
- /**
3331
- * Whether a connection to the PowerSync service is currently open.
3332
- */
3333
- get connected(): boolean;
3334
- get connecting(): boolean;
3335
- /**
3336
- * Opens the DBAdapter given open options using a default open factory
3337
- */
3338
- protected abstract openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter;
3339
- /**
3340
- * Generates a base configuration for {@link TriggerManagerImpl}.
3341
- * Implementations should override this if necessary.
3342
- */
3343
- protected generateTriggerManagerConfig(): TriggerManagerConfig;
3344
- protected abstract generateSyncStreamImplementation(connector: PowerSyncBackendConnector, options: CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions): StreamingSyncImplementation;
3345
- protected abstract generateBucketStorageAdapter(): BucketStorageAdapter;
3346
- /**
3347
- * @returns A promise which will resolve once initialization is completed.
3348
- */
3349
- waitForReady(): Promise<void>;
3350
- /**
3351
- * Wait for the first sync operation to complete.
3352
- *
3353
- * @param request - Either an abort signal (after which the promise will complete regardless of
3354
- * whether a full sync was completed) or an object providing an abort signal and a priority target.
3355
- * When a priority target is set, the promise may complete when all buckets with the given (or higher)
3356
- * priorities have been synchronized. This can be earlier than a complete sync.
3357
- * @returns A promise which will resolve once the first full sync has completed.
3358
- */
3359
- waitForFirstSync(request?: AbortSignal | {
3360
- signal?: AbortSignal;
3361
- priority?: number;
3362
- }): Promise<void>;
3363
- /**
3364
- * Waits for the first sync status for which the `status` callback returns a truthy value.
3365
- */
3366
- waitForStatus(predicate: (status: SyncStatus) => any, signal?: AbortSignal): Promise<void>;
3367
- /**
3368
- * Allows for extended implementations to execute custom initialization
3369
- * logic as part of the total init process
3370
- */
3371
- abstract _initialize(): Promise<void>;
3372
- /**
3373
- * Entry point for executing initialization logic.
3374
- * This is to be automatically executed in the constructor.
3375
- */
3376
- protected initialize(): Promise<void>;
3377
- protected loadVersion(): Promise<void>;
3378
- protected resolveOfflineSyncStatus(): Promise<void>;
3379
- /**
3380
- * Replace the schema with a new version. This is for advanced use cases - typically the schema should just be specified once in the constructor.
3381
- *
3382
- * Cannot be used while connected - this should only be called before {@link AbstractPowerSyncDatabase.connect}.
3383
- */
3384
- updateSchema(schema: Schema): Promise<void>;
3385
- /**
3386
- * Wait for initialization to complete.
3387
- * While initializing is automatic, this helps to catch and report initialization errors.
3388
- */
3389
- init(): Promise<void>;
3390
- protected resolvedConnectionOptions(options: CreateSyncImplementationOptions): CreateSyncImplementationOptions & RequiredAdditionalConnectionOptions;
3391
- /**
3392
- * @deprecated Use {@link AbstractPowerSyncDatabase#close} instead.
3393
- * Clears all listeners registered by {@link AbstractPowerSyncDatabase#registerListener}.
3394
- */
3395
- dispose(): void;
3396
- /**
3397
- * Locking mechanism for exclusively running critical portions of connect/disconnect operations.
3398
- * Locking here is mostly only important on web for multiple tab scenarios.
3399
- */
3400
- protected runExclusive<T>(callback: () => Promise<T>): Promise<T>;
3401
- /**
3402
- * Connects to stream of events from the PowerSync instance.
3403
- */
3404
- connect(connector: PowerSyncBackendConnector, options?: PowerSyncConnectionOptions): Promise<void>;
3405
- /**
3406
- * Close the sync connection.
3407
- *
3408
- * Use {@link AbstractPowerSyncDatabase.connect} to connect again.
3409
- */
3410
- disconnect(): Promise<void>;
3411
- /**
3412
- * Disconnect and clear the database.
3413
- * Use this when logging out.
3414
- * The database can still be queried after this is called, but the tables
3415
- * would be empty.
3416
- *
3417
- * To preserve data in local-only tables, set clearLocal to false.
3418
- */
3419
- disconnectAndClear(options?: DisconnectAndClearOptions): Promise<void>;
3420
- /**
3421
- * Create a sync stream to query its status or to subscribe to it.
3422
- *
3423
- * @param name - The name of the stream to subscribe to.
3424
- * @param params - Optional parameters for the stream subscription.
3425
- * @returns A {@link SyncStream} instance that can be subscribed to.
3426
- * @experimental Sync streams are currently in alpha.
3427
- */
3428
- syncStream(name: string, params?: Record<string, any>): SyncStream;
3429
- /**
3430
- * Close the database, releasing resources.
3431
- *
3432
- * Also disconnects any active connection.
3433
- *
3434
- * Once close is called, this connection cannot be used again - a new one
3435
- * must be constructed.
3436
- */
3437
- close(options?: PowerSyncCloseOptions): Promise<void>;
3438
- /**
3439
- * Get upload queue size estimate and count.
3440
- */
3441
- getUploadQueueStats(includeSize?: boolean): Promise<UploadQueueStats>;
3442
- /**
3443
- * Get a batch of CRUD data to upload.
3444
- *
3445
- * Returns null if there is no data to upload.
3446
- *
3447
- * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
3448
- *
3449
- * Once the data have been successfully uploaded, call {@link CrudBatch.complete} before
3450
- * requesting the next batch.
3451
- *
3452
- * Use the `limit` parameter to specify the maximum number of updates to return in a single
3453
- * batch.
3454
- *
3455
- * This method does include transaction ids in the result, but does not group
3456
- * data by transaction. One batch may contain data from multiple transactions,
3457
- * and a single transaction may be split over multiple batches.
3458
- *
3459
- * @param limit - Maximum number of CRUD entries to include in the batch
3460
- * @returns A batch of CRUD operations to upload, or null if there are none
3461
- */
3462
- getCrudBatch(limit?: number): Promise<CrudBatch | null>;
3463
- /**
3464
- * Get the next recorded transaction to upload.
3465
- *
3466
- * Returns null if there is no data to upload.
3467
- *
3468
- * Use this from the {@link PowerSyncBackendConnector.uploadData} callback.
3469
- *
3470
- * Once the data have been successfully uploaded, call {@link CrudTransaction.complete} before
3471
- * requesting the next transaction.
3472
- *
3473
- * Unlike {@link AbstractPowerSyncDatabase.getCrudBatch}, this only returns data from a single transaction at a time.
3474
- * All data for the transaction is loaded into memory.
3475
- *
3476
- * @returns A transaction of CRUD operations to upload, or null if there are none
3477
- */
3478
- getNextCrudTransaction(): Promise<CrudTransaction | null>;
3479
- /**
3480
- * Returns an async iterator of completed transactions with local writes against the database.
3481
- *
3482
- * This is typically used from the {@link PowerSyncBackendConnector.uploadData} callback. Each entry emitted by the
3483
- * returned iterator is a full transaction containing all local writes made while that transaction was active.
3484
- *
3485
- * Unlike {@link AbstractPowerSyncDatabase.getNextCrudTransaction}, which always returns the oldest transaction that hasn't been
3486
- * {@link CrudTransaction.complete}d yet, this iterator can be used to receive multiple transactions. Calling
3487
- * {@link CrudTransaction.complete} will mark that and all prior transactions emitted by the iterator as completed.
3488
- *
3489
- * This can be used to upload multiple transactions in a single batch, e.g with:
3490
- *
3491
- * ```JavaScript
3492
- * let lastTransaction = null;
3493
- * let batch = [];
3494
- *
3495
- * for await (const transaction of database.getCrudTransactions()) {
3496
- * batch.push(...transaction.crud);
3497
- * lastTransaction = transaction;
3498
- *
3499
- * if (batch.length > 10) {
3500
- * break;
3501
- * }
3502
- * }
3503
- * ```
3504
- *
3505
- * If there is no local data to upload, the async iterator complete without emitting any items.
3506
- *
3507
- * 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)
3508
- * for React Native.
3509
- */
3510
- getCrudTransactions(): AsyncIterable<CrudTransaction, null>;
3511
- /**
3512
- * Get an unique client id for this database.
3513
- *
3514
- * The id is not reset when the database is cleared, only when the database is deleted.
3515
- *
3516
- * @returns A unique identifier for the database instance
3517
- */
3518
- getClientId(): Promise<string>;
3519
- private handleCrudCheckpoint;
3520
- /**
3521
- * Execute a SQL write (INSERT/UPDATE/DELETE) query
3522
- * and optionally return results.
3523
- *
3524
- * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
3525
- * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
3526
- * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
3527
- *
3528
- * @param sql - The SQL query to execute
3529
- * @param parameters - Optional array of parameters to bind to the query
3530
- * @returns The query result as an object with structured key-value pairs
3531
- */
3532
- execute(sql: string, parameters?: any[]): Promise<QueryResult>;
3533
- /**
3534
- * Execute a SQL write (INSERT/UPDATE/DELETE) query directly on the database without any PowerSync processing.
3535
- * This bypasses certain PowerSync abstractions and is useful for accessing the raw database results.
3536
- *
3537
- * @param sql - The SQL query to execute
3538
- * @param parameters - Optional array of parameters to bind to the query
3539
- * @returns The raw query result from the underlying database as a nested array of raw values, where each row is
3540
- * represented as an array of column values without field names.
3541
- */
3542
- executeRaw(sql: string, parameters?: any[]): Promise<any[][]>;
3543
- /**
3544
- * Execute a write query (INSERT/UPDATE/DELETE) multiple times with each parameter set
3545
- * and optionally return results.
3546
- * This is faster than executing separately with each parameter set.
3547
- *
3548
- * @param sql - The SQL query to execute
3549
- * @param parameters - Optional 2D array of parameter sets, where each inner array is a set of parameters for one execution
3550
- * @returns The query result
3551
- */
3552
- executeBatch(sql: string, parameters?: any[][]): Promise<QueryResult>;
3553
- /**
3554
- * Execute a read-only query and return results.
3555
- *
3556
- * @param sql - The SQL query to execute
3557
- * @param parameters - Optional array of parameters to bind to the query
3558
- * @returns An array of results
3559
- */
3560
- getAll<T>(sql: string, parameters?: any[]): Promise<T[]>;
3561
- /**
3562
- * Execute a read-only query and return the first result, or null if the ResultSet is empty.
3563
- *
3564
- * @param sql - The SQL query to execute
3565
- * @param parameters - Optional array of parameters to bind to the query
3566
- * @returns The first result if found, or null if no results are returned
3567
- */
3568
- getOptional<T>(sql: string, parameters?: any[]): Promise<T | null>;
3569
- /**
3570
- * Execute a read-only query and return the first result, error if the ResultSet is empty.
3571
- *
3572
- * @param sql - The SQL query to execute
3573
- * @param parameters - Optional array of parameters to bind to the query
3574
- * @returns The first result matching the query
3575
- * @throws Error if no rows are returned
3576
- */
3577
- get<T>(sql: string, parameters?: any[]): Promise<T>;
3578
- /**
3579
- * Takes a read lock, without starting a transaction.
3580
- * In most cases, {@link AbstractPowerSyncDatabase.readTransaction} should be used instead.
3581
- */
3582
- readLock<T>(callback: (db: LockContext) => Promise<T>): Promise<T>;
3583
- /**
3584
- * Takes a global lock, without starting a transaction.
3585
- * In most cases, {@link AbstractPowerSyncDatabase.writeTransaction} should be used instead.
3586
- */
3587
- writeLock<T>(callback: (db: LockContext) => Promise<T>): Promise<T>;
3588
- /**
3589
- * Open a read-only transaction.
3590
- * Read transactions can run concurrently to a write transaction.
3591
- * Changes from any write transaction are not visible to read transactions started before it.
3592
- *
3593
- * @param callback - Function to execute within the transaction
3594
- * @param lockTimeout - Time in milliseconds to wait for a lock before throwing an error
3595
- * @returns The result of the callback
3596
- * @throws Error if the lock cannot be obtained within the timeout period
3597
- */
3598
- readTransaction<T>(callback: (tx: Transaction) => Promise<T>, lockTimeout?: number): Promise<T>;
3599
- /**
3600
- * Open a read-write transaction.
3601
- * This takes a global lock - only one write transaction can execute against the database at a time.
3602
- * Statements within the transaction must be done on the provided {@link Transaction} interface.
3603
- *
3604
- * @param callback - Function to execute within the transaction
3605
- * @param lockTimeout - Time in milliseconds to wait for a lock before throwing an error
3606
- * @returns The result of the callback
3607
- * @throws Error if the lock cannot be obtained within the timeout period
3608
- */
3609
- writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, lockTimeout?: number): Promise<T>;
3610
- /**
3611
- * This version of `watch` uses `AsyncGenerator`, for documentation see {@link AbstractPowerSyncDatabase.watchWithAsyncGenerator}.
3612
- * Can be overloaded to use a callback handler instead, for documentation see {@link AbstractPowerSyncDatabase.watchWithCallback}.
3613
- *
3614
- * @example
3615
- * ```javascript
3616
- * async *attachmentIds() {
3617
- * for await (const result of this.powersync.watch(
3618
- * `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
3619
- * []
3620
- * )) {
3621
- * yield result.rows?._array.map((r) => r.id) ?? [];
3622
- * }
3623
- * }
3624
- * ```
3625
- */
3626
- watch(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
3627
- /**
3628
- * See {@link AbstractPowerSyncDatabase.watchWithCallback}.
3629
- *
3630
- * @example
3631
- * ```javascript
3632
- * onAttachmentIdsChange(onResult) {
3633
- * this.powersync.watch(
3634
- * `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
3635
- * [],
3636
- * {
3637
- * onResult: (result) => onResult(result.rows?._array.map((r) => r.id) ?? [])
3638
- * }
3639
- * );
3640
- * }
3641
- * ```
3642
- */
3643
- watch(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
3644
- /**
3645
- * Allows defining a query which can be used to build a {@link WatchedQuery}.
3646
- * The defined query will be executed with {@link AbstractPowerSyncDatabase#getAll}.
3647
- * An optional mapper function can be provided to transform the results.
3648
- *
3649
- * @example
3650
- * ```javascript
3651
- * const watchedTodos = powersync.query({
3652
- * sql: `SELECT photo_id as id FROM todos WHERE photo_id IS NOT NULL`,
3653
- * parameters: [],
3654
- * mapper: (row) => ({
3655
- * ...row,
3656
- * created_at: new Date(row.created_at as string)
3657
- * })
3658
- * })
3659
- * .watch()
3660
- * // OR use .differentialWatch() for fine-grained watches.
3661
- * ```
3662
- */
3663
- query<RowType>(query: ArrayQueryDefinition<RowType>): Query<RowType>;
3664
- /**
3665
- * Allows building a {@link WatchedQuery} using an existing {@link WatchCompatibleQuery}.
3666
- * The watched query will use the provided {@link WatchCompatibleQuery.execute} method to query results.
3667
- *
3668
- * @example
3669
- * ```javascript
3670
- *
3671
- * // Potentially a query from an ORM like Drizzle
3672
- * const query = db.select().from(lists);
3673
- *
3674
- * const watchedTodos = powersync.customQuery(query)
3675
- * .watch()
3676
- * // OR use .differentialWatch() for fine-grained watches.
3677
- * ```
3678
- */
3679
- customQuery<RowType>(query: WatchCompatibleQuery<RowType[]>): Query<RowType>;
3680
- /**
3681
- * Execute a read query every time the source tables are modified.
3682
- * Use {@link SQLOnChangeOptions.throttleMs} to specify the minimum interval between queries.
3683
- * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
3684
- *
3685
- * Note that the `onChange` callback member of the handler is required.
3686
- *
3687
- * @param sql - The SQL query to execute
3688
- * @param parameters - Optional array of parameters to bind to the query
3689
- * @param handler - Callbacks for handling results and errors
3690
- * @param options - Options for configuring watch behavior
3691
- */
3692
- watchWithCallback(sql: string, parameters?: any[], handler?: WatchHandler, options?: SQLWatchOptions): void;
3693
- /**
3694
- * Execute a read query every time the source tables are modified.
3695
- * Use {@link SQLOnChangeOptions.throttleMs} to specify the minimum interval between queries.
3696
- * Source tables are automatically detected using `EXPLAIN QUERY PLAN`.
3697
- *
3698
- * @param sql - The SQL query to execute
3699
- * @param parameters - Optional array of parameters to bind to the query
3700
- * @param options - Options for configuring watch behavior
3701
- * @returns An AsyncIterable that yields QueryResults whenever the data changes
3702
- */
3703
- watchWithAsyncGenerator(sql: string, parameters?: any[], options?: SQLWatchOptions): AsyncIterable<QueryResult>;
3704
- /**
3705
- * Resolves the list of tables that are used in a SQL query.
3706
- * If tables are specified in the options, those are used directly.
3707
- * Otherwise, analyzes the query using EXPLAIN to determine which tables are accessed.
3708
- *
3709
- * @param sql - The SQL query to analyze
3710
- * @param parameters - Optional parameters for the SQL query
3711
- * @param options - Optional watch options that may contain explicit table list
3712
- * @returns Array of table names that the query depends on
3713
- */
3714
- resolveTables(sql: string, parameters?: any[], options?: SQLWatchOptions): Promise<string[]>;
3715
- /**
3716
- * This version of `onChange` uses `AsyncGenerator`, for documentation see {@link AbstractPowerSyncDatabase.onChangeWithAsyncGenerator}.
3717
- * Can be overloaded to use a callback handler instead, for documentation see {@link AbstractPowerSyncDatabase.onChangeWithCallback}.
3718
- *
3719
- * @example
3720
- * ```javascript
3721
- * async monitorChanges() {
3722
- * for await (const event of this.powersync.onChange({tables: ['todos']})) {
3723
- * console.log('Detected change event:', event);
3724
- * }
3725
- * }
3726
- * ```
3727
- */
3728
- onChange(options?: SQLOnChangeOptions): AsyncIterable<WatchOnChangeEvent>;
3729
- /**
3730
- * See {@link AbstractPowerSyncDatabase.onChangeWithCallback}.
3731
- *
3732
- * @example
3733
- * ```javascript
3734
- * monitorChanges() {
3735
- * this.powersync.onChange({
3736
- * onChange: (event) => {
3737
- * console.log('Change detected:', event);
3738
- * }
3739
- * }, { tables: ['todos'] });
3740
- * }
3741
- * ```
3742
- */
3743
- onChange(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
3744
- /**
3745
- * Invoke the provided callback on any changes to any of the specified tables.
3746
- *
3747
- * This is preferred over {@link AbstractPowerSyncDatabase.watchWithCallback} when multiple queries need to be performed
3748
- * together when data is changed.
3749
- *
3750
- * Note that the `onChange` callback member of the handler is required.
3751
- *
3752
- * @param handler - Callbacks for handling change events and errors
3753
- * @param options - Options for configuring watch behavior
3754
- * @returns A dispose function to stop watching for changes
3755
- */
3756
- onChangeWithCallback(handler?: WatchOnChangeHandler, options?: SQLOnChangeOptions): () => void;
3757
- /**
3758
- * Create a Stream of changes to any of the specified tables.
3759
- *
3760
- * This is preferred over {@link AbstractPowerSyncDatabase.watchWithAsyncGenerator} when multiple queries need to be
3761
- * performed together when data is changed.
3762
- *
3763
- * @param options - Options for configuring watch behavior
3764
- * @returns An AsyncIterable that yields change events whenever the specified tables change
3765
- */
3766
- onChangeWithAsyncGenerator(options?: SQLWatchOptions): AsyncIterable<WatchOnChangeEvent>;
3767
- private handleTableChanges;
3768
- private processTableUpdates;
3769
- private executeReadOnly;
3770
- }
3771
-
3772
- /**
3773
- * @public
3774
- */
3775
- declare const LogLevel: {
3776
- TRACE: Logger.ILogLevel;
3777
- DEBUG: Logger.ILogLevel;
3778
- INFO: Logger.ILogLevel;
3779
- TIME: Logger.ILogLevel;
3780
- WARN: Logger.ILogLevel;
3781
- ERROR: Logger.ILogLevel;
3782
- OFF: Logger.ILogLevel;
3783
- };
3784
- /**
3785
- * @public
3786
- */
3787
- interface CreateLoggerOptions {
3788
- logLevel?: ILogLevel;
3789
- }
3790
- /**
3791
- * Retrieves the base (default) logger instance.
3792
- *
3793
- * This base logger controls the default logging configuration and is shared
3794
- * across all loggers created with `createLogger`. Adjusting settings on this
3795
- * base logger affects all loggers derived from it unless explicitly overridden.
3796
- *
3797
- * @public
3798
- */
3799
- declare function createBaseLogger(): typeof Logger;
3800
- /**
3801
- * Creates and configures a new named logger based on the base logger.
3802
- *
3803
- * Named loggers allow specific modules or areas of your application to have
3804
- * their own logging levels and behaviors. These loggers inherit configuration
3805
- * from the base logger by default but can override settings independently.
3806
- *
3807
- * @public
3808
- */
3809
- declare function createLogger(name: string, options?: CreateLoggerOptions): ILogger;
3810
-
3811
- /**
3812
- * The default name of the local table storing attachment data.
3813
- *
3814
- * @alpha
3815
- */
3816
- declare const ATTACHMENT_TABLE = "attachments";
3817
- /**
3818
- * AttachmentRecord represents an attachment in the local database.
3819
- *
3820
- * @alpha
3821
- */
3822
- interface AttachmentRecord {
3823
- id: string;
3824
- filename: string;
3825
- localUri?: string;
3826
- size?: number;
3827
- mediaType?: string;
3828
- timestamp?: number;
3829
- metaData?: string;
3830
- hasSynced?: boolean;
3831
- state: AttachmentState;
3832
- }
3833
- /**
3834
- * Maps a database row to an AttachmentRecord.
3835
- *
3836
- * @param row - The database row object
3837
- * @returns The corresponding AttachmentRecord
3838
- *
3839
- * @alpha
3840
- */
3841
- declare function attachmentFromSql(row: any): AttachmentRecord;
3842
- /**
3843
- * AttachmentState represents the current synchronization state of an attachment.
3844
- *
3845
- * @alpha
3846
- */
3847
- declare enum AttachmentState {
3848
- QUEUED_UPLOAD = 0,// Attachment to be uploaded
3849
- QUEUED_DOWNLOAD = 1,// Attachment to be downloaded
3850
- QUEUED_DELETE = 2,// Attachment to be deleted
3851
- SYNCED = 3,// Attachment has been synced
3852
- ARCHIVED = 4
3853
- }
3854
- /**
3855
- * @alpha
3856
- */
3857
- interface AttachmentTableOptions extends Omit<TableV2Options, 'name' | 'columns'> {
3858
- }
3859
- /**
3860
- * @alpha
3861
- */
3862
- declare const ATTACHMENT_TABLE_COLUMNS: {
3863
- filename: BaseColumnType<string | null>;
3864
- local_uri: BaseColumnType<string | null>;
3865
- timestamp: BaseColumnType<number | null>;
3866
- size: BaseColumnType<number | null>;
3867
- media_type: BaseColumnType<string | null>;
3868
- state: BaseColumnType<number | null>;
3869
- has_synced: BaseColumnType<number | null>;
3870
- meta_data: BaseColumnType<string | null>;
3871
- };
3872
- /**
3873
- * AttachmentTable defines the schema for the attachment queue table.
3874
- *
3875
- * @alpha
3876
- */
3877
- declare class AttachmentTable extends Table<typeof ATTACHMENT_TABLE_COLUMNS> {
3878
- constructor(options?: AttachmentTableOptions);
3879
- }
3880
- /**
3881
- * AttachmentTableRecord represents the row type of the attachment table.
3882
- *
3883
- * @alpha
3884
- */
3885
- type AttachmentTableRecord = RowType<AttachmentTable>;
3886
-
3887
- /**
3888
- * AttachmentContext provides database operations for managing attachment records.
3889
- *
3890
- * Provides methods to query, insert, update, and delete attachment records with
3891
- * proper transaction management through PowerSync.
3892
- *
3893
- * @experimental
3894
- * @alpha
3895
- */
3896
- declare class AttachmentContext {
3897
- /** PowerSync database instance for executing queries */
3898
- readonly db: AbstractPowerSyncDatabase;
3899
- /** Name of the database table storing attachment records */
3900
- readonly tableName: string;
3901
- /** Logger instance for diagnostic information */
3902
- readonly logger: ILogger;
3903
- /** Maximum number of archived attachments to keep before cleanup */
3904
- readonly archivedCacheLimit: number;
3905
- /**
3906
- * Creates a new AttachmentContext instance.
3907
- *
3908
- * @param db - PowerSync database instance
3909
- * @param tableName - Name of the table storing attachment records. Default: 'attachments'
3910
- * @param logger - Logger instance for diagnostic output
3911
- */
3912
- constructor(db: AbstractPowerSyncDatabase, tableName: string | undefined, logger: ILogger, archivedCacheLimit: number);
3913
- /**
3914
- * Retrieves all active attachments that require synchronization.
3915
- * Active attachments include those queued for upload, download, or delete.
3916
- * Results are ordered by timestamp in ascending order.
3917
- *
3918
- * @returns Promise resolving to an array of active attachment records
3919
- */
3920
- getActiveAttachments(): Promise<AttachmentRecord[]>;
3921
- /**
3922
- * Retrieves all archived attachments.
3923
- *
3924
- * Archived attachments are no longer referenced but haven't been permanently deleted.
3925
- * These are candidates for cleanup operations to free up storage space.
3926
- *
3927
- * @returns Promise resolving to an array of archived attachment records
3928
- */
3929
- getArchivedAttachments(): Promise<AttachmentRecord[]>;
3930
- /**
3931
- * Retrieves all attachment records regardless of state.
3932
- * Results are ordered by timestamp in ascending order.
3933
- *
3934
- * @returns Promise resolving to an array of all attachment records
3935
- */
3936
- getAttachments(): Promise<AttachmentRecord[]>;
3937
- /**
3938
- * Inserts or updates an attachment record within an existing transaction.
3939
- *
3940
- * Performs an upsert operation (INSERT OR REPLACE). Must be called within
3941
- * an active database transaction context.
3942
- *
3943
- * @param attachment - The attachment record to upsert
3944
- * @param context - Active database transaction context
3945
- */
3946
- upsertAttachment(attachment: AttachmentRecord, context: Transaction): Promise<void>;
3947
- getAttachment(id: string): Promise<AttachmentRecord | undefined>;
3948
- /**
3949
- * Permanently deletes an attachment record from the database.
3950
- *
3951
- * This operation removes the attachment record but does not delete
3952
- * the associated local or remote files. File deletion should be handled
3953
- * separately through the appropriate storage adapters.
3954
- *
3955
- * @param attachmentId - Unique identifier of the attachment to delete
3956
- */
3957
- deleteAttachment(attachmentId: string): Promise<void>;
3958
- clearQueue(): Promise<void>;
3959
- deleteArchivedAttachments(callback?: (attachments: AttachmentRecord[]) => Promise<void>): Promise<boolean>;
3960
- /**
3961
- * Saves multiple attachment records in a single transaction.
3962
- *
3963
- * All updates are saved in a single batch after processing.
3964
- * If the attachments array is empty, no database operations are performed.
3965
- *
3966
- * @param attachments - Array of attachment records to save
3967
- */
3968
- saveAttachments(attachments: AttachmentRecord[]): Promise<void>;
3969
- }
3970
-
3971
- /**
3972
- * SyncErrorHandler provides custom error handling for attachment sync operations.
3973
- * Implementations determine whether failed operations should be retried or archived.
3974
- *
3975
- * @experimental
3976
- * @alpha This is currently experimental and may change without a major version bump.
3977
- */
3978
- interface AttachmentErrorHandler {
3979
- /**
3980
- * Handles a download error for a specific attachment.
3981
- * @param attachment - The attachment that failed to download
3982
- * @param error - The error encountered during the download
3983
- * @returns `true` to retry the operation, `false` to archive the attachment
3984
- */
3985
- onDownloadError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3986
- /**
3987
- * Handles an upload error for a specific attachment.
3988
- * @param attachment - The attachment that failed to upload
3989
- * @param error - The error encountered during the upload
3990
- * @returns `true` to retry the operation, `false` to archive the attachment
3991
- */
3992
- onUploadError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
3993
- /**
3994
- * Handles a delete error for a specific attachment.
3995
- * @param attachment - The attachment that failed to delete
3996
- * @param error - The error encountered during the delete
3997
- * @returns `true` to retry the operation, `false` to archive the attachment
3998
- */
3999
- onDeleteError(attachment: AttachmentRecord, error: unknown): Promise<boolean>;
4000
- }
4001
-
4002
- /**
4003
- * @alpha
4004
- */
4005
- type AttachmentData = ArrayBuffer | string;
4006
- /**
4007
- * @alpha
4008
- */
4009
- declare enum EncodingType {
4010
- UTF8 = "utf8",
4011
- Base64 = "base64"
4012
- }
4013
- /**
4014
- * LocalStorageAdapter defines the interface for local file storage operations.
4015
- * Implementations handle file I/O, directory management, and storage initialization.
4016
- *
4017
- * @experimental
4018
- * @alpha This is currently experimental and may change without a major version bump.
4019
- */
4020
- interface LocalStorageAdapter {
4021
- /**
4022
- * Saves data to a local file.
4023
- * @param filePath - Path where the file will be stored
4024
- * @param data - Data to store (ArrayBuffer, Blob, or string)
4025
- * @returns Number of bytes written
4026
- */
4027
- saveFile(filePath: string, data: AttachmentData): Promise<number>;
4028
- /**
4029
- * Retrieves file data as an ArrayBuffer.
4030
- * @param filePath - Path where the file is stored
4031
- * @returns ArrayBuffer containing the file data
4032
- */
4033
- readFile(filePath: string): Promise<ArrayBuffer>;
4034
- /**
4035
- * Deletes the file at the given path.
4036
- * @param filePath - Path where the file is stored
4037
- */
4038
- deleteFile(filePath: string): Promise<void>;
4039
- /**
4040
- * Checks if a file exists at the given path.
4041
- * @param filePath - Path where the file is stored
4042
- * @returns True if the file exists, false otherwise
4043
- */
4044
- fileExists(filePath: string): Promise<boolean>;
4045
- /**
4046
- * Creates a directory at the specified path.
4047
- * @param path - The full path to the directory
4048
- */
4049
- makeDir(path: string): Promise<void>;
4050
- /**
4051
- * Removes a directory at the specified path.
4052
- * @param path - The full path to the directory
4053
- */
4054
- rmDir(path: string): Promise<void>;
4055
- /**
4056
- * Initializes the storage adapter (e.g., creating necessary directories).
4057
- */
4058
- initialize(): Promise<void>;
4059
- /**
4060
- * Clears all files in the storage.
4061
- */
4062
- clear(): Promise<void>;
4063
- /**
4064
- * Returns the file path for the provided filename in the storage directory.
4065
- * @param filename - The filename to get the path for
4066
- * @returns The full file path
4067
- */
4068
- getLocalUri(filename: string): string;
4069
- }
4070
-
4071
- /**
4072
- * RemoteStorageAdapter defines the interface for remote storage operations.
4073
- * Implementations handle uploading, downloading, and deleting files from remote storage.
4074
- *
4075
- * @experimental
4076
- * @alpha This is currently experimental and may change without a major version bump.
4077
- */
4078
- interface RemoteStorageAdapter {
4079
- /**
4080
- * Uploads a file to remote storage.
4081
- * @param fileData - The binary content of the file to upload
4082
- * @param attachment - The associated attachment metadata
4083
- */
4084
- uploadFile(fileData: ArrayBuffer, attachment: AttachmentRecord): Promise<void>;
4085
- /**
4086
- * Downloads a file from remote storage.
4087
- * @param attachment - The attachment describing the file to download
4088
- * @returns The binary data of the downloaded file
4089
- */
4090
- downloadFile(attachment: AttachmentRecord): Promise<ArrayBuffer>;
4091
- /**
4092
- * Deletes a file from remote storage.
4093
- * @param attachment - The attachment describing the file to delete
4094
- */
4095
- deleteFile(attachment: AttachmentRecord): Promise<void>;
4096
- }
4097
-
4098
- /**
4099
- * WatchedAttachmentItem represents an attachment reference in your application's data model.
4100
- * Use either filename OR fileExtension (not both).
4101
- *
4102
- * @alpha
4103
- */
4104
- type WatchedAttachmentItem = {
4105
- id: string;
4106
- filename: string;
4107
- fileExtension?: never;
4108
- metaData?: string;
4109
- mediaType?: string;
4110
- } | {
4111
- id: string;
4112
- fileExtension: string;
4113
- filename?: never;
4114
- metaData?: string;
4115
- mediaType?: string;
4116
- };
4117
-
4118
- /**
4119
- * Configuration options for {@link AttachmentQueue}.
4120
- *
4121
- * @experimental
4122
- * @alpha This is currently experimental and may change without a major version bump.
4123
- */
4124
- interface AttachmentQueueOptions {
4125
- /**
4126
- * PowerSync database instance
4127
- */
4128
- db: AbstractPowerSyncDatabase;
4129
- /**
4130
- * Remote storage adapter for upload/download operations
4131
- */
4132
- remoteStorage: RemoteStorageAdapter;
4133
- /**
4134
- * Local storage adapter for file persistence
4135
- */
4136
- localStorage: LocalStorageAdapter;
4137
- /**
4138
- * Callback for monitoring attachment changes in your data model
4139
- */
4140
- watchAttachments: (onUpdate: (attachment: WatchedAttachmentItem[]) => Promise<void>, signal: AbortSignal) => void;
4141
- /**
4142
- * Name of the table to store attachment records. Default: 'ps_attachment_queue'
4143
- */
4144
- tableName?: string;
4145
- /**
4146
- * Logger instance. Defaults to db.logger
4147
- */
4148
- logger?: ILogger;
4149
- /**
4150
- * Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
4151
- */
4152
- syncIntervalMs?: number;
4153
- /**
4154
- * Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30
4155
- */
4156
- syncThrottleDuration?: number;
4157
- /**
4158
- * Whether to automatically download remote attachments. Default: true
4159
- */
4160
- downloadAttachments?: boolean;
4161
- /**
4162
- * Maximum archived attachments before cleanup. Default: 100
4163
- */
4164
- archivedCacheLimit?: number;
4165
- /** Handler for upload, download and delete errors */
4166
- errorHandler?: AttachmentErrorHandler;
4167
- }
4168
- /**
4169
- * AttachmentQueue manages the lifecycle and synchronization of attachments
4170
- * between local and remote storage.
4171
- * Provides automatic synchronization, upload/download queuing, attachment monitoring,
4172
- * verification and repair of local files, and cleanup of archived attachments.
4173
- *
4174
- * @experimental
4175
- * @alpha This is currently experimental and may change without a major version bump.
4176
- */
4177
- declare class AttachmentQueue {
4178
- /** Timer for periodic synchronization operations */
4179
- private periodicSyncTimer?;
4180
- /** Service for synchronizing attachments between local and remote storage */
4181
- private readonly syncingService;
4182
- /** Adapter for local file storage operations */
4183
- readonly localStorage: LocalStorageAdapter;
4184
- /** Adapter for remote file storage operations */
4185
- readonly remoteStorage: RemoteStorageAdapter;
4186
- /**
4187
- * Callback function to watch for changes in attachment references in your data model.
4188
- *
4189
- * This should be implemented by the user of AttachmentQueue to monitor changes in your application's
4190
- * data that reference attachments. When attachments are added, removed, or modified,
4191
- * this callback should trigger the onUpdate function with the current set of attachments.
4192
- */
4193
- private readonly watchAttachments;
4194
- /** Name of the database table storing attachment records */
4195
- readonly tableName: string;
4196
- /** Logger instance for diagnostic information */
4197
- readonly logger: ILogger;
4198
- /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
4199
- * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
4200
- readonly syncIntervalMs: number;
4201
- /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
4202
- * When attachment records change, a watch query detects the change and triggers a sync.
4203
- * This throttle prevents the sync from firing too rapidly when many changes happen in
4204
- * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
4205
- * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
4206
- * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
4207
- readonly syncThrottleDuration: number;
4208
- /** Whether to automatically download remote attachments. Default: true */
4209
- readonly downloadAttachments: boolean;
4210
- /** Maximum number of archived attachments to keep before cleanup. Default: 100 */
4211
- readonly archivedCacheLimit: number;
4212
- /** Service for managing attachment-related database operations */
4213
- private readonly attachmentService;
4214
- /** PowerSync database instance */
4215
- private readonly db;
4216
- /** Cleanup function for status change listener */
4217
- private statusListenerDispose?;
4218
- private watchActiveAttachments;
4219
- private watchAttachmentsAbortController;
4220
- /**
4221
- * Serializes concurrent `syncStorage()` triggers (periodic timer, watch-onDiff,
4222
- * status-changed). Held across the whole batch, but only contended by other
4223
- * sync triggers — foreground `saveFile` / `deleteFile` / watched-attachment
4224
- * processing don't take this lock and proceed in parallel via the
4225
- * `AttachmentService` mutex, which is acquired only briefly per row.
4226
- */
4227
- private syncLoopMutex;
4228
- /**
4229
- * Aborted by `stopSync()` to interrupt an in-flight batch within one
4230
- * attachment's processing time. Polled between rows by `SyncingService`.
4231
- */
4232
- private syncAbortController?;
4233
- /**
4234
- * Creates a new AttachmentQueue instance.
4235
- *
4236
- * @param options - Configuration options
4237
- */
4238
- constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName, syncIntervalMs, syncThrottleDuration, downloadAttachments, archivedCacheLimit, errorHandler }: AttachmentQueueOptions);
4239
- /**
4240
- * Generates a new attachment ID using a SQLite UUID function.
4241
- *
4242
- * @returns Promise resolving to the new attachment ID
4243
- */
4244
- generateAttachmentId(): Promise<string>;
4245
- /**
4246
- * Starts the attachment synchronization process.
4247
- *
4248
- * This method:
4249
- * - Stops any existing sync operations
4250
- * - Sets up periodic synchronization based on syncIntervalMs
4251
- * - Registers listeners for active attachment changes
4252
- * - Processes watched attachments to queue uploads/downloads
4253
- * - Handles state transitions for archived and new attachments
4254
- */
4255
- startSync(): Promise<void>;
4256
- /**
4257
- * Synchronizes all active attachments between local and remote storage.
4258
- *
4259
- * This is called automatically at regular intervals when sync is started,
4260
- * but can also be called manually to trigger an immediate sync.
4261
- *
4262
- * Concurrent invocations are serialized via `syncLoopMutex`.
4263
- */
4264
- syncStorage(): Promise<void>;
4265
- /**
4266
- * Stops the attachment synchronization process.
4267
- *
4268
- * Clears the periodic sync timer, closes all active attachment watchers, and
4269
- * aborts any in-flight `syncStorage()` call so it exits within one
4270
- * attachment's processing time instead of running the batch to completion.
4271
- */
4272
- stopSync(): Promise<void>;
4273
- /**
4274
- * Provides an {@link AttachmentContext} to a callback.
4275
- *
4276
- * The callback runs while the attachment queue mutex is held. Do not call
4277
- * other {@link AttachmentQueue} methods from within the callback, as they may
4278
- * attempt to acquire the same mutex and block indefinitely.
4279
- */
4280
- withAttachmentContext<T>(callback: (context: AttachmentContext) => Promise<T>): Promise<T>;
4281
- /**
4282
- * Saves a file to local storage and queues it for upload to remote storage.
4283
- *
4284
- * @param options - File save options
4285
- * @returns Promise resolving to the created attachment record
4286
- */
4287
- saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }: {
4288
- /**
4289
- * The file data as ArrayBuffer, Blob, or base64 string
4290
- */
4291
- data: AttachmentData;
4292
- /**
4293
- * File extension (e.g., 'jpg', 'pdf')
4294
- */
4295
- fileExtension: string;
4296
- /**
4297
- * MIME type of the file (e.g., 'image/jpeg')
4298
- */
4299
- mediaType?: string;
4300
- /**
4301
- * Optional metadata to associate with the attachment
4302
- */
4303
- metaData?: string;
4304
- /**
4305
- * Optional custom ID. If not provided, a UUID will be generated
4306
- */
4307
- id?: string;
4308
- /**
4309
- * Optional callback to execute additional database operations within the same transaction as the attachment
4310
- * creation.
4311
- */
4312
- updateHook?: (transaction: Transaction, attachment: AttachmentRecord) => Promise<void>;
4313
- }): Promise<AttachmentRecord>;
4314
- deleteFile({ id, updateHook }: {
4315
- id: string;
4316
- updateHook?: (transaction: Transaction, attachment: AttachmentRecord) => Promise<void>;
4317
- }): Promise<void>;
4318
- expireCache(): Promise<void>;
4319
- clearQueue(): Promise<void>;
4320
- /**
4321
- * Verifies the integrity of all attachment records and repairs inconsistencies.
4322
- *
4323
- * This method checks each attachment record against the local filesystem and:
4324
- * - Updates localUri if the file exists at a different path
4325
- * - Archives attachments with missing local files that haven't been uploaded
4326
- * - Requeues synced attachments for download if their local files are missing
4327
- */
4328
- verifyAttachments(): Promise<void>;
4329
- }
4330
-
4331
- /**
4332
- * Service for querying and watching attachment records in the database.
4333
- *
4334
- * @internal
4335
- */
4336
- declare class AttachmentService {
4337
- private db;
4338
- private logger;
4339
- private tableName;
4340
- private mutex;
4341
- private context;
4342
- constructor(db: AbstractPowerSyncDatabase, logger: ILogger, tableName?: string, archivedCacheLimit?: number);
4343
- /**
4344
- * Creates a differential watch query for active attachments requiring synchronization.
4345
- * @returns Watch query that emits changes for queued uploads, downloads, and deletes
4346
- */
4347
- watchActiveAttachments({ throttleMs }?: {
4348
- throttleMs?: number;
4349
- }): DifferentialWatchedQuery<AttachmentRecord>;
4350
- /**
4351
- * Executes a callback with exclusive access to the attachment context.
4352
- */
4353
- withContext<T>(callback: (context: AttachmentContext) => Promise<T>): Promise<T>;
4354
- }
4355
-
4356
- /**
4357
- * Orchestrates attachment synchronization between local and remote storage.
4358
- * Handles uploads, downloads, deletions, and state transitions.
4359
- *
4360
- * @internal
4361
- */
4362
- declare class SyncingService {
4363
- private attachmentService;
4364
- private localStorage;
4365
- private remoteStorage;
4366
- private logger;
4367
- private errorHandler?;
4368
- constructor(attachmentService: AttachmentService, localStorage: LocalStorageAdapter, remoteStorage: RemoteStorageAdapter, logger: ILogger, errorHandler?: AttachmentErrorHandler);
4369
- /**
4370
- * Processes attachments based on their state (upload, download, or delete).
4371
- *
4372
- * Each attachment's I/O runs outside the attachment-service mutex, and the row's
4373
- * state transition is persisted immediately after it completes. This keeps the
4374
- * mutex available to concurrent `saveFile` / `deleteFile` / watched-attachment
4375
- * processing while a batch is in flight, and means consumer queries against the
4376
- * attachments queue see incremental progress instead of one atomic commit at the
4377
- * end of the batch.
4378
- *
4379
- * @param attachments - Array of attachment records to process
4380
- * @param options - Optional controls. Pass `signal` (an `AbortSignal`) to interrupt
4381
- * the batch: it is checked between attachments and, once aborted, the
4382
- * loop exits early — letting `stopSync` stop a running batch within
4383
- * one attachment's processing time.
4384
- */
4385
- processAttachments(attachments: AttachmentRecord[], options?: {
4386
- signal?: AbortSignal;
4387
- }): Promise<void>;
4388
- /**
4389
- * Uploads an attachment from local storage to remote storage.
4390
- * On success, marks as SYNCED. On failure, defers to error handler or archives.
4391
- *
4392
- * @param attachment - The attachment record to upload
4393
- * @returns Updated attachment record with new state
4394
- * @throws Error if the attachment has no localUri
4395
- */
4396
- uploadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4397
- /**
4398
- * Downloads an attachment from remote storage to local storage.
4399
- * Retrieves the file, converts to base64, and saves locally.
4400
- * On success, marks as SYNCED. On failure, defers to error handler or archives.
4401
- *
4402
- * @param attachment - The attachment record to download
4403
- * @returns Updated attachment record with local URI and new state
4404
- */
4405
- downloadAttachment(attachment: AttachmentRecord): Promise<AttachmentRecord>;
4406
- /**
4407
- * Deletes an attachment from both remote and local storage.
4408
- * Removes the remote file, local file (if exists), and the attachment record.
4409
- * On failure, defers to error handler or archives.
4410
- *
4411
- * @param attachment - The attachment record to delete
4412
- * @param context - Attachment context for database operations
4413
- * @returns Updated attachment record
4414
- */
4415
- deleteAttachment(attachment: AttachmentRecord, context: AttachmentContext): Promise<AttachmentRecord>;
4416
- /**
4417
- * Performs cleanup of archived attachments by removing their local files and records.
4418
- * Errors during local file deletion are logged but do not prevent record deletion.
4419
- */
4420
- deleteArchivedAttachments(context: AttachmentContext): Promise<boolean>;
4421
- }
4422
-
4423
- /**
4424
- * @internal
4425
- */
4426
- interface PowerSyncOpenFactoryOptions extends Partial<PowerSyncDatabaseOptions>, SQLOpenOptions {
4427
- /** Schema used for the local database. */
4428
- schema: Schema;
4429
- }
4430
- /**
4431
- * @internal
4432
- */
4433
- declare abstract class AbstractPowerSyncDatabaseOpenFactory {
4434
- protected options: PowerSyncOpenFactoryOptions;
4435
- constructor(options: PowerSyncOpenFactoryOptions);
4436
- /**
4437
- * Schema used for the local database.
4438
- */
4439
- get schema(): Schema<{
4440
- [x: string]: Table<any>;
4441
- }>;
4442
- protected abstract openDB(): DBAdapter;
4443
- generateOptions(): PowerSyncDatabaseOptions;
4444
- abstract generateInstance(options: PowerSyncDatabaseOptions): AbstractPowerSyncDatabase;
4445
- getInstance(): AbstractPowerSyncDatabase;
4446
- }
4447
-
4448
- /**
4449
- * @public
4450
- */
4451
- interface CompilableQueryWatchHandler<T> {
4452
- onResult: (results: T[]) => void;
4453
- onError?: (error: Error) => void;
4454
- }
4455
- /**
4456
- * @public
4457
- */
4458
- declare function compilableQueryWatch<T>(db: AbstractPowerSyncDatabase, query: CompilableQuery<T>, handler: CompilableQueryWatchHandler<T>, options?: SQLWatchOptions): void;
4459
-
4460
- /**
4461
- * @internal
4462
- */
4463
- declare const MAX_OP_ID = "9223372036854775807";
4464
-
4465
- /**
4466
- * @internal
4467
- */
4468
- declare function runOnSchemaChange(callback: (signal: AbortSignal) => void, db: AbstractPowerSyncDatabase, options?: SQLWatchOptions): void;
4469
-
4470
- /**
4471
- * @internal
4472
- */
4473
- declare class SqliteBucketStorage extends BaseObserver<BucketStorageListener> implements BucketStorageAdapter {
4474
- private db;
4475
- private logger;
4476
- tableNames: Set<string>;
4477
- private updateListener;
4478
- private _clientId?;
4479
- constructor(db: DBAdapter, logger?: ILogger);
4480
- init(): Promise<void>;
4481
- dispose(): Promise<void>;
4482
- _getClientId(): Promise<string>;
4483
- getClientId(): Promise<string>;
4484
- getMaxOpId(): string;
4485
- updateLocalTarget(cb: () => Promise<string>): Promise<boolean>;
4486
- nextCrudItem(): Promise<CrudEntry | undefined>;
4487
- hasCrud(): Promise<boolean>;
4488
- /**
4489
- * Get a batch of objects to send to the server.
4490
- * When the objects are successfully sent to the server, call .complete()
4491
- */
4492
- getCrudBatch(limit?: number): Promise<CrudBatch | null>;
4493
- writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, options?: {
4494
- timeoutMs: number;
4495
- }): Promise<T>;
4496
- control(op: PowerSyncControlCommand, payload: string | Uint8Array | ArrayBuffer | null): Promise<string>;
4497
- hasMigratedSubkeys(): Promise<boolean>;
4498
- migrateToFixedSubkeys(): Promise<void>;
4499
- static _subkeyMigrationKey: string;
4500
- }
4501
-
4502
- /**
4503
- * Thrown when an underlying database connection is closed.
4504
- * This is particularly relevant when worker connections are marked as closed while
4505
- * operations are still in progress.
4506
- *
4507
- * @internal
4508
- */
4509
- declare class ConnectionClosedError extends Error {
4510
- static NAME: string;
4511
- static MATCHES(input: any): boolean;
4512
- constructor(message: string);
4513
- }
4514
-
4515
- /**
4516
- * @internal
4517
- * @experimental
4518
- */
4519
- declare const MEMORY_TRIGGER_CLAIM_MANAGER: TriggerClaimManager;
4520
-
4521
- /**
4522
- * Helper function for sanitizing UUID input strings.
4523
- * Typically used with {@link sanitizeSQL}.
4524
- *
4525
- * @alpha
4526
- */
4527
- declare function sanitizeUUID(uuid: string): string;
4528
- /**
4529
- * SQL string template function for {@link TrackDiffOptions#when} and {@link CreateDiffTriggerOptions#when}.
4530
- *
4531
- * This function performs basic string interpolation for SQLite WHEN clauses.
4532
- *
4533
- * **String placeholders:**
4534
- * - All string values passed as placeholders are automatically wrapped in single quotes (`'`).
4535
- * - Do not manually wrap placeholders in single quotes in your template string; the function will handle quoting and escaping for you.
4536
- * - Any single quotes within the string value are escaped by doubling them (`''`), as required by SQL syntax.
4537
- *
4538
- * **Other types:**
4539
- * - `null` and `undefined` are converted to SQL `NULL`.
4540
- * - Objects are stringified using `JSON.stringify()` and wrapped in single quotes, with any single quotes inside the stringified value escaped.
4541
- * - Numbers and other primitive types are inserted directly.
4542
- *
4543
- * **Usage example:**
4544
- * ```typescript
4545
- * const myID = "O'Reilly";
4546
- * const clause = sanitizeSQL`New.id = ${myID}`;
4547
- * // Result: "New.id = 'O''Reilly'"
4548
- * ```
4549
- *
4550
- * Avoid manually quoting placeholders:
4551
- * ```typescript
4552
- * // Incorrect:
4553
- * sanitizeSQL`New.id = '${myID}'` // Produces double quotes: New.id = ''O''Reilly''
4554
- * ```
4555
- *
4556
- * @alpha
4557
- */
4558
- declare function sanitizeSQL(strings: TemplateStringsArray, ...values: any[]): string;
4559
-
4560
- /**
4561
- * Options for {@link GetAllQuery}.
4562
- *
4563
- * @public
4564
- */
4565
- type GetAllQueryOptions<RowType = unknown> = {
4566
- sql: string;
4567
- parameters?: ReadonlyArray<unknown>;
4568
- /**
4569
- * Optional mapper function to convert raw rows into the desired RowType.
4570
- * @example
4571
- * ```javascript
4572
- * (rawRow) => ({
4573
- * id: rawRow.id,
4574
- * created_at: new Date(rawRow.created_at),
4575
- * })
4576
- * ```
4577
- */
4578
- mapper?: (rawRow: Record<string, unknown>) => RowType;
4579
- };
4580
- /**
4581
- * Performs a {@link AbstractPowerSyncDatabase.getAll} operation for a watched query.
4582
- *
4583
- * @public
4584
- */
4585
- declare class GetAllQuery<RowType = unknown> implements WatchCompatibleQuery<RowType[]> {
4586
- protected options: GetAllQueryOptions<RowType>;
4587
- constructor(options: GetAllQueryOptions<RowType>);
4588
- compile(): CompiledQuery;
4589
- execute(options: {
4590
- db: AbstractPowerSyncDatabase;
4591
- }): Promise<RowType[]>;
4592
- }
4593
-
4594
- /**
4595
- * Calls to Abortcontroller.abort(reason: any) will result in the
4596
- * `reason` being thrown. This is not necessarily an error,
4597
- * but extends error for better logging purposes.
4598
- *
4599
- * @internal
4600
- */
4601
- declare class AbortOperation extends Error {
4602
- protected reason: string;
4603
- constructor(reason: string);
4604
- }
4605
-
4606
- /**
4607
- * @internal
4608
- */
4609
- interface ControlledExecutorOptions {
4610
- /**
4611
- * If throttling is enabled, it ensures only one task runs at a time,
4612
- * and only one additional task can be scheduled to run after the current task completes. The pending task will be overwritten by the latest task.
4613
- * Enabled by default.
4614
- */
4615
- throttleEnabled?: boolean;
4616
- }
4617
- /**
4618
- * @internal
4619
- */
4620
- declare class ControlledExecutor<T> {
4621
- private task;
4622
- /**
4623
- * Represents the currently running task, which could be a Promise or undefined if no task is running.
4624
- */
4625
- private runningTask;
4626
- private pendingTaskParam;
4627
- /**
4628
- * Flag to determine if throttling is enabled, which controls whether tasks are queued or run immediately.
4629
- */
4630
- private isThrottling;
4631
- private closed;
4632
- constructor(task: (param: T) => Promise<void> | void, options?: ControlledExecutorOptions);
4633
- schedule(param: T): void;
4634
- dispose(): void;
4635
- private execute;
4636
- }
4637
-
4638
- /**
4639
- * @internal
4640
- */
4641
- interface ParsedQuery {
4642
- sqlStatement: string;
4643
- parameters: any[];
4644
- }
4645
- /**
4646
- * @internal
4647
- */
4648
- declare const parseQuery: <T>(query: string | CompilableQuery<T>, parameters: any[]) => ParsedQuery;
4649
-
4650
- export { ATTACHMENT_TABLE, ATTACHMENT_TABLE_COLUMNS, AbortOperation, AbstractPowerSyncDatabase, AbstractPowerSyncDatabaseOpenFactory, AbstractQueryProcessor, AbstractRemote, AbstractStreamingSyncImplementation, ArrayComparator, AttachmentContext, AttachmentQueue, AttachmentService, AttachmentState, AttachmentTable, BaseObserver, Column, ColumnType, ConnectionClosedError, ConnectionManager, ControlledExecutor, CrudBatch, CrudEntry, CrudTransaction, DBAdapterDefaultMixin, DBGetUtilsDefaultMixin, DEFAULT_CRUD_BATCH_LIMIT, DEFAULT_CRUD_UPLOAD_THROTTLE_MS, DEFAULT_INDEX_COLUMN_OPTIONS, DEFAULT_INDEX_OPTIONS, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_POWERSYNC_CLOSE_OPTIONS, DEFAULT_POWERSYNC_DB_OPTIONS, DEFAULT_REMOTE_LOGGER, DEFAULT_REMOTE_OPTIONS, DEFAULT_RETRY_DELAY_MS, DEFAULT_ROW_COMPARATOR, DEFAULT_STREAMING_SYNC_OPTIONS, DEFAULT_STREAM_CONNECTION_OPTIONS, DEFAULT_SYNC_CLIENT_IMPLEMENTATION, DEFAULT_TABLE_OPTIONS, DEFAULT_WATCH_QUERY_OPTIONS, DEFAULT_WATCH_THROTTLE_MS, DiffTriggerOperation, DifferentialQueryProcessor, EMPTY_DIFFERENTIAL, EncodingType, FalsyComparator, FetchImplementationProvider, FetchStrategy, GetAllQuery, Index, IndexedColumn, InvalidSQLCharacters, LockType, LogLevel, MAX_AMOUNT_OF_COLUMNS, MAX_OP_ID, MEMORY_TRIGGER_CLAIM_MANAGER, Mutex, OnChangeQueryProcessor, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, Semaphore, SqliteBucketStorage, SyncClientImplementation, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID, timeoutSignal };
4651
- export type { AbstractQueryProcessorOptions, AbstractRemoteOptions, AbstractStreamingSyncImplementationOptions, AdditionalConnectionOptions, ArrayComparatorOptions, ArrayQueryDefinition, AttachmentData, AttachmentErrorHandler, AttachmentQueueOptions, AttachmentRecord, AttachmentTableOptions, AttachmentTableRecord, BaseColumnType, BaseConnectionOptions, BaseListener, BaseObserverInterface, BasePowerSyncDatabaseOptions, BaseTriggerDiffRecord, BatchedUpdateNotification, BucketStorageAdapter, BucketStorageListener, ColumnOptions, ColumnsType, CompilableQuery, CompilableQueryWatchHandler, CompiledQuery, ConnectionManagerListener, ConnectionManagerOptions, ConnectionManagerSyncImplementationResult, ConnectionPool, ControlledExecutorOptions, CreateDiffTriggerOptions, CreateLoggerOptions, CreateSyncImplementationOptions, DBAdapter, DBAdapterListener, DBGetUtils, DBLockOptions, DifferentialQueryProcessorOptions, DifferentialWatchedQuery, DifferentialWatchedQueryComparator, DifferentialWatchedQueryListener, DifferentialWatchedQueryOptions, DifferentialWatchedQuerySettings, DisconnectAndClearOptions, Disposable, ExtractColumnValueType, ExtractedTriggerDiffRecord, FetchImplementation, GetAllQueryOptions, IndexColumnOptions, IndexOptions, IndexShorthand, InternalConnectionOptions, InternalSubscriptionAdapter, LinkQueryOptions, LocalStorageAdapter, LockContext, LockOptions, MutableWatchedQueryState, OnChangeQueryProcessorOptions, OpId, ParsedQuery, PendingStatement, PendingStatementParameter, PowerSyncBackendConnector, PowerSyncCloseOptions, PowerSyncConnectionOptions, PowerSyncCredentials, PowerSyncDBListener, PowerSyncDatabaseOptions, PowerSyncDatabaseOptionsWithDBAdapter, PowerSyncDatabaseOptionsWithOpenFactory, PowerSyncDatabaseOptionsWithSettings, PowerSyncOpenFactoryOptions, ProgressWithOperations, Query, QueryParam, QueryResult, RawTableType, RemoteConnector, RemoteStorageAdapter, RequiredAdditionalConnectionOptions, RequiredPowerSyncConnectionOptions, RowType, SQLOnChangeOptions, SQLOpenFactory, SQLOpenOptions, SQLWatchOptions, SchemaTableType, SimpleAsyncIterator, SocketSyncStreamOptions, SqlExecutor, StandardWatchedQuery, StandardWatchedQueryOptions, StreamingSyncImplementation, StreamingSyncImplementationListener, StreamingSyncRequestParameterType, SubscribedStream, SyncDataFlowStatus, SyncPriorityStatus, SyncStatusOptions, SyncStream, SyncStreamDescription, SyncStreamOptions, SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription, SyncSubscriptionDescription, TableOptions, TableOrRawTableOptions, TableUpdateOperation, TableV2Options, TrackDiffOptions, TrackPreviousOptions, Transaction, TriggerClaimManager, TriggerCreationHooks, TriggerDiffDeleteRecord, TriggerDiffHandlerContext, TriggerDiffInsertRecord, TriggerDiffRecord, TriggerDiffUpdateRecord, TriggerManager, TriggerManagerConfig, TriggerRemoveCallback, TriggerRemoveCallbackOptions, UnlockFn, UpdateNotification, WatchCompatibleQuery, WatchExecuteOptions, WatchHandler, WatchOnChangeEvent, WatchOnChangeHandler, WatchedAttachmentItem, WatchedQuery, WatchedQueryComparator, WatchedQueryDifferential, WatchedQueryListener, WatchedQueryOptions, WatchedQueryRowDifferential, WatchedQuerySettings, WatchedQueryState, WithDiffOptions };