@powersync/shared-internals 0.0.0-dev-20260827080125

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 (152) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +5 -0
  3. package/dist/websockets.mjs +7558 -0
  4. package/dist/websockets.mjs.map +1 -0
  5. package/dist/websockets.node.mjs +5189 -0
  6. package/dist/websockets.node.mjs.map +1 -0
  7. package/legacy/sync_protocol.d.ts +103 -0
  8. package/lib/client/BasePowerSyncDatabase.d.ts +156 -0
  9. package/lib/client/BasePowerSyncDatabase.js +654 -0
  10. package/lib/client/BasePowerSyncDatabase.js.map +1 -0
  11. package/lib/client/ConnectionManager.d.ts +120 -0
  12. package/lib/client/ConnectionManager.js +324 -0
  13. package/lib/client/ConnectionManager.js.map +1 -0
  14. package/lib/client/CustomQuery.d.ts +21 -0
  15. package/lib/client/CustomQuery.js +43 -0
  16. package/lib/client/CustomQuery.js.map +1 -0
  17. package/lib/client/sync/CheckpointRequestImpl.d.ts +11 -0
  18. package/lib/client/sync/CheckpointRequestImpl.js +42 -0
  19. package/lib/client/sync/CheckpointRequestImpl.js.map +1 -0
  20. package/lib/client/sync/bucket/BucketStorageAdapter.d.ts +58 -0
  21. package/lib/client/sync/bucket/BucketStorageAdapter.js +47 -0
  22. package/lib/client/sync/bucket/BucketStorageAdapter.js.map +1 -0
  23. package/lib/client/sync/bucket/CrudEntry.d.ts +46 -0
  24. package/lib/client/sync/bucket/CrudEntry.js +60 -0
  25. package/lib/client/sync/bucket/CrudEntry.js.map +1 -0
  26. package/lib/client/sync/bucket/SqliteBucketStorage.d.ts +32 -0
  27. package/lib/client/sync/bucket/SqliteBucketStorage.js +160 -0
  28. package/lib/client/sync/bucket/SqliteBucketStorage.js.map +1 -0
  29. package/lib/client/sync/options.d.ts +9 -0
  30. package/lib/client/sync/options.js +17 -0
  31. package/lib/client/sync/options.js.map +1 -0
  32. package/lib/client/sync/stream/AbstractRemote.d.ts +131 -0
  33. package/lib/client/sync/stream/AbstractRemote.js +270 -0
  34. package/lib/client/sync/stream/AbstractRemote.js.map +1 -0
  35. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +156 -0
  36. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +740 -0
  37. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -0
  38. package/lib/client/sync/stream/CheckpointState.d.ts +44 -0
  39. package/lib/client/sync/stream/CheckpointState.js +106 -0
  40. package/lib/client/sync/stream/CheckpointState.js.map +1 -0
  41. package/lib/client/sync/stream/WebSocketSupport.d.ts +26 -0
  42. package/lib/client/sync/stream/WebSocketSupport.js +198 -0
  43. package/lib/client/sync/stream/WebSocketSupport.js.map +1 -0
  44. package/lib/client/sync/stream/WebsocketClientTransport.d.ts +15 -0
  45. package/lib/client/sync/stream/WebsocketClientTransport.js +62 -0
  46. package/lib/client/sync/stream/WebsocketClientTransport.js.map +1 -0
  47. package/lib/client/sync/stream/core-instruction.d.ts +81 -0
  48. package/lib/client/sync/stream/core-instruction.js +4 -0
  49. package/lib/client/sync/stream/core-instruction.js.map +1 -0
  50. package/lib/client/triggers/MemoryTriggerClaimManager.d.ts +6 -0
  51. package/lib/client/triggers/MemoryTriggerClaimManager.js +21 -0
  52. package/lib/client/triggers/MemoryTriggerClaimManager.js.map +1 -0
  53. package/lib/client/triggers/TriggerManagerImpl.d.ts +68 -0
  54. package/lib/client/triggers/TriggerManagerImpl.js +415 -0
  55. package/lib/client/triggers/TriggerManagerImpl.js.map +1 -0
  56. package/lib/client/watched/AbstractQueryProcessor.d.ts +68 -0
  57. package/lib/client/watched/AbstractQueryProcessor.js +155 -0
  58. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -0
  59. package/lib/client/watched/DifferentialQueryProcessor.d.ts +50 -0
  60. package/lib/client/watched/DifferentialQueryProcessor.js +174 -0
  61. package/lib/client/watched/DifferentialQueryProcessor.js.map +1 -0
  62. package/lib/client/watched/OnChangeQueryProcessor.d.ts +22 -0
  63. package/lib/client/watched/OnChangeQueryProcessor.js +80 -0
  64. package/lib/client/watched/OnChangeQueryProcessor.js.map +1 -0
  65. package/lib/client/watched/WatchedQuery.d.ts +9 -0
  66. package/lib/client/watched/WatchedQuery.js +12 -0
  67. package/lib/client/watched/WatchedQuery.js.map +1 -0
  68. package/lib/constants.d.ts +5 -0
  69. package/lib/constants.js +6 -0
  70. package/lib/constants.js.map +1 -0
  71. package/lib/db/ConnectionClosedError.d.ts +12 -0
  72. package/lib/db/ConnectionClosedError.js +23 -0
  73. package/lib/db/ConnectionClosedError.js.map +1 -0
  74. package/lib/db/crud/SyncProgress.d.ts +10 -0
  75. package/lib/db/crud/SyncProgress.js +33 -0
  76. package/lib/db/crud/SyncProgress.js.map +1 -0
  77. package/lib/db/crud/SyncStatus.d.ts +48 -0
  78. package/lib/db/crud/SyncStatus.js +178 -0
  79. package/lib/db/crud/SyncStatus.js.map +1 -0
  80. package/lib/db/openDatabase.d.ts +7 -0
  81. package/lib/db/openDatabase.js +22 -0
  82. package/lib/db/openDatabase.js.map +1 -0
  83. package/lib/index.d.ts +22 -0
  84. package/lib/index.js +22 -0
  85. package/lib/index.js.map +1 -0
  86. package/lib/utils/AbortOperation.d.ts +11 -0
  87. package/lib/utils/AbortOperation.js +21 -0
  88. package/lib/utils/AbortOperation.js.map +1 -0
  89. package/lib/utils/ControlledExecutor.d.ts +31 -0
  90. package/lib/utils/ControlledExecutor.js +58 -0
  91. package/lib/utils/ControlledExecutor.js.map +1 -0
  92. package/lib/utils/MetaBaseObserver.d.ts +11 -0
  93. package/lib/utils/MetaBaseObserver.js +51 -0
  94. package/lib/utils/MetaBaseObserver.js.map +1 -0
  95. package/lib/utils/async.d.ts +46 -0
  96. package/lib/utils/async.js +147 -0
  97. package/lib/utils/async.js.map +1 -0
  98. package/lib/utils/compatibility.d.ts +8 -0
  99. package/lib/utils/compatibility.js +9 -0
  100. package/lib/utils/compatibility.js.map +1 -0
  101. package/lib/utils/mutex.d.ts +42 -0
  102. package/lib/utils/mutex.js +150 -0
  103. package/lib/utils/mutex.js.map +1 -0
  104. package/lib/utils/parseQuery.d.ts +12 -0
  105. package/lib/utils/parseQuery.js +20 -0
  106. package/lib/utils/parseQuery.js.map +1 -0
  107. package/lib/utils/queue.d.ts +16 -0
  108. package/lib/utils/queue.js +42 -0
  109. package/lib/utils/queue.js.map +1 -0
  110. package/lib/utils/stream_transform.d.ts +42 -0
  111. package/lib/utils/stream_transform.js +227 -0
  112. package/lib/utils/stream_transform.js.map +1 -0
  113. package/lib/version.d.ts +1 -0
  114. package/lib/version.js +4 -0
  115. package/lib/version.js.map +1 -0
  116. package/package.json +68 -0
  117. package/src/client/BasePowerSyncDatabase.ts +898 -0
  118. package/src/client/ConnectionManager.ts +441 -0
  119. package/src/client/CustomQuery.ts +60 -0
  120. package/src/client/sync/CheckpointRequestImpl.ts +54 -0
  121. package/src/client/sync/bucket/BucketStorageAdapter.ts +85 -0
  122. package/src/client/sync/bucket/CrudEntry.ts +116 -0
  123. package/src/client/sync/bucket/SqliteBucketStorage.ts +203 -0
  124. package/src/client/sync/options.ts +25 -0
  125. package/src/client/sync/stream/AbstractRemote.ts +388 -0
  126. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +948 -0
  127. package/src/client/sync/stream/CheckpointState.ts +136 -0
  128. package/src/client/sync/stream/WebSocketSupport.ts +259 -0
  129. package/src/client/sync/stream/WebsocketClientTransport.ts +82 -0
  130. package/src/client/sync/stream/core-instruction.ts +85 -0
  131. package/src/client/triggers/MemoryTriggerClaimManager.ts +25 -0
  132. package/src/client/triggers/TriggerManagerImpl.ts +538 -0
  133. package/src/client/watched/AbstractQueryProcessor.ts +231 -0
  134. package/src/client/watched/DifferentialQueryProcessor.ts +226 -0
  135. package/src/client/watched/OnChangeQueryProcessor.ts +108 -0
  136. package/src/client/watched/WatchedQuery.ts +14 -0
  137. package/src/constants.ts +6 -0
  138. package/src/db/ConnectionClosedError.ts +25 -0
  139. package/src/db/crud/SyncProgress.ts +39 -0
  140. package/src/db/crud/SyncStatus.ts +234 -0
  141. package/src/db/openDatabase.ts +23 -0
  142. package/src/index.ts +24 -0
  143. package/src/utils/AbortOperation.ts +19 -0
  144. package/src/utils/ControlledExecutor.ts +81 -0
  145. package/src/utils/MetaBaseObserver.ts +65 -0
  146. package/src/utils/async.ts +185 -0
  147. package/src/utils/compatibility.ts +9 -0
  148. package/src/utils/mutex.ts +186 -0
  149. package/src/utils/parseQuery.ts +31 -0
  150. package/src/utils/queue.ts +48 -0
  151. package/src/utils/stream_transform.ts +276 -0
  152. package/src/version.ts +3 -0
