@powersync/common 1.46.0 → 1.48.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 (71) hide show
  1. package/README.md +5 -1
  2. package/dist/bundle.cjs +1298 -395
  3. package/dist/bundle.cjs.map +1 -1
  4. package/dist/bundle.mjs +1291 -395
  5. package/dist/bundle.mjs.map +1 -1
  6. package/dist/bundle.node.cjs +1298 -395
  7. package/dist/bundle.node.cjs.map +1 -1
  8. package/dist/bundle.node.mjs +1291 -395
  9. package/dist/bundle.node.mjs.map +1 -1
  10. package/dist/index.d.cts +652 -106
  11. package/lib/attachments/AttachmentContext.d.ts +86 -0
  12. package/lib/attachments/AttachmentContext.js +229 -0
  13. package/lib/attachments/AttachmentContext.js.map +1 -0
  14. package/lib/attachments/AttachmentErrorHandler.d.ts +31 -0
  15. package/lib/attachments/AttachmentErrorHandler.js +2 -0
  16. package/lib/attachments/AttachmentErrorHandler.js.map +1 -0
  17. package/lib/attachments/AttachmentQueue.d.ts +149 -0
  18. package/lib/attachments/AttachmentQueue.js +362 -0
  19. package/lib/attachments/AttachmentQueue.js.map +1 -0
  20. package/lib/attachments/AttachmentService.d.ts +29 -0
  21. package/lib/attachments/AttachmentService.js +56 -0
  22. package/lib/attachments/AttachmentService.js.map +1 -0
  23. package/lib/attachments/LocalStorageAdapter.d.ts +62 -0
  24. package/lib/attachments/LocalStorageAdapter.js +6 -0
  25. package/lib/attachments/LocalStorageAdapter.js.map +1 -0
  26. package/lib/attachments/RemoteStorageAdapter.d.ts +27 -0
  27. package/lib/attachments/RemoteStorageAdapter.js +2 -0
  28. package/lib/attachments/RemoteStorageAdapter.js.map +1 -0
  29. package/lib/attachments/Schema.d.ts +50 -0
  30. package/lib/attachments/Schema.js +62 -0
  31. package/lib/attachments/Schema.js.map +1 -0
  32. package/lib/attachments/SyncingService.d.ts +62 -0
  33. package/lib/attachments/SyncingService.js +168 -0
  34. package/lib/attachments/SyncingService.js.map +1 -0
  35. package/lib/attachments/WatchedAttachmentItem.d.ts +17 -0
  36. package/lib/attachments/WatchedAttachmentItem.js +2 -0
  37. package/lib/attachments/WatchedAttachmentItem.js.map +1 -0
  38. package/lib/db/schema/RawTable.d.ts +61 -26
  39. package/lib/db/schema/RawTable.js +1 -32
  40. package/lib/db/schema/RawTable.js.map +1 -1
  41. package/lib/db/schema/Schema.d.ts +14 -7
  42. package/lib/db/schema/Schema.js +25 -3
  43. package/lib/db/schema/Schema.js.map +1 -1
  44. package/lib/db/schema/Table.d.ts +13 -8
  45. package/lib/db/schema/Table.js +3 -8
  46. package/lib/db/schema/Table.js.map +1 -1
  47. package/lib/db/schema/internal.d.ts +12 -0
  48. package/lib/db/schema/internal.js +15 -0
  49. package/lib/db/schema/internal.js.map +1 -0
  50. package/lib/index.d.ts +11 -1
  51. package/lib/index.js +10 -1
  52. package/lib/index.js.map +1 -1
  53. package/lib/utils/mutex.d.ts +1 -1
  54. package/lib/utils/mutex.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/attachments/AttachmentContext.ts +279 -0
  57. package/src/attachments/AttachmentErrorHandler.ts +34 -0
  58. package/src/attachments/AttachmentQueue.ts +472 -0
  59. package/src/attachments/AttachmentService.ts +62 -0
  60. package/src/attachments/LocalStorageAdapter.ts +72 -0
  61. package/src/attachments/README.md +718 -0
  62. package/src/attachments/RemoteStorageAdapter.ts +30 -0
  63. package/src/attachments/Schema.ts +87 -0
  64. package/src/attachments/SyncingService.ts +193 -0
  65. package/src/attachments/WatchedAttachmentItem.ts +19 -0
  66. package/src/db/schema/RawTable.ts +66 -31
  67. package/src/db/schema/Schema.ts +27 -2
  68. package/src/db/schema/Table.ts +11 -11
  69. package/src/db/schema/internal.ts +17 -0
  70. package/src/index.ts +12 -1
  71. package/src/utils/mutex.ts +1 -1
@@ -4,6 +4,1233 @@ var asyncMutex = require('async-mutex');
4
4
  var eventIterator = require('event-iterator');
5
5
  var node_buffer = require('node:buffer');
6
6
 
