@powersync/shared-internals 0.0.0-dev-20260917114458 → 0.0.0-dev-20261020125654

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 (40) hide show
  1. package/lib/client/BasePowerSyncDatabase.js +24 -14
  2. package/lib/client/BasePowerSyncDatabase.js.map +1 -1
  3. package/lib/client/ConnectionManager.d.ts +1 -0
  4. package/lib/client/ConnectionManager.js +7 -1
  5. package/lib/client/ConnectionManager.js.map +1 -1
  6. package/lib/client/sync/options.js +2 -1
  7. package/lib/client/sync/options.js.map +1 -1
  8. package/lib/client/sync/stream/AbstractRemote.d.ts +5 -5
  9. package/lib/client/sync/stream/AbstractRemote.js +11 -11
  10. package/lib/client/sync/stream/AbstractRemote.js.map +1 -1
  11. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.d.ts +6 -1
  12. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js +37 -6
  13. package/lib/client/sync/stream/AbstractStreamingSyncImplementation.js.map +1 -1
  14. package/lib/client/sync/stream/core-instruction.d.ts +26 -1
  15. package/lib/client/sync/stream/core-instruction.js.map +1 -1
  16. package/lib/client/watched/AbstractQueryProcessor.js +6 -1
  17. package/lib/client/watched/AbstractQueryProcessor.js.map +1 -1
  18. package/lib/db/crud/SyncStatus.d.ts +2 -5
  19. package/lib/db/crud/SyncStatus.js +5 -18
  20. package/lib/db/crud/SyncStatus.js.map +1 -1
  21. package/lib/index.d.ts +2 -0
  22. package/lib/index.js +1 -0
  23. package/lib/index.js.map +1 -1
  24. package/lib/utils/error-serialization.d.ts +27 -0
  25. package/lib/utils/error-serialization.js +90 -0
  26. package/lib/utils/error-serialization.js.map +1 -0
  27. package/lib/version.d.ts +1 -1
  28. package/lib/version.js +1 -1
  29. package/package.json +3 -3
  30. package/src/client/BasePowerSyncDatabase.ts +21 -15
  31. package/src/client/ConnectionManager.ts +8 -1
  32. package/src/client/sync/options.ts +2 -1
  33. package/src/client/sync/stream/AbstractRemote.ts +12 -12
  34. package/src/client/sync/stream/AbstractStreamingSyncImplementation.ts +41 -9
  35. package/src/client/sync/stream/core-instruction.ts +24 -2
  36. package/src/client/watched/AbstractQueryProcessor.ts +7 -1
  37. package/src/db/crud/SyncStatus.ts +6 -19
  38. package/src/index.ts +2 -0
  39. package/src/utils/error-serialization.ts +116 -0
  40. package/src/version.ts +1 -1
@@ -16,7 +16,7 @@ import { POWERSYNC_JS_VERSION } from '../../../version.js';
16
16
  * @internal
17
17
  */
18
18
  export type RemoteConnector = {
19
- fetchCredentials: () => Promise<PowerSyncCredentials | null>;
19
+ fetchCredentials: (signal?: AbortSignal) => Promise<PowerSyncCredentials | null>;
20
20
  invalidateCredentials?: () => void;
21
21
  };
22
22
 
