@powersync/react 2.0.1 → 2.1.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 (69) hide show
  1. package/README.md +15 -0
  2. package/lib/hooks/PowerSyncContext.d.ts +4 -2
  3. package/lib/hooks/PowerSyncContext.js +7 -1
  4. package/lib/hooks/PowerSyncContext.js.map +1 -1
  5. package/lib/hooks/streams.d.ts +4 -3
  6. package/lib/hooks/streams.js +11 -10
  7. package/lib/hooks/streams.js.map +1 -1
  8. package/lib/hooks/suspense/SuspenseQueryCache.d.ts +46 -0
  9. package/lib/hooks/suspense/SuspenseQueryCache.js +231 -0
  10. package/lib/hooks/suspense/SuspenseQueryCache.js.map +1 -0
  11. package/lib/hooks/suspense/useSuspenseQuery.d.ts +3 -3
  12. package/lib/hooks/suspense/useSuspenseQuery.js +28 -7
  13. package/lib/hooks/suspense/useSuspenseQuery.js.map +1 -1
  14. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +60 -24
  15. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js.map +1 -1
  16. package/lib/hooks/useStatus.d.ts +7 -1
  17. package/lib/hooks/useStatus.js +11 -6
  18. package/lib/hooks/useStatus.js.map +1 -1
  19. package/lib/hooks/watched/QueryRunner.d.ts +90 -0
  20. package/lib/hooks/watched/QueryRunner.js +366 -0
  21. package/lib/hooks/watched/QueryRunner.js.map +1 -0
  22. package/lib/hooks/watched/useQuery.js +14 -40
  23. package/lib/hooks/watched/useQuery.js.map +1 -1
  24. package/lib/hooks/watched/useWatchedQuerySubscription.d.ts +1 -1
  25. package/lib/hooks/watched/useWatchedQuerySubscription.js.map +1 -1
  26. package/lib/hooks/watched/watch-types.d.ts +39 -3
  27. package/lib/hooks/watched/watch-utils.d.ts +3 -15
  28. package/lib/hooks/watched/watch-utils.js +5 -31
  29. package/lib/hooks/watched/watch-utils.js.map +1 -1
  30. package/lib/index.d.ts +2 -2
  31. package/lib/index.js +1 -1
  32. package/lib/index.js.map +1 -1
  33. package/package.json +11 -9
  34. package/src/hooks/PowerSyncContext.ts +9 -3
  35. package/src/hooks/streams.ts +14 -20
  36. package/src/hooks/suspense/SuspenseQueryCache.ts +253 -0
  37. package/src/hooks/suspense/useSuspenseQuery.ts +40 -13
  38. package/src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts +65 -25
  39. package/src/hooks/useStatus.ts +21 -7
  40. package/src/hooks/watched/QueryRunner.ts +484 -0
  41. package/src/hooks/watched/useQuery.ts +15 -41
  42. package/src/hooks/watched/useWatchedQuerySubscription.ts +2 -2
  43. package/src/hooks/watched/watch-types.ts +42 -3
  44. package/src/hooks/watched/watch-utils.ts +8 -54
  45. package/src/index.ts +8 -2
  46. package/lib/QueryStore.d.ts +0 -10
  47. package/lib/QueryStore.js +0 -63
  48. package/lib/QueryStore.js.map +0 -1
  49. package/lib/hooks/suspense/suspense-utils.d.ts +0 -16
  50. package/lib/hooks/suspense/suspense-utils.js +0 -76
  51. package/lib/hooks/suspense/suspense-utils.js.map +0 -1
  52. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +0 -10
  53. package/lib/hooks/suspense/useSingleSuspenseQuery.js +0 -73
  54. package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +0 -1
  55. package/lib/hooks/suspense/useWatchedSuspenseQuery.d.ts +0 -6
  56. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +0 -26
  57. package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +0 -1
  58. package/lib/hooks/watched/useSingleQuery.d.ts +0 -6
  59. package/lib/hooks/watched/useSingleQuery.js +0 -59
  60. package/lib/hooks/watched/useSingleQuery.js.map +0 -1
  61. package/lib/hooks/watched/useWatchedQuery.d.ts +0 -13
  62. package/lib/hooks/watched/useWatchedQuery.js +0 -81
  63. package/lib/hooks/watched/useWatchedQuery.js.map +0 -1
  64. package/src/QueryStore.ts +0 -81
  65. package/src/hooks/suspense/suspense-utils.ts +0 -86
  66. package/src/hooks/suspense/useSingleSuspenseQuery.ts +0 -81
  67. package/src/hooks/suspense/useWatchedSuspenseQuery.ts +0 -36
  68. package/src/hooks/watched/useSingleQuery.ts +0 -67
  69. package/src/hooks/watched/useWatchedQuery.ts +0 -93