@@ -0,0 +1,116 @@
1
+ import { CrudEntry, UpdateType } from '@powersync/common';
2
+
3
+ /**
4
+ * @internal
5
+ */
6
+ export type CrudEntryJSON = {
7
+ id: string;
8
+ data: string;
9
+ tx_id?: number;
10
+ };
11
+
12
+ type CrudEntryDataJSON = {
13
+ data: Record<string, any>;
14
+ old?: Record<string, any>;
15
+ op: UpdateType;
16
+ type: string;
17
+ id: string;
18
+ metadata?: string;
19
+ };
20
+
21
+ /**
22
+ * The output JSON seems to be a third type of JSON, not the same as the input JSON.
23
+ */
24
+ type CrudEntryOutputJSON = {
25
+ op_id: number;
26
+ op: UpdateType;
27
+ type: string;
28
+ id: string;
29
+ tx_id?: number;
30
+ data?: Record<string, any>;
31
+ old?: Record<string, any>;
32
+ metadata?: string;
33
+ };
34
+
35
+ /**
36
+ * A single client-side change.
37
+ *
38
+ * @public
39
+ */
40
+ export class CrudEntryImpl implements CrudEntry {
41
+ clientId: number;
42
+ id: string;
43
+ op: UpdateType;
44
+ opData?: Record<string, any>;
45
+ previousValues?: Record<string, any>;
46
+ table: string;
47
+ transactionId?: number;
48
+ metadata?: string;
49
+
50
+ static fromRow(dbRow: CrudEntryJSON): CrudEntry {
51
+ const data: CrudEntryDataJSON = JSON.parse(dbRow.data);
52
+ return new CrudEntryImpl(
53
+ parseInt(dbRow.id),
54
+ data.op,
55
+ data.type,
56
+ data.id,
57
+ dbRow.tx_id,
58
+ data.data,
59
+ data.old,
60
+ data.metadata
61
+ );
62
+ }
63
+
64
+ constructor(
65
+ clientId: number,
66
+ op: UpdateType,
67
+ table: string,
68
+ id: string,
69
+ transactionId?: number,
70
+ opData?: Record<string, any>,
71
+ previousValues?: Record<string, any>,
72
+ metadata?: string
73
+ ) {
74
+ this.clientId = clientId;
75
+ this.id = id;
76
+ this.op = op;
77
+ this.opData = opData;
78
+ this.table = table;
79
+ this.transactionId = transactionId;
80
+ this.previousValues = previousValues;
81
+ this.metadata = metadata;
82
+ }
83
+
84
+ toJSON(): CrudEntryOutputJSON {
85
+ return {
86
+ op_id: this.clientId,
87
+ op: this.op,
88
+ type: this.table,
89
+ id: this.id,
90
+ tx_id: this.transactionId,
91
+ data: this.opData,
92
+ old: this.previousValues,
93
+ metadata: this.metadata
94
+ };
95
+ }
96
+
97
+ equals(entry: CrudEntry) {
98
+ return JSON.stringify(this.toComparisonArray()) == JSON.stringify(entry.toComparisonArray());
99
+ }
100
+
101
+ /**
102
+ * Generates an array for use in deep comparison operations
103
+ */
104
+ toComparisonArray(): unknown[] {
105
+ return [
106
+ this.transactionId,
107
+ this.clientId,
108
+ this.op,
109
+ this.table,
110
+ this.id,
111
+ this.opData,
112
+ this.previousValues,
113
+ this.metadata
114
+ ];
115
+ }
116
+ }
@@ -0,0 +1,203 @@
1
+ import {
2
+ BaseObserver,
3
+ LogLevels,
4
+ PowerSyncLogger,
5
+ DBAdapter,
6
+ Transaction,
7
+ CrudEntry,
8
+ CrudBatch,
9
+ SqliteValue
10
+ } from '@powersync/common';
11
+
12
+ import {
13
+ BucketStorageAdapter,
14
+ BucketStorageListener,
15
+ PowerSyncControlCommand,
16
+ PSInternalTable,
17
+ rawPowerSyncControl,
18
+ targetCheckpointRequestId
19
+ } from './BucketStorageAdapter.js';
20
+ import { CrudEntryImpl, CrudEntryJSON } from './CrudEntry.js';
21
+ import { MAX_OP_ID } from '../../../constants.js';
22
+
23
+ /**
24
+ * @internal
25
+ */
26
+ export class SqliteBucketStorage extends BaseObserver<BucketStorageListener> implements BucketStorageAdapter {
27
+ private updateListener: () => void;
28
+ private _clientId?: Promise<string>;
29
+
30
+ constructor(
31
+ private db: DBAdapter,
32
+ private logger: PowerSyncLogger
33
+ ) {
34
+ super();
35
+ this.updateListener = db.registerListener({
36
+ tablesUpdated: ({ tables }) => {
37
+ if (tables.includes(PSInternalTable.CRUD)) {
38
+ this.iterateListeners((l) => l.crudUpdate?.());
39
+ }
40
+ }
41
+ });
42
+ }
43
+
44
+ async dispose() {
45
+ this.updateListener?.();
46
+ }
47
+
48
+ async _getClientId() {
49
+ const row = await this.db.get<{ client_id: string }>('SELECT powersync_client_id() as client_id');
50
+ return row['client_id'];
51
+ }
52
+
53
+ getClientId() {
54
+ if (this._clientId == null) {
55
+ this._clientId = this._getClientId();
56
+ }
57
+ return this._clientId!;
58
+ }
59
+
60
+ async updateLocalTarget(cb: () => Promise<string>): Promise<boolean> {
61
+ const sequenceBefore = await this.db.readTransaction(async (tx): Promise<number | undefined> => {
62
+ const currentCheckpoint = await targetCheckpointRequestId(tx);
63
+ if (currentCheckpoint != MAX_OP_ID) return;
64
+
65
+ const rs = await tx.getOptional<{ seq: number }>("SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'");
66
+ return rs?.seq;
67
+ });
68
+
69
+ if (sequenceBefore == null) {
70
+ // Nothing to update
71
+ return false;
72
+ }
73
+
74
+ const opId = await cb();
75
+
76
+ return this.writeTransaction(async (tx) => {
77
+ const anyData = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');
78
+ if (anyData.rows?.length) {
79
+ // if isNotEmpty
80
+ this.logger.log({
81
+ level: LogLevels.debug,
82
+ message: `New data uploaded since write checkpoint ${opId} - need new write checkpoint`
83
+ });
84
+ return false;
85
+ }
86
+
87
+ const { seq: seqAfter } = await tx.get<{ seq: number }>(
88
+ "SELECT seq FROM main.sqlite_sequence WHERE name = 'ps_crud'"
89
+ );
90
+
91
+ if (seqAfter != sequenceBefore) {
92
+ this.logger.log({
93
+ level: LogLevels.debug,
94
+ message: `New data uploaded since write checpoint ${opId} - need new write checkpoint (sequence updated)`
95
+ });
96
+
97
+ // New crud data may have been uploaded since we got the checkpoint. Abort.
98
+ return false;
99
+ }
100
+
101
+ this.logger.log({
102
+ level: LogLevels.debug,
103
+ message: `Updating target write checkpoint to ${opId}`
104
+ });
105
+ await targetCheckpointRequestId(tx, opId);
106
+ return true;
107
+ });
108
+ }
109
+
110
+ readCheckpointRequestId(variant: 'next' | 'current' | 'seed', payload: string | null = null): Promise<string> {
111
+ // This needs to run in a write transaction because some checkpoint request reads interact with sync client state
112
+ // bound to the write connection.
113
+ return this.db.writeTransaction(async (tx) => {
114
+ return (await rawPowerSyncControl(tx, `${variant}_checkpoint_request_id`, payload))!;
115
+ });
116
+ }
117
+
118
+ async nextCrudItem(): Promise<CrudEntry | undefined> {
119
+ const next = await this.db.getOptional<CrudEntryJSON>('SELECT * FROM ps_crud ORDER BY id ASC LIMIT 1');
120
+ if (!next) {
121
+ return;
122
+ }
123
+ return CrudEntryImpl.fromRow(next);
124
+ }
125
+
126
+ async hasCrud(): Promise<boolean> {
127
+ const anyData = await this.db.getOptional('SELECT 1 FROM ps_crud LIMIT 1');
128
+ return !!anyData;
129
+ }
130
+
131
+ /**
132
+ * Get a batch of objects to send to the server.
133
+ * When the objects are successfully sent to the server, call .complete()
134
+ */
135
+ async getCrudBatch(limit: number = 100): Promise<CrudBatch | null> {
136
+ if (!(await this.hasCrud())) {
137
+ return null;
138
+ }
139
+
140
+ const crudResult = await this.db.getAll<CrudEntryJSON>('SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?', [limit]);
141
+
142
+ const all: CrudEntry[] = [];
143
+ for (const row of crudResult) {
144
+ all.push(CrudEntryImpl.fromRow(row));
145
+ }
146
+
147
+ if (all.length === 0) {
148
+ return null;
149
+ }
150
+
151
+ const last = all[all.length - 1];
152
+ return {
153
+ crud: all,
154
+ haveMore: true,
155
+ complete: async (writeCheckpoint?: string) => {
156
+ return this.handleCrudCheckpoint(last.clientId, writeCheckpoint);
157
+ }
158
+ };
159
+ }
160
+
161
+ handleCrudCheckpoint(lastClientId: number, writeCheckpoint?: string): Promise<void> {
162
+ return this.writeTransaction(async (tx) => {
163
+ await tx.execute('DELETE FROM ps_crud WHERE id <= ?', [lastClientId]);
164
+ if (writeCheckpoint) {
165
+ const crudResult = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1');
166
+ if (crudResult.rows?.length) {
167
+ await targetCheckpointRequestId(tx, writeCheckpoint);
168
+ }
169
+ } else {
170
+ await targetCheckpointRequestId(tx, MAX_OP_ID);
171
+ }
172
+ });
173
+ }
174
+
175
+ async writeTransaction<T>(callback: (tx: Transaction) => Promise<T>, options?: { timeoutMs: number }): Promise<T> {
176
+ return this.db.writeTransaction(callback, options);
177
+ }
178
+
179
+ async control(op: PowerSyncControlCommand, payload: string | Uint8Array | ArrayBuffer | null): Promise<string> {
180
+ return await this.writeTransaction(async (tx) => {
181
+ return (await rawPowerSyncControl(tx, op, payload as SqliteValue))!;
182
+ });
183
+ }
184
+
185
+ async hasMigratedSubkeys(): Promise<boolean> {
186
+ const { r } = await this.db.get<{ r: number }>('SELECT EXISTS(SELECT * FROM ps_kv WHERE key = ?) as r', [
187
+ SqliteBucketStorage._subkeyMigrationKey
188
+ ]);
189
+ return r != 0;
190
+ }
191
+
192
+ async migrateToFixedSubkeys(): Promise<void> {
193
+ await this.writeTransaction(async (tx) => {
194
+ await tx.execute('UPDATE ps_oplog SET key = powersync_remove_duplicate_key_encoding(key);');
195
+ await tx.execute('INSERT OR REPLACE INTO ps_kv (key, value) VALUES (?, ?);', [
196
+ SqliteBucketStorage._subkeyMigrationKey,
197
+ '1'
198
+ ]);
199
+ });
200
+ }
201
+
202
+ static _subkeyMigrationKey = 'powersync_js_migrated_subkeys';
203
+ }
@@ -0,0 +1,25 @@
1
+ import { FetchStrategy, SyncOptions, SyncStreamConnectionMethod } from '@powersync/common';
2
+
3
+ /**
4
+ * @internal
5
+ */
6
+ export type ResolvedSyncOptions = Required<SyncOptions>;
7
+
8
+ /**
9
+ * @internal
10
+ */
11
+ export function resolveSyncOptions(
12
+ options: SyncOptions,
13
+ defaultConnectionMethod: SyncStreamConnectionMethod
14
+ ): ResolvedSyncOptions {
15
+ return {
16
+ appMetadata: options.appMetadata ?? {},
17
+ connectionMethod: options.connectionMethod ?? defaultConnectionMethod,
18
+ fetchStrategy: options.fetchStrategy ?? FetchStrategy.Buffered,
19
+ params: options.params ?? {},
20
+ includeDefaultStreams: options.includeDefaultStreams ?? true,
21
+ retryDelayMs: options.retryDelayMs ?? 5000,
22
+ crudUploadThrottleMs: options.crudUploadThrottleMs ?? 1000,
23
+ checkpointMode: options.checkpointMode ?? 'legacy'
24
+ };
25
+ }