7
+ // https://www.sqlite.org/lang_expr.html#castexpr
8
+ exports.ColumnType = void 0;
9
+ (function (ColumnType) {
10
+ ColumnType["TEXT"] = "TEXT";
11
+ ColumnType["INTEGER"] = "INTEGER";
12
+ ColumnType["REAL"] = "REAL";
13
+ })(exports.ColumnType || (exports.ColumnType = {}));
14
+ const text = {
15
+ type: exports.ColumnType.TEXT
16
+ };
17
+ const integer = {
18
+ type: exports.ColumnType.INTEGER
19
+ };
20
+ const real = {
21
+ type: exports.ColumnType.REAL
22
+ };
23
+ // powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
24
+ // In earlier versions this was limited to 63.
25
+ const MAX_AMOUNT_OF_COLUMNS = 1999;
26
+ const column = {
27
+ text,
28
+ integer,
29
+ real
30
+ };
31
+ class Column {
32
+ options;
33
+ constructor(options) {
34
+ this.options = options;
35
+ }
36
+ get name() {
37
+ return this.options.name;
38
+ }
39
+ get type() {
40
+ return this.options.type;
41
+ }
42
+ toJSON() {
43
+ return {
44
+ name: this.name,
45
+ type: this.type
46
+ };
47
+ }
48
+ }
49
+
50
+ const DEFAULT_INDEX_COLUMN_OPTIONS = {
51
+ ascending: true
52
+ };
53
+ class IndexedColumn {
54
+ options;
55
+ static createAscending(column) {
56
+ return new IndexedColumn({
57
+ name: column,
58
+ ascending: true
59
+ });
60
+ }
61
+ constructor(options) {
62
+ this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
63
+ }
64
+ get name() {
65
+ return this.options.name;
66
+ }
67
+ get ascending() {
68
+ return this.options.ascending;
69
+ }
70
+ toJSON(table) {
71
+ return {
72
+ name: this.name,
73
+ ascending: this.ascending,
74
+ type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
75
+ };
76
+ }
77
+ }
78
+
79
+ const DEFAULT_INDEX_OPTIONS = {
80
+ columns: []
81
+ };
82
+ class Index {
83
+ options;
84
+ static createAscending(options, columnNames) {
85
+ return new Index({
86
+ ...options,
87
+ columns: columnNames.map((name) => IndexedColumn.createAscending(name))
88
+ });
89
+ }
90
+ constructor(options) {
91
+ this.options = options;
92
+ this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
93
+ }
94
+ get name() {
95
+ return this.options.name;
96
+ }
97
+ get columns() {
98
+ return this.options.columns ?? [];
99
+ }
100
+ toJSON(table) {
101
+ return {
102
+ name: this.name,
103
+ columns: this.columns.map((c) => c.toJSON(table))
104
+ };
105
+ }
106
+ }
107
+
108
+ /**
109
+ * @internal Not exported from `index.ts`.
110
+ */
111
+ function encodeTableOptions(options) {
112
+ const trackPrevious = options.trackPrevious;
113
+ return {
114
+ local_only: options.localOnly,
115
+ insert_only: options.insertOnly,
116
+ include_old: trackPrevious && (trackPrevious.columns ?? true),
117
+ include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
118
+ include_metadata: options.trackMetadata,
119
+ ignore_empty_update: options.ignoreEmptyUpdates
120
+ };
121
+ }
122
+
123
+ const DEFAULT_TABLE_OPTIONS = {
124
+ indexes: [],
125
+ insertOnly: false,
126
+ localOnly: false,
127
+ trackPrevious: false,
128
+ trackMetadata: false,
129
+ ignoreEmptyUpdates: false
130
+ };
131
+ const InvalidSQLCharacters = /["'%,.#\s[\]]/;
132
+ class Table {
133
+ options;
134
+ _mappedColumns;
135
+ static createLocalOnly(options) {
136
+ return new Table({ ...options, localOnly: true, insertOnly: false });
137
+ }
138
+ static createInsertOnly(options) {
139
+ return new Table({ ...options, localOnly: false, insertOnly: true });
140
+ }
141
+ /**
142
+ * Create a table.
143
+ * @deprecated This was only only included for TableV2 and is no longer necessary.
144
+ * Prefer to use new Table() directly.
145
+ *
146
+ * TODO remove in the next major release.
147
+ */
148
+ static createTable(name, table) {
149
+ return new Table({
150
+ name,
151
+ columns: table.columns,
152
+ indexes: table.indexes,
153
+ localOnly: table.options.localOnly,
154
+ insertOnly: table.options.insertOnly,
155
+ viewName: table.options.viewName
156
+ });
157
+ }
158
+ constructor(optionsOrColumns, v2Options) {
159
+ if (this.isTableV1(optionsOrColumns)) {
160
+ this.initTableV1(optionsOrColumns);
161
+ }
162
+ else {
163
+ this.initTableV2(optionsOrColumns, v2Options);
164
+ }
165
+ }
166
+ copyWithName(name) {
167
+ return new Table({
168
+ ...this.options,
169
+ name
170
+ });
171
+ }
172
+ isTableV1(arg) {
173
+ return 'columns' in arg && Array.isArray(arg.columns);
174
+ }
175
+ initTableV1(options) {
176
+ this.options = {
177
+ ...options,
178
+ indexes: options.indexes || []
179
+ };
180
+ this.applyDefaultOptions();
181
+ }
182
+ initTableV2(columns, options) {
183
+ const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));
184
+ const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({
185
+ name,
186
+ columns: columnNames.map((name) => new IndexedColumn({
187
+ name: name.replace(/^-/, ''),
188
+ ascending: !name.startsWith('-')
189
+ }))
190
+ }));
191
+ this.options = {
192
+ name: '',
193
+ columns: convertedColumns,
194
+ indexes: convertedIndexes,
195
+ viewName: options?.viewName,
196
+ insertOnly: options?.insertOnly,
197
+ localOnly: options?.localOnly,
198
+ trackPrevious: options?.trackPrevious,
199
+ trackMetadata: options?.trackMetadata,
200
+ ignoreEmptyUpdates: options?.ignoreEmptyUpdates
201
+ };
202
+ this.applyDefaultOptions();
203
+ this._mappedColumns = columns;
204
+ }
205
+ applyDefaultOptions() {
206
+ this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;
207
+ this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;
208
+ this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;
209
+ this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;
210
+ this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;
211
+ }
212
+ get name() {
213
+ return this.options.name;
214
+ }
215
+ get viewNameOverride() {
216
+ return this.options.viewName;
217
+ }
218
+ get viewName() {
219
+ return this.viewNameOverride ?? this.name;
220
+ }
221
+ get columns() {
222
+ return this.options.columns;
223
+ }
224
+ get columnMap() {
225
+ return (this._mappedColumns ??
226
+ this.columns.reduce((hash, column) => {
227
+ hash[column.name] = { type: column.type ?? exports.ColumnType.TEXT };
228
+ return hash;
229
+ }, {}));
230
+ }
231
+ get indexes() {
232
+ return this.options.indexes ?? [];
233
+ }
234
+ get localOnly() {
235
+ return this.options.localOnly;
236
+ }
237
+ get insertOnly() {
238
+ return this.options.insertOnly;
239
+ }
240
+ get trackPrevious() {
241
+ return this.options.trackPrevious;
242
+ }
243
+ get trackMetadata() {
244
+ return this.options.trackMetadata;
245
+ }
246
+ get ignoreEmptyUpdates() {
247
+ return this.options.ignoreEmptyUpdates;
248
+ }
249
+ get internalName() {
250
+ if (this.options.localOnly) {
251
+ return `ps_data_local__${this.name}`;
252
+ }
253
+ return `ps_data__${this.name}`;
254
+ }
255
+ get validName() {
256
+ if (InvalidSQLCharacters.test(this.name)) {
257
+ return false;
258
+ }
259
+ if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
260
+ return false;
261
+ }
262
+ return true;
263
+ }
264
+ validate() {
265
+ if (InvalidSQLCharacters.test(this.name)) {
266
+ throw new Error(`Invalid characters in table name: ${this.name}`);
267
+ }
268
+ if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
269
+ throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
270
+ }
271
+ if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {
272
+ throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);
273
+ }
274
+ if (this.trackMetadata && this.localOnly) {
275
+ throw new Error(`Can't include metadata for local-only tables.`);
276
+ }
277
+ if (this.trackPrevious != false && this.localOnly) {
278
+ throw new Error(`Can't include old values for local-only tables.`);
279
+ }
280
+ const columnNames = new Set();
281
+ columnNames.add('id');
282
+ for (const column of this.columns) {
283
+ const { name: columnName } = column;
284
+ if (column.name === 'id') {
285
+ throw new Error(`An id column is automatically added, custom id columns are not supported`);
286
+ }
287
+ if (columnNames.has(columnName)) {
288
+ throw new Error(`Duplicate column ${columnName}`);
289
+ }
290
+ if (InvalidSQLCharacters.test(columnName)) {
291
+ throw new Error(`Invalid characters in column name: ${column.name}`);
292
+ }
293
+ columnNames.add(columnName);
294
+ }
295
+ const indexNames = new Set();
296
+ for (const index of this.indexes) {
297
+ if (indexNames.has(index.name)) {
298
+ throw new Error(`Duplicate index ${index.name}`);
299
+ }
300
+ if (InvalidSQLCharacters.test(index.name)) {
301
+ throw new Error(`Invalid characters in index name: ${index.name}`);
302
+ }
303
+ for (const column of index.columns) {
304
+ if (!columnNames.has(column.name)) {
305
+ throw new Error(`Column ${column.name} not found for index ${index.name}`);
306
+ }
307
+ }
308
+ indexNames.add(index.name);
309
+ }
310
+ }
311
+ toJSON() {
312
+ return {
313
+ name: this.name,
314
+ view_name: this.viewName,
315
+ columns: this.columns.map((c) => c.toJSON()),
316
+ indexes: this.indexes.map((e) => e.toJSON(this)),
317
+ ...encodeTableOptions(this)
318
+ };
319
+ }
320
+ }
321
+
322
+ const ATTACHMENT_TABLE = 'attachments';
323
+ /**
324
+ * Maps a database row to an AttachmentRecord.
325
+ *
326
+ * @param row - The database row object
327
+ * @returns The corresponding AttachmentRecord
328
+ *
329
+ * @experimental
330
+ */
331
+ function attachmentFromSql(row) {
332
+ return {
333
+ id: row.id,
334
+ filename: row.filename,
335
+ localUri: row.local_uri,
336
+ size: row.size,
337
+ mediaType: row.media_type,
338
+ timestamp: row.timestamp,
339
+ metaData: row.meta_data,
340
+ hasSynced: row.has_synced === 1,
341
+ state: row.state
342
+ };
343
+ }
344
+ /**
345
+ * AttachmentState represents the current synchronization state of an attachment.
346
+ *
347
+ * @experimental
348
+ */
349
+ exports.AttachmentState = void 0;
350
+ (function (AttachmentState) {
351
+ AttachmentState[AttachmentState["QUEUED_UPLOAD"] = 0] = "QUEUED_UPLOAD";
352
+ AttachmentState[AttachmentState["QUEUED_DOWNLOAD"] = 1] = "QUEUED_DOWNLOAD";
353
+ AttachmentState[AttachmentState["QUEUED_DELETE"] = 2] = "QUEUED_DELETE";
354
+ AttachmentState[AttachmentState["SYNCED"] = 3] = "SYNCED";
355
+ AttachmentState[AttachmentState["ARCHIVED"] = 4] = "ARCHIVED"; // Attachment has been orphaned, i.e. the associated record has been deleted
356
+ })(exports.AttachmentState || (exports.AttachmentState = {}));
357
+ /**
358
+ * AttachmentTable defines the schema for the attachment queue table.
359
+ *
360
+ * @internal
361
+ */
362
+ class AttachmentTable extends Table {
363
+ constructor(options) {
364
+ super({
365
+ filename: column.text,
366
+ local_uri: column.text,
367
+ timestamp: column.integer,
368
+ size: column.integer,
369
+ media_type: column.text,
370
+ state: column.integer, // Corresponds to AttachmentState
371
+ has_synced: column.integer,
372
+ meta_data: column.text
373
+ }, {
374
+ ...options,
375
+ viewName: options?.viewName ?? ATTACHMENT_TABLE,
376
+ localOnly: true,
377
+ insertOnly: false
378
+ });
379
+ }
380
+ }
381
+
382
+ /**
383
+ * AttachmentContext provides database operations for managing attachment records.
384
+ *
385
+ * Provides methods to query, insert, update, and delete attachment records with
386
+ * proper transaction management through PowerSync.
387
+ *
388
+ * @internal
389
+ */
390
+ class AttachmentContext {
391
+ /** PowerSync database instance for executing queries */
392
+ db;
393
+ /** Name of the database table storing attachment records */
394
+ tableName;
395
+ /** Logger instance for diagnostic information */
396
+ logger;
397
+ /** Maximum number of archived attachments to keep before cleanup */
398
+ archivedCacheLimit = 100;
399
+ /**
400
+ * Creates a new AttachmentContext instance.
401
+ *
402
+ * @param db - PowerSync database instance
403
+ * @param tableName - Name of the table storing attachment records. Default: 'attachments'
404
+ * @param logger - Logger instance for diagnostic output
405
+ */
406
+ constructor(db, tableName = 'attachments', logger, archivedCacheLimit) {
407
+ this.db = db;
408
+ this.tableName = tableName;
409
+ this.logger = logger;
410
+ this.archivedCacheLimit = archivedCacheLimit;
411
+ }
412
+ /**
413
+ * Retrieves all active attachments that require synchronization.
414
+ * Active attachments include those queued for upload, download, or delete.
415
+ * Results are ordered by timestamp in ascending order.
416
+ *
417
+ * @returns Promise resolving to an array of active attachment records
418
+ */
419
+ async getActiveAttachments() {
420
+ const attachments = await this.db.getAll(
421
+ /* sql */
422
+ `
423
+ SELECT
424
+ *
425
+ FROM
426
+ ${this.tableName}
427
+ WHERE
428
+ state = ?
429
+ OR state = ?
430
+ OR state = ?
431
+ ORDER BY
432
+ timestamp ASC
433
+ `, [exports.AttachmentState.QUEUED_UPLOAD, exports.AttachmentState.QUEUED_DOWNLOAD, exports.AttachmentState.QUEUED_DELETE]);
434
+ return attachments.map(attachmentFromSql);
435
+ }
436
+ /**
437
+ * Retrieves all archived attachments.
438
+ *
439
+ * Archived attachments are no longer referenced but haven't been permanently deleted.
440
+ * These are candidates for cleanup operations to free up storage space.
441
+ *
442
+ * @returns Promise resolving to an array of archived attachment records
443
+ */
444
+ async getArchivedAttachments() {
445
+ const attachments = await this.db.getAll(
446
+ /* sql */
447
+ `
448
+ SELECT
449
+ *
450
+ FROM
451
+ ${this.tableName}
452
+ WHERE
453
+ state = ?
454
+ ORDER BY
455
+ timestamp ASC
456
+ `, [exports.AttachmentState.ARCHIVED]);
457
+ return attachments.map(attachmentFromSql);
458
+ }
459
+ /**
460
+ * Retrieves all attachment records regardless of state.
461
+ * Results are ordered by timestamp in ascending order.
462
+ *
463
+ * @returns Promise resolving to an array of all attachment records
464
+ */
465
+ async getAttachments() {
466
+ const attachments = await this.db.getAll(
467
+ /* sql */
468
+ `
469
+ SELECT
470
+ *
471
+ FROM
472
+ ${this.tableName}
473
+ ORDER BY
474
+ timestamp ASC
475
+ `, []);
476
+ return attachments.map(attachmentFromSql);
477
+ }
478
+ /**
479
+ * Inserts or updates an attachment record within an existing transaction.
480
+ *
481
+ * Performs an upsert operation (INSERT OR REPLACE). Must be called within
482
+ * an active database transaction context.
483
+ *
484
+ * @param attachment - The attachment record to upsert
485
+ * @param context - Active database transaction context
486
+ */
487
+ async upsertAttachment(attachment, context) {
488
+ await context.execute(
489
+ /* sql */
490
+ `
491
+ INSERT
492
+ OR REPLACE INTO ${this.tableName} (
493
+ id,
494
+ filename,
495
+ local_uri,
496
+ size,
497
+ media_type,
498
+ timestamp,
499
+ state,
500
+ has_synced,
501
+ meta_data
502
+ )
503
+ VALUES
504
+ (?, ?, ?, ?, ?, ?, ?, ?, ?)
505
+ `, [
506
+ attachment.id,
507
+ attachment.filename,
508
+ attachment.localUri || null,
509
+ attachment.size || null,
510
+ attachment.mediaType || null,
511
+ attachment.timestamp,
512
+ attachment.state,
513
+ attachment.hasSynced ? 1 : 0,
514
+ attachment.metaData || null
515
+ ]);
516
+ }
517
+ async getAttachment(id) {
518
+ const attachment = await this.db.get(
519
+ /* sql */
520
+ `
521
+ SELECT
522
+ *
523
+ FROM
524
+ ${this.tableName}
525
+ WHERE
526
+ id = ?
527
+ `, [id]);
528
+ return attachment ? attachmentFromSql(attachment) : undefined;
529
+ }
530
+ /**
531
+ * Permanently deletes an attachment record from the database.
532
+ *
533
+ * This operation removes the attachment record but does not delete
534
+ * the associated local or remote files. File deletion should be handled
535
+ * separately through the appropriate storage adapters.
536
+ *
537
+ * @param attachmentId - Unique identifier of the attachment to delete
538
+ */
539
+ async deleteAttachment(attachmentId) {
540
+ await this.db.writeTransaction((tx) => tx.execute(
541
+ /* sql */
542
+ `
543
+ DELETE FROM ${this.tableName}
544
+ WHERE
545
+ id = ?
546
+ `, [attachmentId]));
547
+ }
548
+ async clearQueue() {
549
+ await this.db.writeTransaction((tx) => tx.execute(/* sql */ ` DELETE FROM ${this.tableName} `));
550
+ }
551
+ async deleteArchivedAttachments(callback) {
552
+ const limit = 1000;
553
+ const results = await this.db.getAll(
554
+ /* sql */
555
+ `
556
+ SELECT
557
+ *
558
+ FROM
559
+ ${this.tableName}
560
+ WHERE
561
+ state = ?
562
+ ORDER BY
563
+ timestamp DESC
564
+ LIMIT
565
+ ?
566
+ OFFSET
567
+ ?
568
+ `, [exports.AttachmentState.ARCHIVED, limit, this.archivedCacheLimit]);
569
+ const archivedAttachments = results.map(attachmentFromSql);
570
+ if (archivedAttachments.length === 0)
571
+ return false;
572
+ await callback?.(archivedAttachments);
573
+ this.logger.info(`Deleting ${archivedAttachments.length} archived attachments. Archived attachment exceeds cache archiveCacheLimit of ${this.archivedCacheLimit}.`);
574
+ const ids = archivedAttachments.map((attachment) => attachment.id);
575
+ await this.db.execute(
576
+ /* sql */
577
+ `
578
+ DELETE FROM ${this.tableName}
579
+ WHERE
580
+ id IN (
581
+ SELECT
582
+ json_each.value
583
+ FROM
584
+ json_each (?)
585
+ );
586
+ `, [JSON.stringify(ids)]);
587
+ this.logger.info(`Deleted ${archivedAttachments.length} archived attachments`);
588
+ return archivedAttachments.length < limit;
589
+ }
590
+ /**
591
+ * Saves multiple attachment records in a single transaction.
592
+ *
593
+ * All updates are saved in a single batch after processing.
594
+ * If the attachments array is empty, no database operations are performed.
595
+ *
596
+ * @param attachments - Array of attachment records to save
597
+ */
598
+ async saveAttachments(attachments) {
599
+ if (attachments.length === 0) {
600
+ return;
601
+ }
602
+ await this.db.writeTransaction(async (tx) => {
603
+ for (const attachment of attachments) {
604
+ await this.upsertAttachment(attachment, tx);
605
+ }
606
+ });
607
+ }
608
+ }
609
+
610
+ exports.WatchedQueryListenerEvent = void 0;
611
+ (function (WatchedQueryListenerEvent) {
612
+ WatchedQueryListenerEvent["ON_DATA"] = "onData";
613
+ WatchedQueryListenerEvent["ON_ERROR"] = "onError";
614
+ WatchedQueryListenerEvent["ON_STATE_CHANGE"] = "onStateChange";
615
+ WatchedQueryListenerEvent["SETTINGS_WILL_UPDATE"] = "settingsWillUpdate";
616
+ WatchedQueryListenerEvent["CLOSED"] = "closed";
617
+ })(exports.WatchedQueryListenerEvent || (exports.WatchedQueryListenerEvent = {}));
618
+ const DEFAULT_WATCH_THROTTLE_MS = 30;
619
+ const DEFAULT_WATCH_QUERY_OPTIONS = {
620
+ throttleMs: DEFAULT_WATCH_THROTTLE_MS,
621
+ reportFetching: true
622
+ };
623
+
624
+ /**
625
+ * Orchestrates attachment synchronization between local and remote storage.
626
+ * Handles uploads, downloads, deletions, and state transitions.
627
+ *
628
+ * @internal
629
+ */
630
+ class SyncingService {
631
+ attachmentService;
632
+ localStorage;
633
+ remoteStorage;
634
+ logger;
635
+ errorHandler;
636
+ constructor(attachmentService, localStorage, remoteStorage, logger, errorHandler) {
637
+ this.attachmentService = attachmentService;
638
+ this.localStorage = localStorage;
639
+ this.remoteStorage = remoteStorage;
640
+ this.logger = logger;
641
+ this.errorHandler = errorHandler;
642
+ }
643
+ /**
644
+ * Processes attachments based on their state (upload, download, or delete).
645
+ * All updates are saved in a single batch after processing.
646
+ *
647
+ * @param attachments - Array of attachment records to process
648
+ * @param context - Attachment context for database operations
649
+ * @returns Promise that resolves when all attachments have been processed and saved
650
+ */
651
+ async processAttachments(attachments, context) {
652
+ const updatedAttachments = [];
653
+ for (const attachment of attachments) {
654
+ switch (attachment.state) {
655
+ case exports.AttachmentState.QUEUED_UPLOAD:
656
+ const uploaded = await this.uploadAttachment(attachment);
657
+ updatedAttachments.push(uploaded);
658
+ break;
659
+ case exports.AttachmentState.QUEUED_DOWNLOAD:
660
+ const downloaded = await this.downloadAttachment(attachment);
661
+ updatedAttachments.push(downloaded);
662
+ break;
663
+ case exports.AttachmentState.QUEUED_DELETE:
664
+ const deleted = await this.deleteAttachment(attachment);
665
+ updatedAttachments.push(deleted);
666
+ break;
667
+ }
668
+ }
669
+ await context.saveAttachments(updatedAttachments);
670
+ }
671
+ /**
672
+ * Uploads an attachment from local storage to remote storage.
673
+ * On success, marks as SYNCED. On failure, defers to error handler or archives.
674
+ *
675
+ * @param attachment - The attachment record to upload
676
+ * @returns Updated attachment record with new state
677
+ * @throws Error if the attachment has no localUri
678
+ */
679
+ async uploadAttachment(attachment) {
680
+ this.logger.info(`Uploading attachment ${attachment.filename}`);
681
+ try {
682
+ if (attachment.localUri == null) {
683
+ throw new Error(`No localUri for attachment ${attachment.id}`);
684
+ }
685
+ const fileBlob = await this.localStorage.readFile(attachment.localUri);
686
+ await this.remoteStorage.uploadFile(fileBlob, attachment);
687
+ return {
688
+ ...attachment,
689
+ state: exports.AttachmentState.SYNCED,
690
+ hasSynced: true
691
+ };
692
+ }
693
+ catch (error) {
694
+ const shouldRetry = (await this.errorHandler?.onUploadError(attachment, error)) ?? true;
695
+ if (!shouldRetry) {
696
+ return {
697
+ ...attachment,
698
+ state: exports.AttachmentState.ARCHIVED
699
+ };
700
+ }
701
+ return attachment;
702
+ }
703
+ }
704
+ /**
705
+ * Downloads an attachment from remote storage to local storage.
706
+ * Retrieves the file, converts to base64, and saves locally.
707
+ * On success, marks as SYNCED. On failure, defers to error handler or archives.
708
+ *
709
+ * @param attachment - The attachment record to download
710
+ * @returns Updated attachment record with local URI and new state
711
+ */
712
+ async downloadAttachment(attachment) {
713
+ this.logger.info(`Downloading attachment ${attachment.filename}`);
714
+ try {
715
+ const fileData = await this.remoteStorage.downloadFile(attachment);
716
+ const localUri = this.localStorage.getLocalUri(attachment.filename);
717
+ await this.localStorage.saveFile(localUri, fileData);
718
+ return {
719
+ ...attachment,
720
+ state: exports.AttachmentState.SYNCED,
721
+ localUri: localUri,
722
+ hasSynced: true
723
+ };
724
+ }
725
+ catch (error) {
726
+ const shouldRetry = (await this.errorHandler?.onDownloadError(attachment, error)) ?? true;
727
+ if (!shouldRetry) {
728
+ return {
729
+ ...attachment,
730
+ state: exports.AttachmentState.ARCHIVED
731
+ };
732
+ }
733
+ return attachment;
734
+ }
735
+ }
736
+ /**
737
+ * Deletes an attachment from both remote and local storage.
738
+ * Removes the remote file, local file (if exists), and the attachment record.
739
+ * On failure, defers to error handler or archives.
740
+ *
741
+ * @param attachment - The attachment record to delete
742
+ * @returns Updated attachment record
743
+ */
744
+ async deleteAttachment(attachment) {
745
+ try {
746
+ await this.remoteStorage.deleteFile(attachment);
747
+ if (attachment.localUri) {
748
+ await this.localStorage.deleteFile(attachment.localUri);
749
+ }
750
+ await this.attachmentService.withContext(async (ctx) => {
751
+ await ctx.deleteAttachment(attachment.id);
752
+ });
753
+ return {
754
+ ...attachment,
755
+ state: exports.AttachmentState.ARCHIVED
756
+ };
757
+ }
758
+ catch (error) {
759
+ const shouldRetry = (await this.errorHandler?.onDeleteError(attachment, error)) ?? true;
760
+ if (!shouldRetry) {
761
+ return {
762
+ ...attachment,
763
+ state: exports.AttachmentState.ARCHIVED
764
+ };
765
+ }
766
+ return attachment;
767
+ }
768
+ }
769
+ /**
770
+ * Performs cleanup of archived attachments by removing their local files and records.
771
+ * Errors during local file deletion are logged but do not prevent record deletion.
772
+ */
773
+ async deleteArchivedAttachments(context) {
774
+ return await context.deleteArchivedAttachments(async (archivedAttachments) => {
775
+ for (const attachment of archivedAttachments) {
776
+ if (attachment.localUri) {
777
+ try {
778
+ await this.localStorage.deleteFile(attachment.localUri);
779
+ }
780
+ catch (error) {
781
+ this.logger.error('Error deleting local file for archived attachment', error);
782
+ }
783
+ }
784
+ }
785
+ });
786
+ }
787
+ }
788
+
789
+ /**
790
+ * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
791
+ */
792
+ async function mutexRunExclusive(mutex, callback, options) {
793
+ return new Promise((resolve, reject) => {
794
+ const timeout = options?.timeoutMs;
795
+ let timedOut = false;
796
+ const timeoutId = timeout
797
+ ? setTimeout(() => {
798
+ timedOut = true;
799
+ reject(new Error('Timeout waiting for lock'));
800
+ }, timeout)
801
+ : undefined;
802
+ mutex.runExclusive(async () => {
803
+ if (timeoutId) {
804
+ clearTimeout(timeoutId);
805
+ }
806
+ if (timedOut)
807
+ return;
808
+ try {
809
+ resolve(await callback());
810
+ }
811
+ catch (ex) {
812
+ reject(ex);
813
+ }
814
+ });
815
+ });
816
+ }
817
+
818
+ /**
819
+ * Service for querying and watching attachment records in the database.
820
+ *
821
+ * @internal
822
+ */
823
+ class AttachmentService {
824
+ db;
825
+ logger;
826
+ tableName;
827
+ mutex = new asyncMutex.Mutex();
828
+ context;
829
+ constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
830
+ this.db = db;
831
+ this.logger = logger;
832
+ this.tableName = tableName;
833
+ this.context = new AttachmentContext(db, tableName, logger, archivedCacheLimit);
834
+ }
835
+ /**
836
+ * Creates a differential watch query for active attachments requiring synchronization.
837
+ * @returns Watch query that emits changes for queued uploads, downloads, and deletes
838
+ */
839
+ watchActiveAttachments({ throttleMs } = {}) {
840
+ this.logger.info('Watching active attachments...');
841
+ const watch = this.db
842
+ .query({
843
+ sql: /* sql */ `
844
+ SELECT
845
+ *
846
+ FROM
847
+ ${this.tableName}
848
+ WHERE
849
+ state = ?
850
+ OR state = ?
851
+ OR state = ?
852
+ ORDER BY
853
+ timestamp ASC
854
+ `,
855
+ parameters: [exports.AttachmentState.QUEUED_UPLOAD, exports.AttachmentState.QUEUED_DOWNLOAD, exports.AttachmentState.QUEUED_DELETE]
856
+ })
857
+ .differentialWatch({ throttleMs });
858
+ return watch;
859
+ }
860
+ /**
861
+ * Executes a callback with exclusive access to the attachment context.
862
+ */
863
+ async withContext(callback) {
864
+ return mutexRunExclusive(this.mutex, async () => {
865
+ return callback(this.context);
866
+ });
867
+ }
868
+ }
869
+
870
+ /**
871
+ * AttachmentQueue manages the lifecycle and synchronization of attachments
872
+ * between local and remote storage.
873
+ * Provides automatic synchronization, upload/download queuing, attachment monitoring,
874
+ * verification and repair of local files, and cleanup of archived attachments.
875
+ *
876
+ * @experimental
877
+ * @alpha This is currently experimental and may change without a major version bump.
878
+ */
879
+ class AttachmentQueue {
880
+ /** Timer for periodic synchronization operations */
881
+ periodicSyncTimer;
882
+ /** Service for synchronizing attachments between local and remote storage */
883
+ syncingService;
884
+ /** Adapter for local file storage operations */
885
+ localStorage;
886
+ /** Adapter for remote file storage operations */
887
+ remoteStorage;
888
+ /**
889
+ * Callback function to watch for changes in attachment references in your data model.
890
+ *
891
+ * This should be implemented by the user of AttachmentQueue to monitor changes in your application's
892
+ * data that reference attachments. When attachments are added, removed, or modified,
893
+ * this callback should trigger the onUpdate function with the current set of attachments.
894
+ */
895
+ watchAttachments;
896
+ /** Name of the database table storing attachment records */
897
+ tableName;
898
+ /** Logger instance for diagnostic information */
899
+ logger;
900
+ /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
901
+ syncIntervalMs = 30 * 1000;
902
+ /** Duration in milliseconds to throttle sync operations */
903
+ syncThrottleDuration;
904
+ /** Whether to automatically download remote attachments. Default: true */
905
+ downloadAttachments = true;
906
+ /** Maximum number of archived attachments to keep before cleanup. Default: 100 */
907
+ archivedCacheLimit;
908
+ /** Service for managing attachment-related database operations */
909
+ attachmentService;
910
+ /** PowerSync database instance */
911
+ db;
912
+ /** Cleanup function for status change listener */
913
+ statusListenerDispose;
914
+ watchActiveAttachments;
915
+ watchAttachmentsAbortController;
916
+ /**
917
+ * Creates a new AttachmentQueue instance.
918
+ *
919
+ * @param options - Configuration options
920
+ * @param options.db - PowerSync database instance
921
+ * @param options.remoteStorage - Remote storage adapter for upload/download operations
922
+ * @param options.localStorage - Local storage adapter for file persistence
923
+ * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
924
+ * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
925
+ * @param options.logger - Logger instance. Defaults to db.logger
926
+ * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
927
+ * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
928
+ * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
929
+ * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
930
+ */
931
+ constructor({ db, localStorage, remoteStorage, watchAttachments, logger, tableName = ATTACHMENT_TABLE, syncIntervalMs = 30 * 1000, syncThrottleDuration = DEFAULT_WATCH_THROTTLE_MS, downloadAttachments = true, archivedCacheLimit = 100, errorHandler }) {
932
+ this.db = db;
933
+ this.remoteStorage = remoteStorage;
934
+ this.localStorage = localStorage;
935
+ this.watchAttachments = watchAttachments;
936
+ this.tableName = tableName;
937
+ this.syncIntervalMs = syncIntervalMs;
938
+ this.syncThrottleDuration = syncThrottleDuration;
939
+ this.archivedCacheLimit = archivedCacheLimit;
940
+ this.downloadAttachments = downloadAttachments;
941
+ this.logger = logger ?? db.logger;
942
+ this.attachmentService = new AttachmentService(db, this.logger, tableName, archivedCacheLimit);
943
+ this.syncingService = new SyncingService(this.attachmentService, localStorage, remoteStorage, this.logger, errorHandler);
944
+ }
945
+ /**
946
+ * Generates a new attachment ID using a SQLite UUID function.
947
+ *
948
+ * @returns Promise resolving to the new attachment ID
949
+ */
950
+ async generateAttachmentId() {
951
+ return this.db.get('SELECT uuid() as id').then((row) => row.id);
952
+ }
953
+ /**
954
+ * Starts the attachment synchronization process.
955
+ *
956
+ * This method:
957
+ * - Stops any existing sync operations
958
+ * - Sets up periodic synchronization based on syncIntervalMs
959
+ * - Registers listeners for active attachment changes
960
+ * - Processes watched attachments to queue uploads/downloads
961
+ * - Handles state transitions for archived and new attachments
962
+ */
963
+ async startSync() {
964
+ await this.stopSync();
965
+ this.watchActiveAttachments = this.attachmentService.watchActiveAttachments({
966
+ throttleMs: this.syncThrottleDuration
967
+ });
968
+ // immediately invoke the sync storage to initialize local storage
969
+ await this.localStorage.initialize();
970
+ await this.verifyAttachments();
971
+ // Sync storage periodically
972
+ this.periodicSyncTimer = setInterval(async () => {
973
+ await this.syncStorage();
974
+ }, this.syncIntervalMs);
975
+ // Sync storage when there is a change in active attachments
976
+ this.watchActiveAttachments.registerListener({
977
+ onDiff: async () => {
978
+ await this.syncStorage();
979
+ }
980
+ });
981
+ this.statusListenerDispose = this.db.registerListener({
982
+ statusChanged: (status) => {
983
+ if (status.connected) {
984
+ // Device came online, process attachments immediately
985
+ this.syncStorage().catch((error) => {
986
+ this.logger.error('Error syncing storage on connection:', error);
987
+ });
988
+ }
989
+ }
990
+ });
991
+ this.watchAttachmentsAbortController = new AbortController();
992
+ const signal = this.watchAttachmentsAbortController.signal;
993
+ // Process attachments when there is a change in watched attachments
994
+ this.watchAttachments(async (watchedAttachments) => {
995
+ // Skip processing if sync has been stopped
996
+ if (signal.aborted) {
997
+ return;
998
+ }
999
+ await this.attachmentService.withContext(async (ctx) => {
1000
+ // Need to get all the attachments which are tracked in the DB.
1001
+ // We might need to restore an archived attachment.
1002
+ const currentAttachments = await ctx.getAttachments();
1003
+ const attachmentUpdates = [];
1004
+ for (const watchedAttachment of watchedAttachments) {
1005
+ const existingQueueItem = currentAttachments.find((a) => a.id === watchedAttachment.id);
1006
+ if (!existingQueueItem) {
1007
+ // Item is watched but not in the queue yet. Need to add it.
1008
+ if (!this.downloadAttachments) {
1009
+ continue;
1010
+ }
1011
+ const filename = watchedAttachment.filename ?? `${watchedAttachment.id}.${watchedAttachment.fileExtension}`;
1012
+ attachmentUpdates.push({
1013
+ id: watchedAttachment.id,
1014
+ filename,
1015
+ state: exports.AttachmentState.QUEUED_DOWNLOAD,
1016
+ hasSynced: false,
1017
+ metaData: watchedAttachment.metaData,
1018
+ timestamp: new Date().getTime()
1019
+ });
1020
+ continue;
1021
+ }
1022
+ if (existingQueueItem.state === exports.AttachmentState.ARCHIVED) {
1023
+ // The attachment is present again. Need to queue it for sync.
1024
+ // We might be able to optimize this in future
1025
+ if (existingQueueItem.hasSynced === true) {
1026
+ // No remote action required, we can restore the record (avoids deletion)
1027
+ attachmentUpdates.push({
1028
+ ...existingQueueItem,
1029
+ state: exports.AttachmentState.SYNCED
1030
+ });
1031
+ }
1032
+ else {
1033
+ // The localURI should be set if the record was meant to be uploaded
1034
+ // and hasSynced is false then
1035
+ // it must be an upload operation
1036
+ const newState = existingQueueItem.localUri == null ? exports.AttachmentState.QUEUED_DOWNLOAD : exports.AttachmentState.QUEUED_UPLOAD;
1037
+ attachmentUpdates.push({
1038
+ ...existingQueueItem,
1039
+ state: newState
1040
+ });
1041
+ }
1042
+ }
1043
+ }
1044
+ for (const attachment of currentAttachments) {
1045
+ const notInWatchedItems = watchedAttachments.find((i) => i.id === attachment.id) == null;
1046
+ if (notInWatchedItems) {
1047
+ switch (attachment.state) {
1048
+ case exports.AttachmentState.QUEUED_DELETE:
1049
+ case exports.AttachmentState.QUEUED_UPLOAD:
1050
+ // Only archive if it has synced
1051
+ if (attachment.hasSynced === true) {
1052
+ attachmentUpdates.push({
1053
+ ...attachment,
1054
+ state: exports.AttachmentState.ARCHIVED
1055
+ });
1056
+ }
1057
+ break;
1058
+ default:
1059
+ // Archive other states such as QUEUED_DOWNLOAD
1060
+ attachmentUpdates.push({
1061
+ ...attachment,
1062
+ state: exports.AttachmentState.ARCHIVED
1063
+ });
1064
+ }
1065
+ }
1066
+ }
1067
+ if (attachmentUpdates.length > 0) {
1068
+ await ctx.saveAttachments(attachmentUpdates);
1069
+ }
1070
+ });
1071
+ }, signal);
1072
+ }
1073
+ /**
1074
+ * Synchronizes all active attachments between local and remote storage.
1075
+ *
1076
+ * This is called automatically at regular intervals when sync is started,
1077
+ * but can also be called manually to trigger an immediate sync.
1078
+ */
1079
+ async syncStorage() {
1080
+ await this.attachmentService.withContext(async (ctx) => {
1081
+ const activeAttachments = await ctx.getActiveAttachments();
1082
+ await this.localStorage.initialize();
1083
+ await this.syncingService.processAttachments(activeAttachments, ctx);
1084
+ await this.syncingService.deleteArchivedAttachments(ctx);
1085
+ });
1086
+ }
1087
+ /**
1088
+ * Stops the attachment synchronization process.
1089
+ *
1090
+ * Clears the periodic sync timer and closes all active attachment watchers.
1091
+ */
1092
+ async stopSync() {
1093
+ clearInterval(this.periodicSyncTimer);
1094
+ this.periodicSyncTimer = undefined;
1095
+ if (this.watchActiveAttachments)
1096
+ await this.watchActiveAttachments.close();
1097
+ if (this.watchAttachmentsAbortController) {
1098
+ this.watchAttachmentsAbortController.abort();
1099
+ }
1100
+ if (this.statusListenerDispose) {
1101
+ this.statusListenerDispose();
1102
+ this.statusListenerDispose = undefined;
1103
+ }
1104
+ }
1105
+ /**
1106
+ * Saves a file to local storage and queues it for upload to remote storage.
1107
+ *
1108
+ * @param options - File save options
1109
+ * @param options.data - The file data as ArrayBuffer, Blob, or base64 string
1110
+ * @param options.fileExtension - File extension (e.g., 'jpg', 'pdf')
1111
+ * @param options.mediaType - MIME type of the file (e.g., 'image/jpeg')
1112
+ * @param options.metaData - Optional metadata to associate with the attachment
1113
+ * @param options.id - Optional custom ID. If not provided, a UUID will be generated
1114
+ * @param options.updateHook - Optional callback to execute additional database operations
1115
+ * within the same transaction as the attachment creation
1116
+ * @returns Promise resolving to the created attachment record
1117
+ */
1118
+ async saveFile({ data, fileExtension, mediaType, metaData, id, updateHook }) {
1119
+ const resolvedId = id ?? (await this.generateAttachmentId());
1120
+ const filename = `${resolvedId}.${fileExtension}`;
1121
+ const localUri = this.localStorage.getLocalUri(filename);
1122
+ const size = await this.localStorage.saveFile(localUri, data);
1123
+ const attachment = {
1124
+ id: resolvedId,
1125
+ filename,
1126
+ mediaType,
1127
+ localUri,
1128
+ state: exports.AttachmentState.QUEUED_UPLOAD,
1129
+ hasSynced: false,
1130
+ size,
1131
+ timestamp: new Date().getTime(),
1132
+ metaData
1133
+ };
1134
+ await this.attachmentService.withContext(async (ctx) => {
1135
+ await ctx.db.writeTransaction(async (tx) => {
1136
+ await updateHook?.(tx, attachment);
1137
+ await ctx.upsertAttachment(attachment, tx);
1138
+ });
1139
+ });
1140
+ return attachment;
1141
+ }
1142
+ async deleteFile({ id, updateHook }) {
1143
+ await this.attachmentService.withContext(async (ctx) => {
1144
+ const attachment = await ctx.getAttachment(id);
1145
+ if (!attachment) {
1146
+ throw new Error(`Attachment with id ${id} not found`);
1147
+ }
1148
+ await ctx.db.writeTransaction(async (tx) => {
1149
+ await updateHook?.(tx, attachment);
1150
+ await ctx.upsertAttachment({
1151
+ ...attachment,
1152
+ state: exports.AttachmentState.QUEUED_DELETE,
1153
+ hasSynced: false
1154
+ }, tx);
1155
+ });
1156
+ });
1157
+ }
1158
+ async expireCache() {
1159
+ let isDone = false;
1160
+ while (!isDone) {
1161
+ await this.attachmentService.withContext(async (ctx) => {
1162
+ isDone = await this.syncingService.deleteArchivedAttachments(ctx);
1163
+ });
1164
+ }
1165
+ }
1166
+ async clearQueue() {
1167
+ await this.attachmentService.withContext(async (ctx) => {
1168
+ await ctx.clearQueue();
1169
+ });
1170
+ await this.localStorage.clear();
1171
+ }
1172
+ /**
1173
+ * Verifies the integrity of all attachment records and repairs inconsistencies.
1174
+ *
1175
+ * This method checks each attachment record against the local filesystem and:
1176
+ * - Updates localUri if the file exists at a different path
1177
+ * - Archives attachments with missing local files that haven't been uploaded
1178
+ * - Requeues synced attachments for download if their local files are missing
1179
+ */
1180
+ async verifyAttachments() {
1181
+ await this.attachmentService.withContext(async (ctx) => {
1182
+ const attachments = await ctx.getAttachments();
1183
+ const updates = [];
1184
+ for (const attachment of attachments) {
1185
+ if (attachment.localUri == null) {
1186
+ continue;
1187
+ }
1188
+ const exists = await this.localStorage.fileExists(attachment.localUri);
1189
+ if (exists) {
1190
+ // The file exists, this is correct
1191
+ continue;
1192
+ }
1193
+ const newLocalUri = this.localStorage.getLocalUri(attachment.filename);
1194
+ const newExists = await this.localStorage.fileExists(newLocalUri);
1195
+ if (newExists) {
1196
+ // The file exists locally but the localUri is broken, we update it.
1197
+ updates.push({
1198
+ ...attachment,
1199
+ localUri: newLocalUri
1200
+ });
1201
+ }
1202
+ else {
1203
+ // the file doesn't exist locally.
1204
+ if (attachment.state === exports.AttachmentState.SYNCED) {
1205
+ // the file has been successfully synced to remote storage but is missing
1206
+ // we download it again
1207
+ updates.push({
1208
+ ...attachment,
1209
+ state: exports.AttachmentState.QUEUED_DOWNLOAD,
1210
+ localUri: undefined
1211
+ });
1212
+ }
1213
+ else {
1214
+ // the file wasn't successfully synced to remote storage, we archive it
1215
+ updates.push({
1216
+ ...attachment,
1217
+ state: exports.AttachmentState.ARCHIVED,
1218
+ localUri: undefined // Clears the value
1219
+ });
1220
+ }
1221
+ }
1222
+ }
1223
+ await ctx.saveAttachments(updates);
1224
+ });
1225
+ }
1226
+ }
1227
+
1228
+ exports.EncodingType = void 0;
1229
+ (function (EncodingType) {
1230
+ EncodingType["UTF8"] = "utf8";
1231
+ EncodingType["Base64"] = "base64";
1232
+ })(exports.EncodingType || (exports.EncodingType = {}));
1233
+
7
1234
  function getDefaultExportFromCjs (x) {
8
1235
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
1236
  }