@@ -96,12 +96,12 @@ export abstract class AbstractRemote {
96
96
  *
97
97
  * These credentials may have expired already.
98
98
  */
99
- async getCredentials(): Promise<PowerSyncCredentials | null> {
99
+ async getCredentials(signal?: AbortSignal): Promise<PowerSyncCredentials | null> {
100
100
  if (this.credentials) {
101
101
  return this.credentials;
102
102
  }
103
103
 
104
- return this.prefetchCredentials();
104
+ return this.prefetchCredentials(signal);
105
105
  }
106
106
 
107
107
  /**
@@ -112,8 +112,8 @@ export abstract class AbstractRemote {
112
112
  *
113
113
  * This may be called before the current credentials have expired.
114
114
  */
115
- async prefetchCredentials() {
116
- this.credentials = await this.fetchCredentials();
115
+ async prefetchCredentials(signal?: AbortSignal) {
116
+ this.credentials = await this.fetchCredentials(signal);
117
117
 
118
118
  return this.credentials;
119
119
  }
@@ -124,8 +124,8 @@ export abstract class AbstractRemote {
124
124
  * This should always fetch a fresh set of credentials - don't use cached
125
125
  * values.
126
126
  */
127
- async fetchCredentials() {
128
- const credentials = await this.connector.fetchCredentials();
127
+ async fetchCredentials(signal?: AbortSignal) {
128
+ const credentials = await this.connector.fetchCredentials(signal);
129
129
  if (credentials?.endpoint.match(POWERSYNC_TRAILING_SLASH_MATCH)) {
130
130
  throw new Error(
131
131
  `A trailing forward slash "/" was found in the fetchCredentials endpoint: "${credentials.endpoint}". Remove the trailing forward slash "/" to fix this error.`
@@ -149,8 +149,8 @@ export abstract class AbstractRemote {
149
149
  return `powersync-js/${POWERSYNC_JS_VERSION}`;
150
150
  }
151
151
 
152
- protected async buildRequest(path: string): Promise<PreparedRequest> {
153
- const credentials = await this.getCredentials();
152
+ protected async buildRequest(path: string, signal?: AbortSignal): Promise<PreparedRequest> {
153
+ const credentials = await this.getCredentials(signal);
154
154
  if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
155
155
  throw new Error('PowerSync endpoint not configured');
156
156
  } else if (credentials?.token == null || credentials?.token == '') {
@@ -186,7 +186,7 @@ export abstract class AbstractRemote {
186
186
  body?: string;
187
187
  signal?: AbortSignal;
188
188
  }): Promise<any> {
189
- const request = await this.buildRequest(path);
189
+ const request = await this.buildRequest(path, signal);
190
190
  const res = await this.fetch({
191
191
  resource: request.url,
192
192
  request: {
@@ -240,7 +240,7 @@ export abstract class AbstractRemote {
240
240
  async socketStreamRaw(options: SocketSyncStreamOptions): Promise<SimpleAsyncIterator<Uint8Array>> {
241
241
  const support = await this.loadWebSocketSupport(webSocketPlatform);
242
242
 
243
- const request = await this.buildRequest(options.path);
243
+ const request = await this.buildRequest(options.path, options.abortSignal);
244
244
  request.url = request.url.replace(/^https?:\/\//, function (match) {
245
245
  return match === 'https://' ? 'wss://' : 'ws://';
246
246
  });
@@ -265,7 +265,7 @@ export abstract class AbstractRemote {
265
265
  options: SyncStreamOptions
266
266
  ): Promise<{ isBson: boolean; stream: SimpleAsyncIterator<Uint8Array> }> {
267
267
  const { data, path, abortSignal } = options;
268
- const request = await this.buildRequest(path);
268
+ const request = await this.buildRequest(path, abortSignal);
269
269
 
270
270
  /**
271
271
  * This abort controller will abort pending fetch requests.
@@ -18,7 +18,8 @@ import {
18
18
  CoreSyncStatus,
19
19
  Instruction,
20
20
  NonInterruptingInstruction,
21
- isInterruptingInstruction
21
+ isInterruptingInstruction,
22
+ DiagnosticsEvent
22
23
  } from './core-instruction.js';
23
24
  import {
24
25
  doneResult,
@@ -195,6 +196,12 @@ export abstract class AbstractStreamingSyncImplementation
195
196
  this.crudUpdateListener = undefined;
196
197
  }
197
198
 
199
+ /**
200
+ * Receives a core diagnostics event (emitted only when diagnostics are enabled on the sync stream).
201
+ * Does nothing here; an SDK with diagnostics tooling overrides it to hand the event on.
202
+ */
203
+ protected emitDiagnostics(_event: DiagnosticsEvent): void {}
204
+
198
205
  abstract obtainLock<T>(lockOptions: LockOptions<T>): Promise<T>;
199
206
 
200
207
  private async requestNextCheckpointFromService(abort: AbortSignal): Promise<string> {
@@ -333,22 +340,38 @@ The next upload iteration will be delayed.`
333
340
 
334
341
  const controller = new AbortController();
335
342
  this.abortController = controller;
343
+ const signal = controller.signal;
336
344
  this.streamingSyncPromise = Promise.all([
337
- this.crudUploadLoop(controller.signal, options).catch((error) =>
338
- this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error })
339
- ),
340
- this.streamingSync(controller.signal, options),
341
- this.repostUnacknowledgedCheckpointRequests(controller.signal, options)
345
+ this.crudUploadLoop(signal, options).catch((error) => {
346
+ // Requesting the crud lock when aborted will file, but that's not something worth logging.
347
+ if (signal.reason !== error) {
348
+ this.logger.log({ level: LogLevels.error, message: 'Error in crud upload loop', error });
349
+ }
350
+ }),
351
+ this.streamingSync(signal, options),
352
+ this.repostUnacknowledgedCheckpointRequests(signal, options)
342
353
  ]).finally(() => {
343
354
  // These promises only complete when we want to disconnect. No further sync iteration can resume checkpoint
344
355
  // requests, so fail any that are still pending.
345
356
  this.checkpoints.disconnected();
346
357
  });
347
358
 
348
- // Return a promise that resolves when the connection status is updated to indicate that we're connected. We do this
359
+ // Return a promise that resolves when the connection status is updated to indicate that we're connected, or when
360
+ // this connection attempt is aborted (e.g. superseded by another connect() call) before that happens. We do this
349
361
  // by waiting for connecting to be true and then false again.
350
362
  return new Promise<void>((resolve) => {
351
363
  let sawStartOfConnection = false;
364
+ let settled = false;
365
+
366
+ const finish = () => {
367
+ if (settled) {
368
+ return;
369
+ }
370
+ settled = true;
371
+ disposer();
372
+ signal.removeEventListener('abort', finish);
373
+ resolve();
374
+ };
352
375
 
353
376
  const disposer = this.registerListener({
354
377
  statusChanged: (snapshot) => {
@@ -366,10 +389,13 @@ The next upload iteration will be delayed.`
366
389
  return;
367
390
  }
368
391
 
369
- disposer();
370
- resolve();
392
+ finish();
371
393
  }
372
394
  });
395
+
396
+ // If this attempt is aborted (disconnected) before a `statusChanged` event ever fires - which can happen when
397
+ // the instance never got as far as reporting a connecting status - there's nothing left to wait for.
398
+ signal.addEventListener('abort', finish, { once: true });
373
399
  });
374
400
  }
375
401
 
@@ -713,6 +739,10 @@ The next upload iteration will be delayed.`
713
739
  if (serializedSchema) {
714
740
  options.schema = serializedSchema;
715
741
  }
742
+ if (resolvedOptions.diagnostics) {
743
+ // An empty object enables the core's diagnostics event stream (Option<DiagnosticOptions>).
744
+ options.diagnostics = {};
745
+ }
716
746
 
717
747
  return invokePowerSyncControl(PowerSyncControlCommand.START, JSON.stringify(options));
718
748
  }
@@ -797,6 +827,8 @@ The next upload iteration will be delayed.`
797
827
  // Not necessary on JS platforms.
798
828
  } else if ('DidCompleteSync' in instruction) {
799
829
  syncImplementation.updateJsSyncState({ downloadError: undefined });
830
+ } else if ('HandleDiagnostics' in instruction) {
831
+ syncImplementation.emitDiagnostics(instruction.HandleDiagnostics);
800
832
  }
801
833
  }
802
834
 
@@ -16,7 +16,29 @@ export type NonInterruptingInstruction =
16
16
  | { UpdateSyncStatus: UpdateSyncStatus }
17
17
  | { FetchCredentials: FetchCredentials }
18
18
  | { FlushFileSystem: any }
19
- | { DidCompleteSync: any };
19
+ | { DidCompleteSync: any }
20
+ | { HandleDiagnostics: DiagnosticsEvent };
21
+
22
+ /**
23
+ * Emitted by the core extension when diagnostics are enabled on the sync stream (see
24
+ * {@link https://github.com/powersync-ja/powersync-sqlite-core/blob/main/crates/core/src/sync/diagnostics.rs diagnostics.rs}). Reports detailed
25
+ * per-bucket download state — including the per-bucket `target_count` that is otherwise internal to
26
+ * the core — and inferred column types as data is downloaded.
27
+ */
28
+ export type DiagnosticsEvent =
29
+ | { BucketStateChange: { changes: BucketDownloadState[]; incremental: boolean } }
30
+ | { SchemaChange: ObservedSchemaColumn };
31
+
32
+ export interface BucketDownloadState {
33
+ name: string;
34
+ progress: BucketProgress;
35
+ }
36
+
37
+ export interface ObservedSchemaColumn {
38
+ table: string;
39
+ column: string;
40
+ value_type: 'Null' | 'String' | 'Integer' | 'Real';
41
+ }
20
42
 
21
43
  export interface LogLine {
22
44
  severity: 'DEBUG' | 'INFO' | 'WARNING';
@@ -56,7 +78,7 @@ export interface CoreStreamSubscription {
56
78
 
57
79
  export interface SyncPriorityStatus {
58
80
  priority: number;
59
- last_synced_at: number | number;
81
+ last_synced_at: number | null;
60
82
  has_synced: boolean | null;
61
83
  }
62
84
 
@@ -174,11 +174,17 @@ export abstract class AbstractQueryProcessor<
174
174
  }
175
175
  });
176
176
 
177
- this.disposeListeners = () => {
177
+ const disposeListeners = () => {
178
178
  disposeCloseListener();
179
179
  disposeSchemaListener();
180
180
  };
181
181
 
182
+ if (this._closed) {
183
+ disposeListeners();
184
+ return;
185
+ }
186
+ this.disposeListeners = disposeListeners;
187
+
182
188
  // Initial setup
183
189
  await this.runWithReporting(async () => {
184
190
  await this.updateSettingsInternal(this.options.watchOptions, signal);
@@ -9,6 +9,7 @@ import {
9
9
  } from '@powersync/common';
10
10
  import { CoreStreamSubscription, CoreSyncStatus } from '../../client/sync/stream/core-instruction.js';
11
11
  import { SyncPriorityStatus as CoreSyncPriorityStatus } from '../../client/sync/stream/core-instruction.js';
12
+ import { SerializedRelayError, serializeErrorForRelay } from '../../utils/error-serialization.js';
12
13
  import { SyncProgressImpl } from './SyncProgress.js';
13
14
  import { FULL_SYNC_PRIORITY } from '../../constants.js';
14
15
 
@@ -156,26 +157,12 @@ export class SyncStatusSnapshot implements SyncStatus {
156
157
  };
157
158
  }
158
159
 
159
- /**
160
- * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
161
- * This explicitly serializes errors in the SyncStatus.
162
- */
163
- serializeError(error?: Error) {
160
+ // Must stay deterministic: isEqual() serializes both sides of a comparison.
161
+ serializeError(error?: Error): SerializedRelayError | undefined {
164
162
  if (typeof error == 'undefined') {
165
163
  return undefined;
166
164
  }
167
- const serialized: Error = {
168
- name: error.name,
169
- message: error.message,
170
- stack: error.stack
171
- };
172
- // `Error.cause` can be any value (the spec types it as unknown). Preserve it
173
- // so consumers reading uploadError/downloadError keep the failure context.
174
- // Recurse for Error causes so the whole chain is flattened the same way.
175
- if (typeof error.cause != 'undefined') {
176
- serialized.cause = error.cause instanceof Error ? this.serializeError(error.cause) : error.cause;
177
- }
178
- return serialized;
165
+ return serializeErrorForRelay(error);
179
166
  }
180
167
  }
181
168
 
@@ -210,9 +197,9 @@ class SyncStreamStatusView implements SyncStreamStatus {
210
197
  active: core.active,
211
198
  isDefault: core.is_default,
212
199
  hasExplicitSubscription: core.has_explicit_subscription,
213
- expiresAt: core.expires_at != null ? new Date(core.expires_at * 1000) : null,
200
+ expiresAt: coreTimestampToDate(core.expires_at) ?? null,
214
201
  hasSynced: core.last_synced_at != null,
215
- lastSyncedAt: core.last_synced_at != null ? new Date(core.last_synced_at * 1000) : null
202
+ lastSyncedAt: coreTimestampToDate(core.last_synced_at) ?? null
216
203
  };
217
204
  }
218
205
 
package/src/index.ts CHANGED
@@ -18,6 +18,8 @@ export * from './client/watched/OnChangeQueryProcessor.js';
18
18
 
19
19
  export * from './utils/AbortOperation.js';
20
20
  export * from './utils/compatibility.js';
21
+ export { serializeErrorForRelay } from './utils/error-serialization.js';
22
+ export type { SerializedRelayError, ErrorRelayState } from './utils/error-serialization.js';
21
23
  export * from './utils/ControlledExecutor.js';
22
24
  export * from './utils/mutex.js';
23
25
  export * from './utils/parseQuery.js';
@@ -0,0 +1,116 @@
1
+ // Clone-safe representation of errors crossing a worker boundary.
2
+
3
+ export const RELAY_ERROR_MARKER = '__powersyncError';
4
+
5
+ export type ErrorRelayState = 'serialized' | 'partial' | 'missing';
6
+
7
+ /** Structurally Error-like, but `instanceof Error` is false. */
8
+ export interface SerializedRelayError {
9
+ [RELAY_ERROR_MARKER]: true;
10
+ name: string;
11
+ message: string;
12
+ stack?: string;
13
+ /** SQLite errors, e.g. wa-sqlite's `SQLiteError`. */
14
+ code?: string | number;
15
+ /** HTTP/network error status, e.g. 401. */
16
+ status?: number;
17
+ cause?: SerializedRelayError | string;
18
+ state: ErrorRelayState;
19
+ relay?: { origin: string; sequence: number; errorState: ErrorRelayState; relayedAt: string };
20
+ }
21
+
22
+ const MAX_CAUSE_DEPTH = 5;
23
+
24
+ interface RelayContext {
25
+ lossy: boolean;
26
+ }
27
+
28
+ function isErrorLike(value: unknown): value is Error {
29
+ return (
30
+ typeof value === 'object' &&
31
+ value !== null &&
32
+ typeof (value as { name?: unknown }).name === 'string' &&
33
+ typeof (value as { message?: unknown }).message === 'string'
34
+ );
35
+ }
36
+
37
+ function missing(reason: unknown): SerializedRelayError {
38
+ return {
39
+ [RELAY_ERROR_MARKER]: true,
40
+ name: 'PowerSyncMissingRejectionReason',
41
+ message: `No rejection reason was provided (${reason}).`,
42
+ state: 'missing'
43
+ };
44
+ }
45
+
46
+ function serializeCause(value: unknown, depth: number, ctx: RelayContext): SerializedRelayError | string {
47
+ if (isErrorLike(value)) {
48
+ if (depth <= 0) {
49
+ ctx.lossy = true;
50
+ return '[Max depth reached]';
51
+ }
52
+ return serialize(value, depth, ctx);
53
+ }
54
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
55
+ return String(value);
56
+ }
57
+ ctx.lossy = true;
58
+ return `[Unserializable ${typeof value}]`;
59
+ }
60
+
61
+ function serialize(value: unknown, depth: number, ctx: RelayContext): SerializedRelayError {
62
+ if (isSerializedRelayError(value)) return value;
63
+ if (!isErrorLike(value)) return serializePlain(value);
64
+
65
+ const source = value as Error & { code?: unknown; status?: unknown; cause?: unknown };
66
+ const result: SerializedRelayError = {
67
+ [RELAY_ERROR_MARKER]: true,
68
+ name: source.name || 'Error',
69
+ message: source.message,
70
+ state: 'serialized'
71
+ };
72
+
73
+ const stack = source.stack;
74
+ if (typeof stack === 'string') result.stack = stack;
75
+ // Not standard Error fields, but wa-sqlite errors (code) and HTTP errors (status) carry them and consumers need them as context.
76
+ if (typeof source.code === 'string' || typeof source.code === 'number') result.code = source.code;
77
+ if (typeof source.status === 'number') result.status = source.status;
78
+
79
+ if (source.cause !== undefined) result.cause = serializeCause(source.cause, depth - 1, ctx);
80
+
81
+ if (ctx.lossy && result.state !== 'missing') result.state = 'partial';
82
+ return result;
83
+ }
84
+
85
+ /** Never stringifies an arbitrary object: it may hold credentials or a request payload. */
86
+ function serializePlain(value: unknown): SerializedRelayError {
87
+ const printable = typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';
88
+ return {
89
+ [RELAY_ERROR_MARKER]: true,
90
+ name: typeof value === 'string' ? 'String' : 'Error',
91
+ message: printable ? String(value) : 'Non-Error rejection',
92
+ state: 'serialized'
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Serializes a caught value into a clone-safe shape. Never throws and never
98
+ * returns `undefined` — a missing rejection reason becomes `state: 'missing'`.
99
+ */
100
+ export function serializeErrorForRelay(value: unknown): SerializedRelayError {
101
+ try {
102
+ if (value === undefined || value === null) return missing(value);
103
+ return serialize(value, MAX_CAUSE_DEPTH, { lossy: false });
104
+ } catch {
105
+ return {
106
+ [RELAY_ERROR_MARKER]: true,
107
+ name: 'Error',
108
+ message: 'Unable to serialize rejection reason',
109
+ state: 'partial'
110
+ };
111
+ }
112
+ }
113
+
114
+ export function isSerializedRelayError(value: unknown): value is SerializedRelayError {
115
+ return typeof value === 'object' && value !== null && (value as SerializedRelayError)[RELAY_ERROR_MARKER] === true;
116
+ }
package/src/version.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  // Note: This file gets updated by tool/update_version.js script as part of the Changesets release workflow.
2
2
  // The update happens in the changesets PR, before the package is built.
3
- export const POWERSYNC_JS_VERSION = '1.2.0';
3
+ export const POWERSYNC_JS_VERSION = '1.3.1';