@@ -6,9 +6,9 @@ export interface HookWatchOptions extends Omit<SQLOnChangeOptions, 'signal'> {
6
6
  *
7
7
  * When set, `useQuery` will subscribe to those streams (and automatically handle unsubscribing from them, too).
8
8
  *
9
- * If {@link QuerySyncStreamOptions} is set on a stream, `useQuery` will remain in a loading state until that stream
10
- * is marked as {@link SyncSubscriptionDescription.hasSynced}. This ensures the query is not missing rows that haven't
11
- * been downloaded.
9
+ * If {@link QuerySyncStreamOptions.waitForStream} is set on a stream, `useQuery` will remain in a loading state until
10
+ * that stream is marked as {@link SyncSubscriptionDescription.hasSynced}. This ensures the query is not missing rows
11
+ * that haven't been downloaded.
12
12
  * Note however that after an initial sync, the query will not block itself while new rows are downloading. Instead,
13
13
  * consistent sync snapshots will be made available as they've been processed by PowerSync.
14
14
  */
@@ -51,6 +51,31 @@ export interface DifferentialHookOptions<RowType> extends HookWatchOptions {
51
51
  */
52
52
  rowComparator?: DifferentialWatchedQueryComparator<RowType>;
53
53
  }
54
+ type WithoutSyncStreams<T> = Omit<T, 'streams'> & {
55
+ /**
56
+ * @deprecated Sync streams are not supported by `useSuspenseQuery` and are ignored. Use `useQuery` or
57
+ * `useSyncStream` to subscribe to streams instead.
58
+ */
59
+ streams?: QuerySyncStreamOptions[];
60
+ };
61
+ /**
62
+ * Options for `useSuspenseQuery`.
63
+ */
64
+ export type SuspenseQueryOptions = WithoutSyncStreams<AdditionalOptions>;
65
+ /**
66
+ * Options for `useSuspenseQuery` with a `rowComparator`.
67
+ */
68
+ export type DifferentialSuspenseQueryOptions<RowType> = WithoutSyncStreams<DifferentialHookOptions<RowType>>;
69
+ /**
70
+ * Why a `useQuery` hook is currently fetching.
71
+ *
72
+ * - `'initial'`: the first load of this query, `isLoading` is true as well.
73
+ * - `refresh`: `QueryResult.refresh` was called.
74
+ * - `'tables-changed'`: a table the query depends on changed and the same query is re-running. `data` is still current.
75
+ * - `'settings-changed'`: the SQL, parameters or options changed. `data` still holds the previous query's rows until the
76
+ * updated query has produced its first result.
77
+ */
78
+ export type FetchReason = 'initial' | 'refresh' | 'tables-changed' | 'settings-changed';
54
79
  export type ReadonlyQueryResult<RowType> = {
55
80
  readonly data: ReadonlyArray<Readonly<RowType>>;
56
81
  /**
@@ -62,6 +87,11 @@ export type ReadonlyQueryResult<RowType> = {
62
87
  */
63
88
  readonly isFetching: boolean;
64
89
  readonly error: Error | undefined;
90
+ /**
91
+ * Why the query is running while `isFetching` is true, `undefined` otherwise. `'settings-changed'` means the
92
+ * SQL, parameters or options changed and `data` still holds the previous query's rows until the new result arrives.
93
+ */
94
+ readonly fetchReason?: FetchReason;
65
95
  /**
66
96
  * Function used to run the query again.
67
97
  */
@@ -78,8 +108,14 @@ export type QueryResult<RowType> = {
78
108
  */
79
109
  isFetching: boolean;
80
110
  error: Error | undefined;
111
+ /**
112
+ * Why the query is running while `isFetching` is true, `undefined` otherwise. `'settings-changed'` means the
113
+ * SQL, parameters or options changed and `data` still holds the previous query's rows until the new result arrives.
114
+ */
115
+ fetchReason?: FetchReason;
81
116
  /**
82
117
  * Function used to run the query again.
83
118
  */
84
119
  refresh?: (signal?: AbortSignal) => Promise<void>;
85
120
  };
121
+ export {};
@@ -1,17 +1,5 @@
1
- import { AbstractPowerSyncDatabase, CompilableQuery, WatchCompatibleQuery } from '@powersync/common';
2
- import { AdditionalOptions } from './watch-types.js';
3
- export type InternalHookOptions<DataType> = {
4
- query: WatchCompatibleQuery<DataType>;
5
- powerSync: AbstractPowerSyncDatabase;
6
- queryChanged: boolean;
7
- active: boolean;
8
- };
9
- interface WatchCompatibleQueryWithParams<T> extends WatchCompatibleQuery<T> {
1
+ import { CompilableQuery, WatchCompatibleQuery } from '@powersync/common';
2
+ export interface WatchCompatibleQueryWithParams<T> extends WatchCompatibleQuery<T> {
10
3
  stringifiedParameters?: string;
11
4
  }
12
- export declare const checkQueryChanged: <T>(query: WatchCompatibleQueryWithParams<T>, options: AdditionalOptions) => boolean;
13
- export declare const constructCompatibleQuery: <RowType>(query: string | CompilableQuery<RowType>, parameters: any[], options: AdditionalOptions) => {
14
- parsedQuery: WatchCompatibleQueryWithParams<RowType[]>;
15
- queryChanged: boolean;
16
- };
17
- export {};
5
+ export declare const constructCompatibleQuery: <RowType>(query: string | CompilableQuery<RowType>, parameters?: any[]) => WatchCompatibleQueryWithParams<RowType[]>;
@@ -1,29 +1,7 @@
1
1
  import React from 'react';
2
- import { usePowerSync } from '../PowerSyncContext.js';
3
- export const checkQueryChanged = (query, options) => {
4
- let _compiled;
5
- try {
6
- _compiled = query.compile();
7
- }
8
- catch (error) {
9
- return false; // If compilation fails, we assume the query has changed
10
- }
11
- const compiled = _compiled;
12
- const stringifiedParams = query.stringifiedParameters ?? JSON.stringify(compiled.parameters);
13
- const stringifiedOptions = JSON.stringify(options);
14
- const previousQueryRef = React.useRef({ sqlStatement: compiled.sql, stringifiedParams, stringifiedOptions });
15
- if (previousQueryRef.current.sqlStatement !== compiled.sql ||
16
- previousQueryRef.current.stringifiedParams != stringifiedParams ||
17
- previousQueryRef.current.stringifiedOptions != stringifiedOptions) {
18
- previousQueryRef.current.sqlStatement = compiled.sql;
19
- previousQueryRef.current.stringifiedParams = stringifiedParams;
20
- previousQueryRef.current.stringifiedOptions = stringifiedOptions;
21
- return true;
22
- }
23
- return false;
24
- };
25
- export const constructCompatibleQuery = (query, parameters = [], options) => {
26
- const powerSync = usePowerSync();
2
+ import { usePowerSyncOrNull } from '../PowerSyncContext.js';
3
+ export const constructCompatibleQuery = (query, parameters = []) => {
4
+ const powerSync = usePowerSyncOrNull();
27
5
  const stringifiedParameters = React.useMemo(() => JSON.stringify(parameters), [parameters]);
28
6
  const parsedQuery = React.useMemo(() => {
29
7
  if (typeof query == 'string') {
@@ -33,7 +11,7 @@ export const constructCompatibleQuery = (query, parameters = [], options) => {
33
11
  parameters
34
12
  }),
35
13
  execute: () => powerSync.getAll(query, parameters),
36
- // Setting this is a small optimization that avoids checkQueryChanged recomputing the JSON representation.
14
+ // Setting this is a small optimization that avoids QueryRunner recomputing the JSON representation.
37
15
  stringifiedParameters
38
16
  };
39
17
  }
@@ -53,10 +31,6 @@ export const constructCompatibleQuery = (query, parameters = [], options) => {
53
31
  };
54
32
  }
55
33
  }, [query, powerSync, stringifiedParameters]);
56
- const queryChanged = checkQueryChanged(parsedQuery, options);
57
- return {
58
- parsedQuery,
59
- queryChanged
60
- };
34
+ return parsedQuery;
61
35
  };
62
36
  //# sourceMappingURL=watch-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"watch-utils.js","sourceRoot":"","sources":["../../../src/hooks/watched/watch-utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AActD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAI,KAAwC,EAAE,OAA0B,EAAE,EAAE;IAC3G,IAAI,SAAwB,CAAC;IAC7B,IAAI,CAAC;QACH,SAAS,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;IAC9B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,KAAK,CAAC,CAAC,wDAAwD;IACxE,CAAC;IACD,MAAM,QAAQ,GAAG,SAAU,CAAC;IAE5B,MAAM,iBAAiB,GAAG,KAAK,CAAC,qBAAqB,IAAI,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;IAC7F,MAAM,kBAAkB,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IAEnD,MAAM,gBAAgB,GAAG,KAAK,CAAC,MAAM,CAAC,EAAE,YAAY,EAAE,QAAQ,CAAC,GAAG,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,CAAC,CAAC;IAE7G,IACE,gB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AM,CAAC;YACN,OAAO;gBACL,0DAA0D;gBAC1D,OAAO,EAAE,GAAG,EAAE;oBACZ,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,EAAE,CAAC;oBACjC,OAAO;wBACL,GAAG,EAAE,QAAQ,CAAC,GAAG;wBACjB,UAAU,EAAE,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC;qBACrC,CAAC;gBACJ,CAAC;gBACD,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,EAAE;gBAC9B,6GAA6G;gBAC7G,YAAY;aACb,CAAC;QACJ,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,qBAAqB,CAAC,CAAC,CAAC;IAE9C,OAAO,WAAW,CAAC;AACrB,CAAC,CAAC"}
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export * from './hooks/PowerSyncContext.js';
1
+ export { usePowerSync, PowerSyncContext } from './hooks/PowerSyncContext.js';
2
2
  export { SuspenseQueryResult } from './hooks/suspense/SuspenseQueryResult.js';
3
3
  export { useSuspenseQuery } from './hooks/suspense/useSuspenseQuery.js';
4
4
  export { useWatchedQuerySuspenseSubscription } from './hooks/suspense/useWatchedQuerySuspenseSubscription.js';
@@ -6,4 +6,4 @@ export { useAllSyncStreamsHaveSynced, useSyncStream, UseSyncStreamOptions } from
6
6
  export { useStatus } from './hooks/useStatus.js';
7
7
  export { useQuery } from './hooks/watched/useQuery.js';
8
8
  export { useWatchedQuerySubscription } from './hooks/watched/useWatchedQuerySubscription.js';
9
- export { AdditionalOptions, QuerySyncStreamOptions } from './hooks/watched/watch-types.js';
9
+ export { AdditionalOptions, FetchReason, DifferentialSuspenseQueryOptions, QuerySyncStreamOptions, SuspenseQueryOptions } from './hooks/watched/watch-types.js';
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export * from './hooks/PowerSyncContext.js';
1
+ export { usePowerSync, PowerSyncContext } from './hooks/PowerSyncContext.js';
2
2
  export { useSuspenseQuery } from './hooks/suspense/useSuspenseQuery.js';
3
3
  export { useWatchedQuerySuspenseSubscription } from './hooks/suspense/useWatchedQuerySuspenseSubscription.js';
4
4
  export { useAllSyncStreamsHaveSynced, useSyncStream } from './hooks/streams.js';
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,6BAA6B,CAAC;AAE5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACxE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yDAAyD,CAAC;AAC9G,OAAO,EAAE,2BAA2B,EAAE,aAAa,EAAwB,MAAM,oBAAoB,CAAC;AACtG,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,gDAAgD,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AACxE,OAAO,EAAE,mCAAmC,EAAE,MAAM,yDAAyD,CAAC;AAC9G,OAAO,EAAE,2BAA2B,EAAE,aAAa,EAAwB,MAAM,oBAAoB,CAAC;AACtG,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EAAE,2BAA2B,EAAE,MAAM,gDAAgD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/react",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"
@@ -25,24 +25,26 @@
25
25
  },