@@ -1167,20 +2394,6 @@ class MetaBaseObserver extends BaseObserver {
1167
2394
  }
1168
2395
  }
1169
2396
 
1170
- exports.WatchedQueryListenerEvent = void 0;
1171
- (function (WatchedQueryListenerEvent) {
1172
- WatchedQueryListenerEvent["ON_DATA"] = "onData";
1173
- WatchedQueryListenerEvent["ON_ERROR"] = "onError";
1174
- WatchedQueryListenerEvent["ON_STATE_CHANGE"] = "onStateChange";
1175
- WatchedQueryListenerEvent["SETTINGS_WILL_UPDATE"] = "settingsWillUpdate";
1176
- WatchedQueryListenerEvent["CLOSED"] = "closed";
1177
- })(exports.WatchedQueryListenerEvent || (exports.WatchedQueryListenerEvent = {}));
1178
- const DEFAULT_WATCH_THROTTLE_MS = 30;
1179
- const DEFAULT_WATCH_QUERY_OPTIONS = {
1180
- throttleMs: DEFAULT_WATCH_THROTTLE_MS,
1181
- reportFetching: true
1182
- };
1183
-
1184
2397
  /**
1185
2398
  * Performs underlying watching and yields a stream of results.
1186
2399
  * @internal
@@ -6722,7 +7935,7 @@ function requireDist () {
6722
7935
 
6723
7936
  var distExports = requireDist();
6724
7937
 
6725
- var version = "1.46.0";
7938
+ var version = "1.48.0";
6726
7939
  var PACKAGE = {
6727
7940
  version: version};
6728
7941
 
@@ -10347,193 +11560,59 @@ class SqliteBucketStorage extends BaseObserver {
10347
11560
  async control(op, payload) {
10348
11561
  return await this.writeTransaction(async (tx) => {
10349
11562
  const [[raw]] = await tx.executeRaw('SELECT powersync_control(?, ?)', [op, payload]);
10350
- return raw;
10351
- });
10352
- }
10353
- async hasMigratedSubkeys() {
10354
- const { r } = await this.db.get('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [
10355
- SqliteBucketStorage._subkeyMigrationKey
10356
- ]);
10357
- return r != 0;
10358
- }
10359
- async migrateToFixedSubkeys() {
10360
- await this.writeTransaction(async (tx) => {
10361
- await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
10362
- await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
10363
- SqliteBucketStorage._subkeyMigrationKey,
10364
- '1'
10365
- ]);
10366
- });
10367
- }
10368
- static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
10369
- }
10370
- function hasMatchingPriority(priority, bucket) {
10371
- return bucket.priority != null && bucket.priority <= priority;
10372
- }
10373
-
10374
- // TODO JSON
10375
- class SyncDataBatch {
10376
- buckets;
10377
- static fromJSON(json) {
10378
- return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
10379
- }
10380
- constructor(buckets) {
10381
- this.buckets = buckets;
10382
- }
10383
- }
10384
-
10385
- /**
10386
- * Thrown when an underlying database connection is closed.
10387
- * This is particularly relevant when worker connections are marked as closed while
10388
- * operations are still in progress.
10389
- */
10390
- class ConnectionClosedError extends Error {
10391
- static NAME = 'ConnectionClosedError';
10392
- static MATCHES(input) {
10393
- /**
10394
- * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
10395
- * check might fail. This also performs a failsafe check.
10396
- * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
10397
- */
10398
- return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
10399
- }
10400
- constructor(message) {
10401
- super(message);
10402
- this.name = ConnectionClosedError.NAME;
10403
- }
10404
- }
10405
-
10406
- // https://www.sqlite.org/lang_expr.html#castexpr
10407
- exports.ColumnType = void 0;
10408
- (function (ColumnType) {
10409
- ColumnType["TEXT"] = "TEXT";
10410
- ColumnType["INTEGER"] = "INTEGER";
10411
- ColumnType["REAL"] = "REAL";
10412
- })(exports.ColumnType || (exports.ColumnType = {}));
10413
- const text = {
10414
- type: exports.ColumnType.TEXT
10415
- };
10416
- const integer = {
10417
- type: exports.ColumnType.INTEGER
10418
- };
10419
- const real = {
10420
- type: exports.ColumnType.REAL
10421
- };
10422
- // powersync-sqlite-core limits the number of column per table to 1999, due to internal SQLite limits.
10423
- // In earlier versions this was limited to 63.
10424
- const MAX_AMOUNT_OF_COLUMNS = 1999;
10425
- const column = {
10426
- text,
10427
- integer,
10428
- real
10429
- };
10430
- class Column {
10431
- options;
10432
- constructor(options) {
10433
- this.options = options;
10434
- }
10435
- get name() {
10436
- return this.options.name;
10437
- }
10438
- get type() {
10439
- return this.options.type;
10440
- }
10441
- toJSON() {
10442
- return {
10443
- name: this.name,
10444
- type: this.type
10445
- };
10446
- }
10447
- }
10448
-
10449
- const DEFAULT_INDEX_COLUMN_OPTIONS = {
10450
- ascending: true
10451
- };
10452
- class IndexedColumn {
10453
- options;
10454
- static createAscending(column) {
10455
- return new IndexedColumn({
10456
- name: column,
10457
- ascending: true
10458
- });
10459
- }
10460
- constructor(options) {
10461
- this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
10462
- }
10463
- get name() {
10464
- return this.options.name;
10465
- }
10466
- get ascending() {
10467
- return this.options.ascending;
10468
- }
10469
- toJSON(table) {
10470
- return {
10471
- name: this.name,
10472
- ascending: this.ascending,
10473
- type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
10474
- };
10475
- }
10476
- }
10477
-
10478
- const DEFAULT_INDEX_OPTIONS = {
10479
- columns: []
10480
- };
10481
- class Index {
10482
- options;
10483
- static createAscending(options, columnNames) {
10484
- return new Index({
10485
- ...options,
10486
- columns: columnNames.map((name) => IndexedColumn.createAscending(name))
11563
+ return raw;
10487
11564
  });
10488
11565
  }
10489
- constructor(options) {
10490
- this.options = options;
10491
- this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
11566
+ async hasMigratedSubkeys() {
11567
+ const { r } = await this.db.get('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [
11568
+ SqliteBucketStorage._subkeyMigrationKey
11569
+ ]);
11570
+ return r != 0;
10492
11571
  }
10493
- get name() {
10494
- return this.options.name;
11572
+ async migrateToFixedSubkeys() {
11573
+ await this.writeTransaction(async (tx) => {
11574
+ await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
11575
+ await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
11576
+ SqliteBucketStorage._subkeyMigrationKey,
11577
+ '1'
11578
+ ]);
11579
+ });
10495
11580
  }
