@powersync/common 1.49.0 → 1.50.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.
package/dist/bundle.mjs CHANGED
@@ -1,5 +1,3 @@
1
- import { Mutex } from 'async-mutex';
2
-
3
1
  // https://www.sqlite.org/lang_expr.html#castexpr
4
2
  var ColumnType;
5
3
  (function (ColumnType) {
@@ -657,7 +655,7 @@ class SyncingService {
657
655
  updatedAttachments.push(downloaded);
658
656
  break;
659
657
  case AttachmentState.QUEUED_DELETE:
660
- const deleted = await this.deleteAttachment(attachment);
658
+ const deleted = await this.deleteAttachment(attachment, context);
661
659
  updatedAttachments.push(deleted);
662
660
  break;
663
661
  }
@@ -735,17 +733,16 @@ class SyncingService {
735
733
  * On failure, defers to error handler or archives.
736
734
  *
737
735
  * @param attachment - The attachment record to delete
736
+ * @param context - Attachment context for database operations
738
737
  * @returns Updated attachment record
739
738
  */
740
- async deleteAttachment(attachment) {
739
+ async deleteAttachment(attachment, context) {
741
740
  try {
742
741
  await this.remoteStorage.deleteFile(attachment);
743
742
  if (attachment.localUri) {
744
743
  await this.localStorage.deleteFile(attachment.localUri);
745
744
  }
746
- await this.attachmentService.withContext(async (ctx) => {
747
- await ctx.deleteAttachment(attachment.id);
748
- });
745
+ await context.deleteAttachment(attachment.id);
749
746
  return {
750
747
  ...attachment,
751
748
  state: AttachmentState.ARCHIVED
@@ -783,32 +780,108 @@ class SyncingService {
783
780
  }
784
781
 
785
782
  /**
786
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
783
+ * An asynchronous mutex implementation.
784
+ *
785
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
787
786
  */
788
- async function mutexRunExclusive(mutex, callback, options) {
789
- return new Promise((resolve, reject) => {
790
- const timeout = options?.timeoutMs;
791
- let timedOut = false;
792
- const timeoutId = timeout
793
- ? setTimeout(() => {
794
- timedOut = true;
795
- reject(new Error('Timeout waiting for lock'));
796
- }, timeout)
797
- : undefined;
798
- mutex.runExclusive(async () => {
799
- if (timeoutId) {
800
- clearTimeout(timeoutId);
801
- }
802
- if (timedOut)
803
- return;
804
- try {
805
- resolve(await callback());
787
+ class Mutex {
788
+ inCriticalSection = false;
789
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
790
+ // aborted waiters from the middle of the list efficiently.
791
+ firstWaiter;
792
+ lastWaiter;
793
+ addWaiter(onAcquire) {
794
+ const node = {
795
+ isActive: true,
796
+ onAcquire,
797
+ prev: this.lastWaiter
798
+ };
799
+ if (this.lastWaiter) {
800
+ this.lastWaiter.next = node;
801
+ this.lastWaiter = node;
802
+ }
803
+ else {
804
+ // First waiter
805
+ this.lastWaiter = this.firstWaiter = node;
806
+ }
807
+ return node;
808
+ }
809
+ deactivateWaiter(waiter) {
810
+ const { prev, next } = waiter;
811
+ waiter.isActive = false;
812
+ if (prev)
813
+ prev.next = next;
814
+ if (next)
815
+ next.prev = prev;
816
+ if (waiter == this.firstWaiter)
817
+ this.firstWaiter = next;
818
+ if (waiter == this.lastWaiter)
819
+ this.lastWaiter = prev;
820
+ }
821
+ acquire(abort) {
822
+ return new Promise((resolve, reject) => {
823
+ function rejectAborted() {
824
+ reject(abort?.reason ?? new Error('Mutex acquire aborted'));
806
825
  }
807
- catch (ex) {
808
- reject(ex);
826
+ if (abort?.aborted) {
827
+ return rejectAborted();
828
+ }
829
+ let holdsMutex = false;
830
+ const markCompleted = () => {
831
+ if (!holdsMutex)
832
+ return;
833
+ holdsMutex = false;
834
+ const waiter = this.firstWaiter;
835
+ if (waiter) {
836
+ this.deactivateWaiter(waiter);
837
+ // Still in critical section, but owned by next waiter now.
838
+ waiter.onAcquire();
839
+ }
840
+ else {
841
+ this.inCriticalSection = false;
842
+ }
843
+ };
844
+ if (!this.inCriticalSection) {
845
+ this.inCriticalSection = true;
846
+ holdsMutex = true;
847
+ return resolve(markCompleted);
848
+ }
849
+ else {
850
+ let node;
851
+ const onAbort = () => {
852
+ abort?.removeEventListener('abort', onAbort);
853
+ if (node.isActive) {
854
+ this.deactivateWaiter(node);
855
+ rejectAborted();
856
+ }
857
+ };
858
+ node = this.addWaiter(() => {
859
+ abort?.removeEventListener('abort', onAbort);
860
+ holdsMutex = true;
861
+ resolve(markCompleted);
862
+ });
863
+ abort?.addEventListener('abort', onAbort);
809
864
  }
810
865
  });
811
- });
866
+ }
867
+ async runExclusive(fn, abort) {
868
+ const returnMutex = await this.acquire(abort);
869
+ try {
870
+ return await fn();
871
+ }
872
+ finally {
873
+ returnMutex();
874
+ }
875
+ }
876
+ }
877
+ function timeoutSignal(timeout) {
878
+ if (timeout == null)
879
+ return;
880
+ if ('timeout' in AbortSignal)
881
+ return AbortSignal.timeout(timeout);
882
+ const controller = new AbortController();
883
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
884
+ return controller.signal;
812
885
  }
813
886
 
814
887
  /**
@@ -857,7 +930,7 @@ class AttachmentService {
857
930
  * Executes a callback with exclusive access to the attachment context.
858
931
  */
859
932
  async withContext(callback) {
860
- return mutexRunExclusive(this.mutex, async () => {
933
+ return this.mutex.runExclusive(async () => {
861
934
  return callback(this.context);
862
935
  });
863
936
  }
@@ -893,9 +966,15 @@ class AttachmentQueue {
893
966
  tableName;
894
967
  /** Logger instance for diagnostic information */
895
968
  logger;
896
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
969
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
970
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
897
971
  syncIntervalMs = 30 * 1000;
898
- /** Duration in milliseconds to throttle sync operations */
972
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
973
+ * When attachment records change, a watch query detects the change and triggers a sync.
974
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
975
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
976
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
977
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
899
978
  syncThrottleDuration;
900
979
  /** Whether to automatically download remote attachments. Default: true */
901
980
  downloadAttachments = true;
@@ -919,8 +998,8 @@ class AttachmentQueue {
919
998
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
920
999
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
921
1000
  * @param options.logger - Logger instance. Defaults to db.logger
922
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
923
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
1001
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
1002
+ * @param options.syncThrottleDuration - Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30
924
1003
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
925
1004
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
926
1005
  */
@@ -10581,7 +10660,7 @@ function requireDist () {
10581
10660
 
10582
10661
  var distExports = requireDist();
10583
10662
 
10584
- var version = "1.49.0";
10663
+ var version = "1.50.0";
10585
10664
  var PACKAGE = {
10586
10665
  version: version};
10587
10666
 
@@ -13438,6 +13517,10 @@ SELECT * FROM crud_entries;
13438
13517
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
13439
13518
  * and optionally return results.
13440
13519
  *
13520
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
13521
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
13522
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
13523
+ *
13441
13524
  * @param sql The SQL query to execute
13442
13525
  * @param parameters Optional array of parameters to bind to the query
13443
13526
  * @returns The query result as an object with structured key-value pairs
@@ -13534,7 +13617,7 @@ SELECT * FROM crud_entries;
13534
13617
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
13535
13618
  await this.waitForReady();
13536
13619
  return this.database.readTransaction(async (tx) => {
13537
- const res = await callback({ ...tx });
13620
+ const res = await callback(tx);
13538
13621
  await tx.rollback();
13539
13622
  return res;
13540
13623
  }, { timeoutMs: lockTimeout });
@@ -14511,5 +14594,5 @@ const parseQuery = (query, parameters) => {
14511
14594
  return { sqlStatement, parameters: parameters };
14512
14595
  };
14513
14596
 
14514
- export { ATTACHMENT_TABLE, 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_PRESSURE_LIMITS, 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, DataStream, 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, OnChangeQueryProcessor, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, mutexRunExclusive, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID };
14597
+ export { ATTACHMENT_TABLE, 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_PRESSURE_LIMITS, 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, DataStream, 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, OpType, OpTypeEnum, OplogEntry, PSInternalTable, PowerSyncControlCommand, RowUpdateType, Schema, SqliteBucketStorage, SyncClientImplementation, SyncDataBatch, SyncDataBucket, SyncProgress, SyncStatus, SyncStreamConnectionMethod, SyncingService, Table, TableV2, TriggerManagerImpl, UpdateType, UploadQueueStats, WatchedQueryListenerEvent, attachmentFromSql, column, compilableQueryWatch, createBaseLogger, createLogger, extractTableUpdates, isBatchedUpdateNotification, isContinueCheckpointRequest, isDBAdapter, isPowerSyncDatabaseOptionsWithSettings, isSQLOpenFactory, isSQLOpenOptions, isStreamingKeepalive, isStreamingSyncCheckpoint, isStreamingSyncCheckpointComplete, isStreamingSyncCheckpointDiff, isStreamingSyncCheckpointPartiallyComplete, isStreamingSyncData, isSyncNewCheckpointRequest, parseQuery, runOnSchemaChange, sanitizeSQL, sanitizeUUID, timeoutSignal };
14515
14598
  //# sourceMappingURL=bundle.mjs.map