26
26
  "homepage": "https://docs.powersync.com",
27
27
  "peerDependencies": {
28
- "@powersync/common": "^2.2.0",
28
+ "@powersync/common": "^2.4.0",
29
29
  "react": "*"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@testing-library/react": "^16.0.0",
33
+ "@types/node": "^24.0.0",
34
+ "better-sqlite3": "^13.0.3",
33
35
  "drizzle-orm": "^0.44.7",
34
36
  "p-defer": "^4.0.1",
35
- "@types/react": "^18.3.1",
36
- "@types/react-dom": "^18.3.0",
37
+ "@types/react": "^19.3.0",
38
+ "@types/react-dom": "^19.3.0",
37
39
  "chart.js": "^4.5.0",
38
40
  "jsdom": "^24.0.0",
39
- "react": "18.3.1",
40
- "react-dom": "18.3.1",
41
+ "react": "19.3.0",
42
+ "react-dom": "19.3.0",
41
43
  "react-error-boundary": "^4.1.0",
42
- "@powersync/common": "2.2.0",
44
+ "@powersync/common": "2.4.0",
43
45
  "@powersync/drizzle-driver": "0.8.0",
44
- "@powersync/web": "2.3.0",
45
- "@powersync/shared-internals": "1.2.0"
46
+ "@powersync/node": "1.2.0",
47
+ "@powersync/shared-internals": "1.4.0"
46
48
  },