10496
- get columns() {
10497
- return this.options.columns ?? [];
11581
+ static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
11582
+ }
11583
+ function hasMatchingPriority(priority, bucket) {
11584
+ return bucket.priority != null && bucket.priority <= priority;
11585
+ }
11586
+
11587
+ // TODO JSON
11588
+ class SyncDataBatch {
11589
+ buckets;
11590
+ static fromJSON(json) {
11591
+ return new SyncDataBatch(json.buckets.map((bucket) => SyncDataBucket.fromRow(bucket)));
10498
11592
  }
10499
- toJSON(table) {
10500
- return {
10501
- name: this.name,
10502
- columns: this.columns.map((c) => c.toJSON(table))
10503
- };
11593
+ constructor(buckets) {
11594
+ this.buckets = buckets;
10504
11595
  }
10505
11596
  }
10506
11597
 
10507
11598
  /**
10508
- * Instructs PowerSync to sync data into a "raw" table.
10509
- *
10510
- * Since raw tables are not backed by JSON, running complex queries on them may be more efficient. Further, they allow
10511
- * using client-side table and column constraints.
10512
- *
10513
- * To collect local writes to raw tables with PowerSync, custom triggers are required. See
10514
- * {@link https://docs.powersync.com/usage/use-case-examples/raw-tables the documentation} for details and an example on
10515
- * using raw tables.
10516
- *
10517
- * Note that raw tables are only supported when using the new `SyncClientImplementation.rust` sync client.
10518
- *
10519
- * @experimental Please note that this feature is experimental at the moment, and not covered by PowerSync semver or
10520
- * stability guarantees.
11599
+ * Thrown when an underlying database connection is closed.
11600
+ * This is particularly relevant when worker connections are marked as closed while
11601
+ * operations are still in progress.
10521
11602
  */
10522
- class RawTable {
10523
- /**
10524
- * The name of the table.
10525
- *
10526
- * This does not have to match the actual table name in the schema - {@link put} and {@link delete} are free to use
10527
- * another table. Instead, this name is used by the sync client to recognize that operations on this table (as it
10528
- * appears in the source / backend database) are to be handled specially.
10529
- */
10530
- name;
10531
- put;
10532
- delete;
10533
- constructor(name, type) {
10534
- this.name = name;
10535
- this.put = type.put;
10536
- this.delete = type.delete;
11603
+ class ConnectionClosedError extends Error {
11604
+ static NAME = 'ConnectionClosedError';
11605
+ static MATCHES(input) {
11606
+ /**
11607
+ * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
11608
+ * check might fail. This also performs a failsafe check.
11609
+ * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
11610
+ */
11611
+ return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
11612
+ }
11613
+ constructor(message) {
11614
+ super(message);
11615
+ this.name = ConnectionClosedError.NAME;
10537
11616
  }
10538
11617
  }
10539
11618
 
@@ -10581,7 +11660,7 @@ class Schema {
10581
11660
  */
10582
11661
  withRawTables(tables) {
10583
11662
  for (const [name, rawTableDefinition] of Object.entries(tables)) {
10584
- this.rawTables.push(new RawTable(name, rawTableDefinition));
11663
+ this.rawTables.push({ name, ...rawTableDefinition });
10585
11664
  }
10586
11665
  }
10587
11666
  validate() {
@@ -10592,213 +11671,30 @@ class Schema {
10592
11671
  toJSON() {
10593
11672
  return {
10594
11673
  tables: this.tables.map((t) => t.toJSON()),
10595
- raw_tables: this.rawTables
11674
+ raw_tables: this.rawTables.map(Schema.rawTableToJson)
10596
11675
  };
10597
11676
  }
10598
- }
10599
-
10600
- const DEFAULT_TABLE_OPTIONS = {
10601
- indexes: [],
10602
- insertOnly: false,
10603
- localOnly: false,
10604
- trackPrevious: false,
10605
- trackMetadata: false,
10606
- ignoreEmptyUpdates: false
10607
- };
10608
- const InvalidSQLCharacters = /["'%,.#\s[\]]/;
10609
- class Table {
10610
- options;
10611
- _mappedColumns;
10612
- static createLocalOnly(options) {
10613
- return new Table({ ...options, localOnly: true, insertOnly: false });
10614
- }
10615
- static createInsertOnly(options) {
10616
- return new Table({ ...options, localOnly: false, insertOnly: true });
10617
- }
10618
11677
  /**
10619
- * Create a table.
10620
- * @deprecated This was only only included for TableV2 and is no longer necessary.
10621
- * Prefer to use new Table() directly.
11678
+ * Returns a representation of the raw table that is understood by the PowerSync SQLite core extension.
10622
11679
  *
10623
- * TODO remove in the next major release.
10624
- */
10625
- static createTable(name, table) {
10626
- return new Table({
10627
- name,
10628
- columns: table.columns,
10629
- indexes: table.indexes,
10630
- localOnly: table.options.localOnly,
10631
- insertOnly: table.options.insertOnly,
10632
- viewName: table.options.viewName
10633
- });
10634
- }
10635
- constructor(optionsOrColumns, v2Options) {
10636
- if (this.isTableV1(optionsOrColumns)) {
10637
- this.initTableV1(optionsOrColumns);
10638
- }
10639
- else {
10640
- this.initTableV2(optionsOrColumns, v2Options);
10641
- }
10642
- }
10643
- copyWithName(name) {
10644
- return new Table({
10645
- ...this.options,
10646
- name
10647
- });
10648
- }
10649
- isTableV1(arg) {
10650
- return 'columns' in arg && Array.isArray(arg.columns);
10651
- }
10652
- initTableV1(options) {
10653
- this.options = {
10654
- ...options,
10655
- indexes: options.indexes || []
10656
- };
10657
- this.applyDefaultOptions();
10658
- }
10659
- initTableV2(columns, options) {
10660
- const convertedColumns = Object.entries(columns).map(([name, columnInfo]) => new Column({ name, type: columnInfo.type }));
10661
- const convertedIndexes = Object.entries(options?.indexes ?? {}).map(([name, columnNames]) => new Index({
10662
- name,
10663
- columns: columnNames.map((name) => new IndexedColumn({
10664
- name: name.replace(/^-/, ''),
10665
- ascending: !name.startsWith('-')
10666
- }))
10667
- }));
10668
- this.options = {
10669
- name: '',
10670
- columns: convertedColumns,
10671
- indexes: convertedIndexes,
10672
- viewName: options?.viewName,
10673
- insertOnly: options?.insertOnly,
10674
- localOnly: options?.localOnly,
10675
- trackPrevious: options?.trackPrevious,
10676
- trackMetadata: options?.trackMetadata,
10677
- ignoreEmptyUpdates: options?.ignoreEmptyUpdates
11680
+ * The output of this can be passed through `JSON.serialize` and then used in `powersync_create_raw_table_crud_trigger`
11681
+ * to define triggers for this table.
11682
+ */
11683
+ static rawTableToJson(table) {
11684
+ const serialized = {
11685
+ name: table.name,
11686
+ put: table.put,
11687
+ delete: table.delete,
11688
+ clear: table.clear
10678
11689
  };
10679
- this.applyDefaultOptions();
10680
- this._mappedColumns = columns;
10681
- }
10682
- applyDefaultOptions() {
10683
- this.options.insertOnly ??= DEFAULT_TABLE_OPTIONS.insertOnly;
10684
- this.options.localOnly ??= DEFAULT_TABLE_OPTIONS.localOnly;
10685
- this.options.trackPrevious ??= DEFAULT_TABLE_OPTIONS.trackPrevious;
10686
- this.options.trackMetadata ??= DEFAULT_TABLE_OPTIONS.trackMetadata;
10687
- this.options.ignoreEmptyUpdates ??= DEFAULT_TABLE_OPTIONS.ignoreEmptyUpdates;
10688
- }
10689
- get name() {
10690
- return this.options.name;
10691
- }
10692
- get viewNameOverride() {
10693
- return this.options.viewName;
10694
- }
10695
- get viewName() {
10696
- return this.viewNameOverride ?? this.name;
10697
- }
10698
- get columns() {
10699
- return this.options.columns;
10700
- }
10701
- get columnMap() {
10702
- return (this._mappedColumns ??
10703
- this.columns.reduce((hash, column) => {
10704
- hash[column.name] = { type: column.type ?? exports.ColumnType.TEXT };
10705
- return hash;
10706
- }, {}));
10707
- }
10708
- get indexes() {
10709
- return this.options.indexes ?? [];
10710
- }
10711
- get localOnly() {
10712
- return this.options.localOnly;
10713
- }
10714
- get insertOnly() {
10715
- return this.options.insertOnly;
10716
- }
10717
- get trackPrevious() {
10718
- return this.options.trackPrevious;
10719
- }
10720
- get trackMetadata() {
10721
- return this.options.trackMetadata;
10722
- }
10723
- get ignoreEmptyUpdates() {
10724
- return this.options.ignoreEmptyUpdates;
10725
- }
10726
- get internalName() {
10727
- if (this.options.localOnly) {
10728
- return `ps_data_local__${this.name}`;
11690
+ if ('schema' in table) {
11691
+ // We have schema options, those are flattened into the outer JSON object for the core extension.
11692
+ const schema = table.schema;
11693
+ serialized.table_name = schema.tableName ?? table.name;
11694
+ serialized.synced_columns = schema.syncedColumns;
11695
+ Object.assign(serialized, encodeTableOptions(table.schema));
10729
11696
  }
10730
- return `ps_data__${this.name}`;
10731
- }
10732
- get validName() {
10733
- if (InvalidSQLCharacters.test(this.name)) {
10734
- return false;
10735
- }
10736
- if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
10737
- return false;
10738
- }
10739
- return true;
10740
- }
10741
- validate() {
10742
- if (InvalidSQLCharacters.test(this.name)) {
10743
- throw new Error(`Invalid characters in table name: ${this.name}`);
10744
- }
10745
- if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
10746
- throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
10747
- }
10748
- if (this.columns.length > MAX_AMOUNT_OF_COLUMNS) {
10749
- throw new Error(`Table has too many columns. The maximum number of columns is ${MAX_AMOUNT_OF_COLUMNS}.`);
10750
- }
10751
- if (this.trackMetadata && this.localOnly) {
10752
- throw new Error(`Can't include metadata for local-only tables.`);
10753
- }
10754
- if (this.trackPrevious != false && this.localOnly) {
10755
- throw new Error(`Can't include old values for local-only tables.`);
10756
- }
10757
- const columnNames = new Set();
10758
- columnNames.add('id');
10759
- for (const column of this.columns) {
10760
- const { name: columnName } = column;
10761
- if (column.name === 'id') {
10762
- throw new Error(`An id column is automatically added, custom id columns are not supported`);
10763
- }
10764
- if (columnNames.has(columnName)) {
10765
- throw new Error(`Duplicate column ${columnName}`);
10766
- }
10767
- if (InvalidSQLCharacters.test(columnName)) {
10768
- throw new Error(`Invalid characters in column name: ${column.name}`);
10769
- }
10770
- columnNames.add(columnName);
10771
- }
10772
- const indexNames = new Set();
10773
- for (const index of this.indexes) {
10774
- if (indexNames.has(index.name)) {
10775
- throw new Error(`Duplicate index ${index.name}`);
10776
- }
10777
- if (InvalidSQLCharacters.test(index.name)) {
10778
- throw new Error(`Invalid characters in index name: ${index.name}`);
10779
- }
10780
- for (const column of index.columns) {
10781
- if (!columnNames.has(column.name)) {
10782
- throw new Error(`Column ${column.name} not found for index ${index.name}`);
10783
- }
10784
- }
10785
- indexNames.add(index.name);
10786
- }
10787
- }
10788
- toJSON() {
10789
- const trackPrevious = this.trackPrevious;
10790
- return {
10791
- name: this.name,
10792
- view_name: this.viewName,
10793
- local_only: this.localOnly,
10794
- insert_only: this.insertOnly,
10795
- include_old: trackPrevious && (trackPrevious.columns ?? true),
10796
- include_old_only_when_changed: typeof trackPrevious == 'object' && trackPrevious.onlyWhenChanged == true,
10797
- include_metadata: this.trackMetadata,
10798
- ignore_empty_update: this.ignoreEmptyUpdates,
10799
- columns: this.columns.map((c) => c.toJSON()),
10800
- indexes: this.indexes.map((e) => e.toJSON(this))
10801
- };
11697
+ return serialized;
10802
11698
  }
10803
11699
  }
10804
11700
 
@@ -10957,6 +11853,7 @@ const parseQuery = (query, parameters) => {
10957
11853
  return { sqlStatement, parameters: parameters };
10958
11854
  };
10959
11855
 
11856
+ exports.ATTACHMENT_TABLE = ATTACHMENT_TABLE;
10960
11857
  exports.AbortOperation = AbortOperation;
10961
11858
  exports.AbstractPowerSyncDatabase = AbstractPowerSyncDatabase;
10962
11859
  exports.AbstractPowerSyncDatabaseOpenFactory = AbstractPowerSyncDatabaseOpenFactory;
@@ -10964,6 +11861,10 @@ exports.AbstractQueryProcessor = AbstractQueryProcessor;
10964
11861
  exports.AbstractRemote = AbstractRemote;
10965
11862
  exports.AbstractStreamingSyncImplementation = AbstractStreamingSyncImplementation;
10966
11863
  exports.ArrayComparator = ArrayComparator;
11864
+ exports.AttachmentContext = AttachmentContext;
11865
+ exports.AttachmentQueue = AttachmentQueue;
11866
+ exports.AttachmentService = AttachmentService;
11867
+ exports.AttachmentTable = AttachmentTable;
10967
11868
  exports.BaseObserver = BaseObserver;
10968
11869
  exports.Column = Column;
10969
11870
  exports.ConnectionClosedError = ConnectionClosedError;
@@ -11006,17 +11907,18 @@ exports.MEMORY_TRIGGER_CLAIM_MANAGER = MEMORY_TRIGGER_CLAIM_MANAGER;
11006
11907
  exports.OnChangeQueryProcessor = OnChangeQueryProcessor;
11007
11908
  exports.OpType = OpType;
11008
11909
  exports.OplogEntry = OplogEntry;
11009
- exports.RawTable = RawTable;
11010
11910
  exports.Schema = Schema;
11011
11911
  exports.SqliteBucketStorage = SqliteBucketStorage;
11012
11912
  exports.SyncDataBatch = SyncDataBatch;
11013
11913
  exports.SyncDataBucket = SyncDataBucket;
11014
11914
  exports.SyncProgress = SyncProgress;
11015
11915
  exports.SyncStatus = SyncStatus;
11916
+ exports.SyncingService = SyncingService;
11016
11917
  exports.Table = Table;
11017
11918
  exports.TableV2 = TableV2;
11018
11919
  exports.TriggerManagerImpl = TriggerManagerImpl;
11019
11920
  exports.UploadQueueStats = UploadQueueStats;
11921
+ exports.attachmentFromSql = attachmentFromSql;
11020
11922
  exports.column = column;
11021
11923
  exports.compilableQueryWatch = compilableQueryWatch;
11022
11924
  exports.createBaseLogger = createBaseLogger;
@@ -11035,6 +11937,7 @@ exports.isStreamingSyncCheckpointDiff = isStreamingSyncCheckpointDiff;
11035
11937
  exports.isStreamingSyncCheckpointPartiallyComplete = isStreamingSyncCheckpointPartiallyComplete;
11036
11938
  exports.isStreamingSyncData = isStreamingSyncData;
11037
11939
  exports.isSyncNewCheckpointRequest = isSyncNewCheckpointRequest;
11940
+ exports.mutexRunExclusive = mutexRunExclusive;
11038
11941
  exports.parseQuery = parseQuery;
11039
11942
  exports.runOnSchemaChange = runOnSchemaChange;
11040
11943
  exports.sanitizeSQL = sanitizeSQL;