@powersync/react 0.0.0-dev-20261015114518 → 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 (36) hide show
  1. package/lib/QueryStore.d.ts +10 -0
  2. package/lib/QueryStore.js +63 -0
  3. package/lib/QueryStore.js.map +1 -0
  4. package/lib/hooks/suspense/suspense-utils.d.ts +16 -0
  5. package/lib/hooks/suspense/suspense-utils.js +76 -0
  6. package/lib/hooks/suspense/suspense-utils.js.map +1 -0
  7. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +10 -0
  8. package/lib/hooks/suspense/useSingleSuspenseQuery.js +70 -0
  9. package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +1 -0
  10. package/lib/hooks/suspense/useSuspenseQuery.d.ts +3 -3
  11. package/lib/hooks/suspense/useSuspenseQuery.js +7 -28
  12. package/lib/hooks/suspense/useSuspenseQuery.js.map +1 -1
  13. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +24 -60
  14. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js.map +1 -1
  15. package/lib/hooks/suspense/useWatchedSuspenseQuery.d.ts +6 -0
  16. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +23 -0
  17. package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +1 -0
  18. package/lib/hooks/watched/QueryRunner.d.ts +4 -15
  19. package/lib/hooks/watched/QueryRunner.js +9 -35
  20. package/lib/hooks/watched/QueryRunner.js.map +1 -1
  21. package/lib/hooks/watched/watch-types.d.ts +1 -18
  22. package/lib/index.d.ts +1 -1
  23. package/package.json +5 -5
  24. package/src/QueryStore.ts +81 -0
  25. package/src/hooks/suspense/suspense-utils.ts +86 -0
  26. package/src/hooks/suspense/useSingleSuspenseQuery.ts +78 -0
  27. package/src/hooks/suspense/useSuspenseQuery.ts +13 -40
  28. package/src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts +25 -65
  29. package/src/hooks/suspense/useWatchedSuspenseQuery.ts +33 -0
  30. package/src/hooks/watched/QueryRunner.ts +11 -40
  31. package/src/hooks/watched/watch-types.ts +1 -20
  32. package/src/index.ts +1 -7
  33. package/lib/hooks/suspense/SuspenseQueryCache.d.ts +0 -46
  34. package/lib/hooks/suspense/SuspenseQueryCache.js +0 -231
  35. package/lib/hooks/suspense/SuspenseQueryCache.js.map +0 -1
  36. package/src/hooks/suspense/SuspenseQueryCache.ts +0 -253
@@ -1,253 +0,0 @@
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
- }