47
49
  "scripts": {
48
50
  "build": "tsc -b",
@@ -1,7 +1,7 @@
1
- import { AbstractPowerSyncDatabase } from '@powersync/common';
1
+ import { CommonPowerSyncDatabase } from '@powersync/common';
2
2
  import React from 'react';
3
3
 
4
- export const PowerSyncContext = React.createContext<AbstractPowerSyncDatabase | null>(null);
4
+ export const PowerSyncContext = React.createContext<CommonPowerSyncDatabase | null>(null);
5
5
  /**
6
6
  * Custom hook that provides access to the PowerSync context.
7
7
  * @returns The PowerSync Database instance.
@@ -19,4 +19,10 @@ export const PowerSyncContext = React.createContext<AbstractPowerSyncDatabase |
19
19
  * </ul>
20
20
  * };
21
21
  */
22
- export const usePowerSync = () => React.useContext(PowerSyncContext);
22
+ export function usePowerSync() {
23
+ const db = usePowerSyncOrNull();
24
+ if (db == null) throw new Error('PowerSync not configured.');
25
+ return db;
26
+ }
27
+
28
+ export const usePowerSyncOrNull = () => React.useContext(PowerSyncContext);
@@ -1,13 +1,7 @@
1
- import { useEffect, useMemo, useState } from 'react';
2
- import { usePowerSync } from './PowerSyncContext.js';
3
- import {
4
- AbstractPowerSyncDatabase,
5
- SyncStatus,
6
- SyncStreamStatus,
7
- SyncStreamSubscribeOptions,
8
- SyncStreamSubscription
9
- } from '@powersync/common';
10
- import { useStatus } from './useStatus.js';
1
+ import { useEffect, useMemo } from 'react';
2
+ import { usePowerSyncOrNull } from './PowerSyncContext.js';
3
+ import { SyncStreamStatus, SyncStreamSubscribeOptions, SyncStreamSubscription } from '@powersync/common';
4
+ import { useStatusOrNull } from './useStatus.js';
11
5
  import { QuerySyncStreamOptions } from './watched/watch-types.js';
12
6
 
13
7
  /**
@@ -44,20 +38,20 @@ export function useSyncStream(options: UseSyncStreamOptions): SyncStreamStatus |
44
38
  * React component calling this function. When it unmounts, or when the streams array contents
45
39
  * change, all previous subscriptions are unsubscribed before new ones are created.
46
40
  */
47
- export function useSyncStreams(streamOptions: UseSyncStreamOptions[]): SyncStreamStatus[] {
48
- const db = usePowerSync();
49
- const status = useStatus();
41
+ export function useSyncStreams(streamOptions: UseSyncStreamOptions[]): (SyncStreamStatus | null)[] {
42
+ const db = usePowerSyncOrNull();
43
+ const status = useStatusOrNull();
50
44
 
51
45
  const stringifiedOptions = useMemo(() => JSON.stringify(streamOptions), [streamOptions]);
52
46
  const syncStreams = useMemo(
53
47
  () =>
54
48
  streamOptions.map((options) => {
55
49
  return {
56
- stream: db.syncStream(options.name, options.parameters ?? undefined),
50
+ stream: db?.syncStream(options.name, options.parameters ?? undefined),
57
51
  options
58
52
  };
59
53
  }),
60
- [stringifiedOptions]
54
+ [db, stringifiedOptions]
61
55
  );
62
56
 
63
57
  useEffect(() => {
@@ -65,7 +59,7 @@ export function useSyncStreams(streamOptions: UseSyncStreamOptions[]): SyncStrea
65
59
  const resolvedSubs: SyncStreamSubscription[] = [];
66
60
 
67
61
  for (const entry of syncStreams) {
68
- entry.stream.subscribe(entry.options).then((sub) => {
62
+ entry.stream?.subscribe(entry.options).then((sub) => {
69
63
  if (active) {
70
64
  resolvedSubs.push(sub);
71
65
  } else {
@@ -81,11 +75,11 @@ export function useSyncStreams(streamOptions: UseSyncStreamOptions[]): SyncStrea
81
75
  sub.unsubscribe();
82
76
  }
83
77
  };
84
- }, [stringifiedOptions]);
78
+ }, [db, stringifiedOptions]);
85
79
 
86
80
  return useMemo(
87
- () => syncStreams.map((entry) => status.forStream(entry.stream) ?? null),
88
- [status, stringifiedOptions]
81
+ () => syncStreams.map((entry) => (entry.stream && status?.forStream(entry.stream)) ?? null),
82
+ [status, syncStreams]
89
83
  );
90
84
  }
91
85
 
@@ -93,7 +87,7 @@ export function useSyncStreams(streamOptions: UseSyncStreamOptions[]): SyncStrea
93
87
  * Returns `true` once all streams in the array have synced at least once.
94
88
  */
95
89
  export function useAllSyncStreamsHaveSynced(
96
- db: AbstractPowerSyncDatabase,
90
+ _db: unknown, // TODO (breaking): Remove
97
91
  streams: QuerySyncStreamOptions[] | undefined
98
92
  ): boolean {
99
93
  const statuses = useSyncStreams(streams ?? []);
@@ -0,0 +1,253 @@
1
+ import { CommonPowerSyncDatabase } from '@powersync/common';
2
+ import { QueryConfig, QueryRunner, Result } from '../watched/QueryRunner.js';
3
+
4
+ /**
5
+ * How long a query checked out by a render stays alive after it has loaded, if no component subscribes to it.
6
+ *
7
+ * React may take a while to commit a component after its suspending promise resolves (at least 300ms), so this should
8
+ * be generous.
9
+ */
10
+ export const TEMPORARY_HOLD_MS = 5_000;
11
+
12
+ /**
13
+ * Shares {@link QueryRunner}s between suspending hooks.
14
+ *
15
+ * Components that suspend before their first commit lose all their state, so the runner for a query can't be stored
16
+ * in the component. Instead, rendering checks out the entry for a query from this cache. Checking out an entry places a
17
+ * temporary hold on it, which runs the query and keeps it alive until a component has committed and subscribed to it
18
+ * (or until the hold expires, e.g. because the render was discarded).
19
+ *
20
+ * An entry is alive exactly while it is held or has subscribers, and the cache maps each query to at most one entry.
21
+ * Hooks never reference entries directly, they use a {@link SuspenseQuery} handle that looks up the current entry for
22
+ * its query (creating it if necessary) and then sticks to that entry while it's alive.
23
+ *
24
+ * Watched queries are shared between all components using them. Queries that only run once are shared only until a
25
+ * component commits with their results: We want a suspending hook to obtain the same query when its render is retried,
26
+ * but components that have committed must be able to refresh independently, and components mounting later shouldn't
27
+ * see stale results. So the first component committing with a one-shot entry claims it, which evicts it from the cache.
28
+ * Other components that rendered with the same entry (e.g. siblings in the same suspense boundary) continue with their
29
+ * own runner, seeded with the loaded result.
30
+ */
31
+ class SuspenseQueryCache {
32
+ private readonly entries = new Map<string, SuspenseQueryEntry<any>>();
33
+
34
+ /**
35
+ * Returns a handle for the given query. Creating handles has no side effects.
36
+ */
37
+ query<RowType>(key: string, config: QueryConfig<RowType>) {
38
+ let entry: SuspenseQueryEntry<RowType> | null = null;
39
+ // For one-shot queries, a runner owned by this handle after another one claimed the shared entry.
40
+ let settledOneShotFork: QueryRunner<RowType> | null = null;
41
+ const current = () => {
42
+ if (entry == null || entry.isRemoved) {
43
+ entry = this.entries.get(key) ?? this.checkOut(key, config);
44
+ }
45
+ return entry;
46
+ };
47
+
48
+ const handle = {
49
+ markUsed: () => {
50
+ if (settledOneShotFork != null) {
51
+ return;
52
+ } else if (entry == null || entry.isRemoved) {
53
+ entry = this.checkOut(key, config);
54
+ } else {
55
+ entry.ensureHeld();
56
+ }
57
+ },
58
+ subscribe: (onChange: () => void): (() => void) => {
59
+ if (settledOneShotFork == null) {
60
+ const shared = current();
61
+ if (shared.claim(handle)) {
62
+ return shared.subscribe(onChange);
63
+ }
64
+
65
+ settledOneShotFork = new QueryRunner();
66
+ settledOneShotFork.configure(config, shared.getSnapshot());
67
+ }
68
+ return settledOneShotFork.subscribe(onChange);
69
+ },
70
+ getSnapshot: (): Result<RowType> => {
71
+ return (settledOneShotFork ?? current()).getSnapshot();
72
+ },
73
+ waitForLoaded: (): Promise<void> => {
74
+ return current().loaded;
75
+ }
76
+ };
77
+ return handle;
78
+ }
79
+
80
+ /**
81
+ * Returns the entry for the given query after placing a temporary hold on it, creating it if necessary.
82
+ */
83
+ private checkOut<RowType>(key: string, config: QueryConfig<RowType>): SuspenseQueryEntry<RowType> {
84
+ let entry = this.entries.get(key) as SuspenseQueryEntry<RowType> | undefined;
85
+ if (entry == null) {
86
+ const created: SuspenseQueryEntry<RowType> = new SuspenseQueryEntry(config, () => {
87
+ // A claimed entry may have been replaced already, don't evict its replacement.
88
+ if (this.entries.get(key) === created) {
89
+ this.entries.delete(key);
90
+ }
91
+ });
92
+ this.entries.set(key, created);
93
+ entry = created;
94
+ }
95
+
96
+ entry.ensureHeld();
97
+ return entry;
98
+ }
99
+ }
100
+
101
+ class SuspenseQueryEntry<RowType> {
102
+ private readonly runner = new QueryRunner<RowType>();
103
+ /**
104
+ * The number of subscribed components, not counting the temporary hold.
105
+ */
106
+ private subscribers = 0;
107
+ private releaseHold: (() => void) | null = null;
108
+ private holdTimeout: ReturnType<typeof setTimeout> | null = null;
109
+ private pendingLoad: { promise: Promise<void>; resolve: () => void } | null = null;
110
+ private readonly runOnce: boolean;
111
+ /**
112
+ * For one-shot queries, the handle of the component that has committed with this entry.
113
+ */
114
+ private owner: object | null = null;
115
+ /**
116
+ * Set once this entry is neither held nor subscribed to. Its runner is idle then, and it must not be used again.
117
+ */
118
+ isRemoved = false;
119
+
120
+ constructor(
121
+ config: QueryConfig<RowType>,
122
+ /**
123
+ * Evicts this entry from the cache, called once it's removed or claimed.
124
+ */
125
+ private readonly evict: () => void
126
+ ) {
127
+ this.runOnce = config.runOnce;
128
+ // We call configure once here, and then never again. A changed config is represented by a fresh query entry
129
+ // (necessary to potentially re-use this across components).
130
+ this.runner.configure(config);
131
+ }
132
+
133
+ /**
134
+ * Called before a committed component subscribes through the given handle. Returns whether it may subscribe to this
135
+ * entry, or whether it needs to use its own runner instead.
136
+ *
137
+ * Watched queries can always be shared. For queries running once, the first committing component takes ownership of
138
+ * this entry, so that refreshing it doesn't affect other components and components mounting later don't get its
139
+ * (potentially stale) result.
140
+ */
141
+ claim(handle: object): boolean {
142
+ if (!this.runOnce) {
143
+ return true;
144
+ }
145
+
146
+ if (this.owner == null) {
147
+ this.owner = handle;
148
+ this.evict();
149
+ }
150
+ // In StrictMode, React unsubscribes and resubscribes right away, so the owner may claim this entry again.
151
+ return this.owner === handle;
152
+ }
153
+
154
+ subscribe(onChange: () => void): () => void {
155
+ this.subscribers++;
156
+ // Note that we don't release the temporary hold here: In StrictMode, React unsubscribes and resubscribes right
157
+ // away, which would otherwise dispose and restart the query. The hold expires on its own shortly after loading.
158
+ const unsubscribe = this.runner.subscribe(() => {
159
+ this.onRunnerChange();
160
+ onChange();
161
+ });
162
+
163
+ return () => {
164
+ unsubscribe();
165
+ this.subscribers--;
166
+ this.removeIfUnused();
167
+ };
168
+ }
169
+
170
+ getSnapshot(): Result<RowType> {
171
+ return this.runner.getSnapshot();
172
+ }
173
+
174
+ /**
175
+ * A promise to throw while the query is loading. It's stable until the query has loaded, and resolves once the
176
+ * query has a result or an error.
177
+ */
178
+ get loaded(): Promise<void> {
179
+ if (this.isSettled) {
180
+ return Promise.resolve();
181
+ }
182
+
183
+ if (this.pendingLoad == null) {
184
+ let resolve!: () => void;
185
+ const promise = new Promise<void>((r) => (resolve = r));
186
+ this.pendingLoad = { promise, resolve };
187
+ }
188
+ return this.pendingLoad.promise;
189
+ }
190
+
191
+ /**
192
+ * Places a temporary hold on this entry for a render that checked it out, or extends the existing one.
193
+ *
194
+ * We do this even if components are subscribed already, since they might unsubscribe before the render checking
195
+ * out this entry commits (e.g. when one component unmounts while another one using the same query mounts).
196
+ */
197
+ ensureHeld() {
198
+ if (this.releaseHold == null) {
199
+ // If this is the first listener, subscribing starts running the query. The runner then only notifies its own
200
+ // listeners, which is just the hold. Otherwise, it doesn't notify anyone. So this is safe to call while rendering.
201
+ this.releaseHold = this.runner.subscribe(() => this.onRunnerChange());
202
+ } else if (this.holdTimeout != null) {
203
+ // Restart the timer in onRunnerChange, so that the hold lasts until shortly after the latest checkout.
204
+ clearTimeout(this.holdTimeout);
205
+ this.holdTimeout = null;
206
+ }
207
+
208
+ this.onRunnerChange();
209
+ }
210
+
211
+ private get isSettled(): boolean {
212
+ const snapshot = this.runner.getSnapshot();
213
+ return !snapshot.isLoading || snapshot.error != null;
214
+ }
215
+
216
+ private onRunnerChange() {
217
+ if (!this.isSettled) {
218
+ return;
219
+ }
220
+
221
+ this.pendingLoad?.resolve();
222
+ this.pendingLoad = null;
223
+
224
+ if (this.releaseHold != null && this.holdTimeout == null) {
225
+ this.holdTimeout = setTimeout(() => {
226
+ this.holdTimeout = null;
227
+ this.releaseHold?.();
228
+ this.releaseHold = null;
229
+ this.removeIfUnused();
230
+ }, TEMPORARY_HOLD_MS);
231
+ }
232
+ }
233
+
234
+ private removeIfUnused() {
235
+ if (this.subscribers == 0 && this.releaseHold == null) {
236
+ // The runner has disposed its work since it has no listeners left.
237
+ this.isRemoved = true;
238
+ this.evict();
239
+ }
240
+ }
241
+ }
242
+
243
+ let caches: WeakMap<CommonPowerSyncDatabase, SuspenseQueryCache> | undefined;
244
+
245
+ export function getSuspenseQueryCache(db: CommonPowerSyncDatabase): SuspenseQueryCache {
246
+ caches ??= new WeakMap();
247
+ let cache = caches.get(db);
248
+ if (cache == null) {
249
+ cache = new SuspenseQueryCache();
250
+ caches.set(db, cache);
251
+ }
252
+ return cache;
253
+ }
@@ -1,8 +1,11 @@
1
1
  import { CompilableQuery } from '@powersync/common';
2
- import { AdditionalOptions, DifferentialHookOptions } from '../watched/watch-types.js';
2
+ import { useContext, useMemo, useSyncExternalStore } from 'react';
3
+ import { PowerSyncContext } from '../PowerSyncContext.js';
4
+ import { configError, configKey, resolveConfig } from '../watched/QueryRunner.js';
5
+ import { DifferentialSuspenseQueryOptions, SuspenseQueryOptions } from '../watched/watch-types.js';
6
+ import { constructCompatibleQuery } from '../watched/watch-utils.js';
7
+ import { getSuspenseQueryCache } from './SuspenseQueryCache.js';
3
8
  import { ReadonlySuspenseQueryResult, SuspenseQueryResult } from './SuspenseQueryResult.js';
4
- import { useSingleSuspenseQuery } from './useSingleSuspenseQuery.js';
5
- import { useWatchedSuspenseQuery } from './useWatchedSuspenseQuery.js';
6
9
 
7
10
  /**
8
11
  * A hook to access the results of a watched query that suspends until the initial result has loaded.
@@ -55,22 +58,46 @@ import { useWatchedSuspenseQuery } from './useWatchedSuspenseQuery.js';
55
58
  export function useSuspenseQuery<RowType = any>(
56
59
  query: string | CompilableQuery<RowType>,
57
60
  parameters?: any[],
58
- options?: AdditionalOptions
61
+ options?: SuspenseQueryOptions
59
62
  ): SuspenseQueryResult<RowType>;
60
63
  export function useSuspenseQuery<RowType = any>(
61
64
  query: string | CompilableQuery<RowType>,
62
- paramerers?: any[],
63
- options?: DifferentialHookOptions<RowType>
65
+ parameters?: any[],
66
+ options?: DifferentialSuspenseQueryOptions<RowType>
64
67
  ): ReadonlySuspenseQueryResult<RowType>;
65
68
  export function useSuspenseQuery<RowType = any>(
66
69
  query: string | CompilableQuery<RowType>,
67
70
  parameters: any[] = [],
68
- options: AdditionalOptions & DifferentialHookOptions<RowType> = {}
69
- ) {
70
- switch (options?.runQueryOnce) {
71
- case true:
72
- return useSingleSuspenseQuery<RowType>(query, parameters, options);
73
- default:
74
- return useWatchedSuspenseQuery<RowType>(query, parameters, options);
71
+ options: SuspenseQueryOptions & DifferentialSuspenseQueryOptions<RowType> = {}
72
+ ): SuspenseQueryResult<RowType> | ReadonlySuspenseQueryResult<RowType> {
73
+ const powerSync = useContext(PowerSyncContext);
74
+ const parsedQuery = constructCompatibleQuery(query, parameters);
75
+ const config = resolveConfig(
76
+ powerSync,
77
+ parsedQuery,
78
+ options,
79
+ // We currently don't support sync streams here (useAllStreamsHaveSynced relies on useEffect, which don't fire in
80
+ // suspended components).
81
+ true
82
+ );
83
+ if (config.kind != 'query') {
84
+ // Missing database or a query that failed to compile, report.
85
+ throw configError(config);
75
86
  }
87
+
88
+ // A component that suspends before its first commit loses all its state, so the runner for this query is stored in
89
+ // a cache shared between components instead of in a ref.
90
+ const cache = getSuspenseQueryCache(config.db);
91
+ const key = configKey(config);
92
+ const suspenseQuery = useMemo(() => cache.query(key, config), [cache, key]);
93
+ suspenseQuery.markUsed();
94
+ const result = useSyncExternalStore(suspenseQuery.subscribe, suspenseQuery.getSnapshot, suspenseQuery.getSnapshot);
95
+
96
+ if (result.error != null) {
97
+ throw result.error;
98
+ } else if (result.isLoading) {
99
+ throw suspenseQuery.waitForLoaded();
100
+ }
101
+
102
+ return { data: result.data as RowType[], refresh: result.refresh };
76
103
  }