@pgxsinkit/react 0.2.6 → 0.3.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/create-hooks.d.ts.map +1 -1
- package/dist/index.js +175 -131
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/skills/react/SKILL.md +12 -11
- package/src/create-hooks.tsx +164 -80
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-hooks.d.ts","sourceRoot":"","sources":["../src/create-hooks.tsx"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,cAAc,EAAE,KAAK,SAAS,EAA4C,MAAM,OAAO,CAAC;AAErH,OAAO,EACL,KAAK,YAAY,EAEjB,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAE1B,KAAK,UAAU,EAEhB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9F,OAAO,EAAuD,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAE5G;;;;;;GAMG;AACH,UAAU,iBAAiB,CAAC,KAAK,SAAS,SAAS,OAAO,EAAE,CAAE,SAAQ,WAAW,CAAC,KAAK,CAAC;IACtF,KAAK,IAAI;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,EAAE,CAAA;KAAE,CAAC;IAC5C,QAAQ,CAAC,CAAC,CAAC,EAAE;QAAE,QAAQ,CAAC,cAAc,CAAC,EAAE,cAAc,CAAA;KAAE,CAAC;CAC3D;AAED;;;;;;;;GAQG;AACH,UAAU,aAAa,CAAC,KAAK;IAC3B,IAAI,EAAE,KAAK,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CACrB;
|
|
1
|
+
{"version":3,"file":"create-hooks.d.ts","sourceRoot":"","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
|
|
92
92
|
};
|
|
93
93
|
});
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Shared "no subscription yet" rows. The hooks DERIVE their return value during render, so this has to be
|
|
97
|
+
* one stable identity — a fresh `[]` per render would defeat the memoised return object and re-fire every
|
|
98
|
+
* consumer effect that depends on `rows`.
|
|
99
|
+
*/
|
|
100
|
+
var EMPTY_ROWS = [];
|
|
95
101
|
var EMPTY_MUTATION_SUMMARY = {
|
|
96
102
|
pendingCount: 0,
|
|
97
103
|
sendingCount: 0,
|
|
@@ -130,6 +136,11 @@ function createSyncClientHooks() {
|
|
|
130
136
|
* lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a
|
|
131
137
|
* `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.
|
|
132
138
|
* Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.
|
|
139
|
+
*
|
|
140
|
+
* `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a
|
|
141
|
+
* `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes
|
|
142
|
+
* (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
|
|
143
|
+
* loading" policy already applied across a query change.
|
|
133
144
|
*/
|
|
134
145
|
function useLiveRows(query, options) {
|
|
135
146
|
const contextClient = useContext(SyncClientContext);
|
|
@@ -137,55 +148,56 @@ function createSyncClientHooks() {
|
|
|
137
148
|
const ready = options?.ready ?? true;
|
|
138
149
|
const paramsKey = JSON.stringify(options?.params ?? []);
|
|
139
150
|
const stableParams = useMemo(() => JSON.parse(paramsKey), [paramsKey]);
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
151
|
+
const canRun = ready && (overridePglite != null || contextClient != null);
|
|
152
|
+
const run = useMemo(() => canRun ? {
|
|
153
|
+
query,
|
|
154
|
+
params: stableParams,
|
|
155
|
+
client: contextClient,
|
|
156
|
+
pglite: overridePglite
|
|
157
|
+
} : null, [
|
|
158
|
+
canRun,
|
|
159
|
+
query,
|
|
160
|
+
stableParams,
|
|
161
|
+
contextClient,
|
|
162
|
+
overridePglite
|
|
163
|
+
]);
|
|
164
|
+
const [snapshot, setSnapshot] = useState({
|
|
165
|
+
run: null,
|
|
166
|
+
rows: EMPTY_ROWS,
|
|
143
167
|
error: null
|
|
144
168
|
});
|
|
145
169
|
useEffect(() => {
|
|
146
|
-
if (
|
|
147
|
-
setState({
|
|
148
|
-
rows: [],
|
|
149
|
-
loading: ready,
|
|
150
|
-
error: null
|
|
151
|
-
});
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
170
|
+
if (run == null) return;
|
|
154
171
|
let active = true;
|
|
155
172
|
let subscription;
|
|
156
|
-
setState((prev) => ({
|
|
157
|
-
rows: prev.rows,
|
|
158
|
-
loading: true,
|
|
159
|
-
error: null
|
|
160
|
-
}));
|
|
161
173
|
const onRows = (rows) => {
|
|
162
174
|
if (active) {
|
|
163
175
|
syncDebug("live query updated → re-render", { rows: rows.length });
|
|
164
|
-
|
|
176
|
+
setSnapshot({
|
|
177
|
+
run,
|
|
165
178
|
rows,
|
|
166
|
-
loading: false,
|
|
167
179
|
error: null
|
|
168
180
|
});
|
|
169
181
|
}
|
|
170
182
|
};
|
|
171
|
-
(
|
|
172
|
-
sql: query,
|
|
173
|
-
params:
|
|
183
|
+
(run.pglite ? subscribeRawPglite(run.pglite, run.query, run.params, onRows) : run.client.subscribeLiveRows({
|
|
184
|
+
sql: run.query,
|
|
185
|
+
params: run.params
|
|
174
186
|
}, (rows) => onRows(rows))).then((registered) => {
|
|
175
187
|
if (!active) {
|
|
176
188
|
registered.unsubscribe();
|
|
177
189
|
return;
|
|
178
190
|
}
|
|
179
191
|
subscription = registered;
|
|
180
|
-
|
|
192
|
+
setSnapshot({
|
|
193
|
+
run,
|
|
181
194
|
rows: registered.initialRows,
|
|
182
|
-
loading: false,
|
|
183
195
|
error: null
|
|
184
196
|
});
|
|
185
197
|
}).catch((error) => {
|
|
186
|
-
if (active)
|
|
187
|
-
|
|
188
|
-
|
|
198
|
+
if (active) setSnapshot({
|
|
199
|
+
run,
|
|
200
|
+
rows: EMPTY_ROWS,
|
|
189
201
|
error: error instanceof Error ? error : new Error(String(error))
|
|
190
202
|
});
|
|
191
203
|
});
|
|
@@ -193,14 +205,20 @@ function createSyncClientHooks() {
|
|
|
193
205
|
active = false;
|
|
194
206
|
subscription?.unsubscribe();
|
|
195
207
|
};
|
|
196
|
-
}, [
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
208
|
+
}, [run]);
|
|
209
|
+
const settled = run != null && snapshot.run === run;
|
|
210
|
+
const rows = run == null ? EMPTY_ROWS : snapshot.rows;
|
|
211
|
+
const loading = ready && !settled;
|
|
212
|
+
const error = settled ? snapshot.error : null;
|
|
213
|
+
return useMemo(() => ({
|
|
214
|
+
rows,
|
|
215
|
+
loading,
|
|
216
|
+
error
|
|
217
|
+
}), [
|
|
218
|
+
rows,
|
|
219
|
+
loading,
|
|
220
|
+
error
|
|
202
221
|
]);
|
|
203
|
-
return state;
|
|
204
222
|
}
|
|
205
223
|
function useLiveRow(query, options) {
|
|
206
224
|
const { rows, loading, error } = useLiveRows(query, options);
|
|
@@ -215,6 +233,11 @@ function createSyncClientHooks() {
|
|
|
215
233
|
* then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional
|
|
216
234
|
* `use`), activates + hydrates them, and only then subscribes the live query — so it is never
|
|
217
235
|
* registered against an un-hydrated lazy relation (ADR-0021).
|
|
236
|
+
*
|
|
237
|
+
* `loading`/`hydrating`/`rows` are derived from which subscription the latest snapshot belongs to, so a
|
|
238
|
+
* `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes
|
|
239
|
+
* (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
|
|
240
|
+
* loading" policy already applied across a query change.
|
|
218
241
|
*/
|
|
219
242
|
function useGuardedDrizzleLive(buildQuery, deps, options) {
|
|
220
243
|
const contextClient = useContext(SyncClientContext);
|
|
@@ -231,51 +254,48 @@ function createSyncClientHooks() {
|
|
|
231
254
|
};
|
|
232
255
|
}, [contextClient, ...deps]);
|
|
233
256
|
const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
257
|
+
const run = useMemo(() => ready && contextClient != null && queryInfo != null ? {
|
|
258
|
+
client: contextClient,
|
|
259
|
+
queryInfo,
|
|
260
|
+
useList,
|
|
261
|
+
keepAliveMs
|
|
262
|
+
} : null, [
|
|
263
|
+
contextClient,
|
|
264
|
+
sqlKey,
|
|
265
|
+
useKey,
|
|
266
|
+
ready
|
|
267
|
+
]);
|
|
268
|
+
const [snapshot, setSnapshot] = useState({
|
|
269
|
+
run: null,
|
|
270
|
+
rows: EMPTY_ROWS,
|
|
271
|
+
hydrated: false,
|
|
238
272
|
error: null
|
|
239
273
|
});
|
|
240
274
|
useEffect(() => {
|
|
241
|
-
if (
|
|
242
|
-
|
|
243
|
-
rows: [],
|
|
244
|
-
loading: ready,
|
|
245
|
-
hydrating: false,
|
|
246
|
-
error: null
|
|
247
|
-
});
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
const { sql, selectedFields } = queryInfo;
|
|
275
|
+
if (run == null) return;
|
|
276
|
+
const { sql, selectedFields } = run.queryInfo;
|
|
251
277
|
const fields = liveFieldAliases(selectedFields);
|
|
252
278
|
const mapRows = (rows) => rows.map((row) => fields ? remapAliasedLiveRow(selectedFields, row) : remapLiveRow(selectedFields, row));
|
|
253
279
|
let active = true;
|
|
254
280
|
let subscription;
|
|
255
|
-
|
|
256
|
-
rows: prev.rows,
|
|
257
|
-
loading: true,
|
|
258
|
-
hydrating: true,
|
|
259
|
-
error: null
|
|
260
|
-
}));
|
|
261
|
-
contextClient.prepareQuery({
|
|
281
|
+
run.client.prepareQuery({
|
|
262
282
|
sql: sql.sql,
|
|
263
|
-
...useList ? { use: useList } : {}
|
|
283
|
+
...run.useList ? { use: run.useList } : {}
|
|
264
284
|
}).then(() => {
|
|
265
285
|
if (!active) return void 0;
|
|
266
|
-
return
|
|
286
|
+
return run.client.subscribeLiveRows({
|
|
267
287
|
sql: sql.sql,
|
|
268
288
|
params: sql.params,
|
|
269
289
|
...fields ? { fields } : {},
|
|
270
|
-
...useList ? { use: useList } : {},
|
|
271
|
-
...keepAliveMs != null ? { keepAliveMs } : {}
|
|
290
|
+
...run.useList ? { use: run.useList } : {},
|
|
291
|
+
...run.keepAliveMs != null ? { keepAliveMs: run.keepAliveMs } : {}
|
|
272
292
|
}, (rows) => {
|
|
273
293
|
if (active) {
|
|
274
294
|
syncDebug("live query updated → re-render", { rows: rows.length });
|
|
275
|
-
|
|
295
|
+
setSnapshot((prev) => ({
|
|
296
|
+
run,
|
|
276
297
|
rows: mapRows(rows),
|
|
277
|
-
|
|
278
|
-
hydrating: prev.hydrating,
|
|
298
|
+
hydrated: prev.run === run ? prev.hydrated : false,
|
|
279
299
|
error: null
|
|
280
300
|
}));
|
|
281
301
|
}
|
|
@@ -289,24 +309,24 @@ function createSyncClientHooks() {
|
|
|
289
309
|
rows: registered.initialRows.length,
|
|
290
310
|
hydrating: registered.hydrated != null
|
|
291
311
|
});
|
|
292
|
-
|
|
312
|
+
setSnapshot({
|
|
313
|
+
run,
|
|
293
314
|
rows: mapRows(registered.initialRows),
|
|
294
|
-
|
|
295
|
-
hydrating: registered.hydrated != null ? prev.hydrating : false,
|
|
315
|
+
hydrated: registered.hydrated == null,
|
|
296
316
|
error: null
|
|
297
|
-
})
|
|
317
|
+
});
|
|
298
318
|
if (registered.hydrated) registered.hydrated.then(() => {
|
|
299
|
-
if (active)
|
|
319
|
+
if (active) setSnapshot((prev) => prev.run === run ? {
|
|
300
320
|
...prev,
|
|
301
|
-
|
|
302
|
-
})
|
|
321
|
+
hydrated: true
|
|
322
|
+
} : prev);
|
|
303
323
|
});
|
|
304
324
|
});
|
|
305
325
|
}).catch((error) => {
|
|
306
|
-
if (active)
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
326
|
+
if (active) setSnapshot({
|
|
327
|
+
run,
|
|
328
|
+
rows: EMPTY_ROWS,
|
|
329
|
+
hydrated: true,
|
|
310
330
|
error: error instanceof Error ? error : new Error(String(error))
|
|
311
331
|
});
|
|
312
332
|
});
|
|
@@ -314,13 +334,23 @@ function createSyncClientHooks() {
|
|
|
314
334
|
active = false;
|
|
315
335
|
subscription?.unsubscribe();
|
|
316
336
|
};
|
|
317
|
-
}, [
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
337
|
+
}, [run]);
|
|
338
|
+
const settled = run != null && snapshot.run === run;
|
|
339
|
+
const rows = run == null ? EMPTY_ROWS : snapshot.rows;
|
|
340
|
+
const loading = ready && !settled;
|
|
341
|
+
const hydrating = run != null && !(settled && snapshot.hydrated);
|
|
342
|
+
const error = settled ? snapshot.error : null;
|
|
343
|
+
return useMemo(() => ({
|
|
344
|
+
rows,
|
|
345
|
+
loading,
|
|
346
|
+
hydrating,
|
|
347
|
+
error
|
|
348
|
+
}), [
|
|
349
|
+
rows,
|
|
350
|
+
loading,
|
|
351
|
+
hydrating,
|
|
352
|
+
error
|
|
322
353
|
]);
|
|
323
|
-
return state;
|
|
324
354
|
}
|
|
325
355
|
/**
|
|
326
356
|
* Reactive query using a Drizzle select builder. The builder is re-created
|
|
@@ -385,35 +415,28 @@ function createSyncClientHooks() {
|
|
|
385
415
|
* EVERY writable journal, folded to one {@link MutationSummary}. ONE subscription drives a global sync
|
|
386
416
|
* indicator — no `hydrating` flag, because journals are local and never network-hydrated. Cheap enough to
|
|
387
417
|
* mount permanently (ADR-0040 dedup: one registration regardless of subscriber count).
|
|
418
|
+
*
|
|
419
|
+
* `loading` and `summary` are derived from which subscription the latest snapshot belongs to, so a
|
|
420
|
+
* `ready: false → true` interlude keeps the previous summary while it re-subscribes (`loading: true`)
|
|
421
|
+
* instead of briefly reporting the zero summary.
|
|
388
422
|
*/
|
|
389
423
|
function useMutationSummary(options) {
|
|
390
424
|
const client = useContext(SyncClientContext);
|
|
391
425
|
const ready = options?.ready ?? true;
|
|
392
|
-
const
|
|
426
|
+
const run = useMemo(() => ready && client != null ? { client } : null, [ready, client]);
|
|
427
|
+
const [snapshot, setSnapshot] = useState({
|
|
428
|
+
run: null,
|
|
393
429
|
summary: EMPTY_MUTATION_SUMMARY,
|
|
394
|
-
loading: ready,
|
|
395
430
|
error: null
|
|
396
431
|
});
|
|
397
432
|
useEffect(() => {
|
|
398
|
-
if (
|
|
399
|
-
setState({
|
|
400
|
-
summary: EMPTY_MUTATION_SUMMARY,
|
|
401
|
-
loading: ready,
|
|
402
|
-
error: null
|
|
403
|
-
});
|
|
404
|
-
return;
|
|
405
|
-
}
|
|
433
|
+
if (run == null) return;
|
|
406
434
|
let active = true;
|
|
407
435
|
let subscription;
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
error: null
|
|
412
|
-
}));
|
|
413
|
-
client.mutations.subscribeSummary((summary) => {
|
|
414
|
-
if (active) setState({
|
|
436
|
+
run.client.mutations.subscribeSummary((summary) => {
|
|
437
|
+
if (active) setSnapshot({
|
|
438
|
+
run,
|
|
415
439
|
summary,
|
|
416
|
-
loading: false,
|
|
417
440
|
error: null
|
|
418
441
|
});
|
|
419
442
|
}).then((registered) => {
|
|
@@ -422,15 +445,15 @@ function createSyncClientHooks() {
|
|
|
422
445
|
return;
|
|
423
446
|
}
|
|
424
447
|
subscription = registered;
|
|
425
|
-
|
|
448
|
+
setSnapshot({
|
|
449
|
+
run,
|
|
426
450
|
summary: registered.initial,
|
|
427
|
-
loading: false,
|
|
428
451
|
error: null
|
|
429
452
|
});
|
|
430
453
|
}).catch((error) => {
|
|
431
|
-
if (active)
|
|
454
|
+
if (active) setSnapshot({
|
|
455
|
+
run,
|
|
432
456
|
summary: EMPTY_MUTATION_SUMMARY,
|
|
433
|
-
loading: false,
|
|
434
457
|
error: error instanceof Error ? error : new Error(String(error))
|
|
435
458
|
});
|
|
436
459
|
});
|
|
@@ -438,14 +461,31 @@ function createSyncClientHooks() {
|
|
|
438
461
|
active = false;
|
|
439
462
|
subscription?.unsubscribe();
|
|
440
463
|
};
|
|
441
|
-
}, [
|
|
442
|
-
|
|
464
|
+
}, [run]);
|
|
465
|
+
const settled = run != null && snapshot.run === run;
|
|
466
|
+
const summary = run == null ? EMPTY_MUTATION_SUMMARY : snapshot.summary;
|
|
467
|
+
const loading = ready && !settled;
|
|
468
|
+
const error = settled ? snapshot.error : null;
|
|
469
|
+
return useMemo(() => ({
|
|
470
|
+
summary,
|
|
471
|
+
loading,
|
|
472
|
+
error
|
|
473
|
+
}), [
|
|
474
|
+
summary,
|
|
475
|
+
loading,
|
|
476
|
+
error
|
|
477
|
+
]);
|
|
443
478
|
}
|
|
444
479
|
/**
|
|
445
480
|
* Reactive filtered mutation detail list (`client.mutations.subscribe`): normalized journal rows across
|
|
446
481
|
* every writable table, filtered by `table` / `entityKey` / `statuses` / `limit`, ordered newest-first.
|
|
447
482
|
* Route/feature-scoped — mount it where a diagnostics view is open, not app-wide (prefer
|
|
448
483
|
* {@link useMutationSummary} for a global indicator). No `hydrating` flag (journals are local).
|
|
484
|
+
*
|
|
485
|
+
* `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a
|
|
486
|
+
* `ready: false → true` interlude with unchanged filters keeps the previous rows while it re-subscribes
|
|
487
|
+
* (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
|
|
488
|
+
* loading" policy already applied across a filter change.
|
|
449
489
|
*/
|
|
450
490
|
function useMutationList(options) {
|
|
451
491
|
const client = useContext(SyncClientContext);
|
|
@@ -453,31 +493,27 @@ function createSyncClientHooks() {
|
|
|
453
493
|
const { ready: _ready, ...filters } = options ?? {};
|
|
454
494
|
const filtersKey = JSON.stringify(filters);
|
|
455
495
|
const stableFilters = useMemo(() => JSON.parse(filtersKey), [filtersKey]);
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
496
|
+
const run = useMemo(() => ready && client != null ? {
|
|
497
|
+
client,
|
|
498
|
+
filters: stableFilters
|
|
499
|
+
} : null, [
|
|
500
|
+
ready,
|
|
501
|
+
client,
|
|
502
|
+
stableFilters
|
|
503
|
+
]);
|
|
504
|
+
const [snapshot, setSnapshot] = useState({
|
|
505
|
+
run: null,
|
|
506
|
+
rows: EMPTY_ROWS,
|
|
459
507
|
error: null
|
|
460
508
|
});
|
|
461
509
|
useEffect(() => {
|
|
462
|
-
if (
|
|
463
|
-
setState({
|
|
464
|
-
rows: [],
|
|
465
|
-
loading: ready,
|
|
466
|
-
error: null
|
|
467
|
-
});
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
510
|
+
if (run == null) return;
|
|
470
511
|
let active = true;
|
|
471
512
|
let subscription;
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
error: null
|
|
476
|
-
}));
|
|
477
|
-
client.mutations.subscribe(stableFilters, (rows) => {
|
|
478
|
-
if (active) setState({
|
|
513
|
+
run.client.mutations.subscribe(run.filters, (rows) => {
|
|
514
|
+
if (active) setSnapshot({
|
|
515
|
+
run,
|
|
479
516
|
rows,
|
|
480
|
-
loading: false,
|
|
481
517
|
error: null
|
|
482
518
|
});
|
|
483
519
|
}).then((registered) => {
|
|
@@ -486,15 +522,15 @@ function createSyncClientHooks() {
|
|
|
486
522
|
return;
|
|
487
523
|
}
|
|
488
524
|
subscription = registered;
|
|
489
|
-
|
|
525
|
+
setSnapshot({
|
|
526
|
+
run,
|
|
490
527
|
rows: registered.initial,
|
|
491
|
-
loading: false,
|
|
492
528
|
error: null
|
|
493
529
|
});
|
|
494
530
|
}).catch((error) => {
|
|
495
|
-
if (active)
|
|
496
|
-
|
|
497
|
-
|
|
531
|
+
if (active) setSnapshot({
|
|
532
|
+
run,
|
|
533
|
+
rows: EMPTY_ROWS,
|
|
498
534
|
error: error instanceof Error ? error : new Error(String(error))
|
|
499
535
|
});
|
|
500
536
|
});
|
|
@@ -502,12 +538,20 @@ function createSyncClientHooks() {
|
|
|
502
538
|
active = false;
|
|
503
539
|
subscription?.unsubscribe();
|
|
504
540
|
};
|
|
505
|
-
}, [
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
541
|
+
}, [run]);
|
|
542
|
+
const settled = run != null && snapshot.run === run;
|
|
543
|
+
const rows = run == null ? EMPTY_ROWS : snapshot.rows;
|
|
544
|
+
const loading = ready && !settled;
|
|
545
|
+
const error = settled ? snapshot.error : null;
|
|
546
|
+
return useMemo(() => ({
|
|
547
|
+
rows,
|
|
548
|
+
loading,
|
|
549
|
+
error
|
|
550
|
+
}), [
|
|
551
|
+
rows,
|
|
552
|
+
loading,
|
|
553
|
+
error
|
|
509
554
|
]);
|
|
510
|
-
return state;
|
|
511
555
|
}
|
|
512
556
|
return {
|
|
513
557
|
SyncClientProvider,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/remap-live-row.ts","../src/create-hooks.tsx"],"sourcesContent":["import { Column, is, SQL } from \"drizzle-orm\";\n\n/** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */\nexport type SelectedFields = Record<string, unknown>;\n\n/**\n * Map a raw PGlite live-query row onto a Drizzle select's field keys.\n *\n * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which\n * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`\n * produces SQL `select \"assignee_id\"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.\n * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it\n * by name using the select's field metadata:\n *\n * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;\n * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;\n * - a nested selection object recurses;\n * - with no field map (a raw query) the row is returned unchanged.\n */\nexport function remapLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(selectedFields)) {\n if (is(field, Column)) {\n out[key] = row[field.name];\n } else if (is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[key];\n } else if (field != null && typeof field === \"object\") {\n out[key] = remapLiveRow(field as SelectedFields, row);\n } else {\n out[key] = row[key];\n }\n }\n return out;\n}\n\n// ─── Materialization-safe live reads (JOINs with same-named columns) ─────────────────────────────────\n//\n// Reading by the underlying column NAME (as `remapLiveRow` does) is unsound when a JOIN's tables share a\n// column name — `select({ courseTitle: course.title, moduleTitle: module.title })` compiles to a SELECT\n// with two `title` output columns. PGlite's `live` extension MATERIALISES the query and fails hard\n// (`column \"title\" specified more than once`); even a plain query would silently collapse both `title`s\n// into one value. The seam (`client.subscribeLiveRows`) fixes this by wrapping the query with a POSITIONAL\n// column-alias-list when it is handed `fields` — the unique aliases below — so every output column is\n// renamed to a distinct name. Rows then come back keyed by THOSE aliases, and `remapAliasedLiveRow` maps\n// them onto the select's field keys positionally.\n\n/** The prefix for the positional output aliases the live-rows seam renames a materialised query's columns to. */\nconst LIVE_FIELD_ALIAS_PREFIX = \"__pgx_c\";\n\n/** Assign a positional alias to the `index`-th output column: `__pgx_c0`, `__pgx_c1`, … (unique by index). */\nfunction liveFieldAliasAt(index: number): string {\n return `${LIVE_FIELD_ALIAS_PREFIX}${index}`;\n}\n\n/**\n * Flatten a Drizzle select's `selectedFields` into the ordered list of UNIQUE output aliases needed to\n * make its live query safe to materialise. The walk order (depth-first over the field keys, recursing\n * into nested selection objects) matches Drizzle's column-emission order in the compiled SQL, so the\n * `index`-th leaf here is the `index`-th output column there — the invariant the positional\n * column-alias-list depends on. Returns `undefined` for a raw query (no field map): the seam then leaves\n * the SQL unwrapped and rows stay keyed by the underlying column names ({@link remapLiveRow}).\n */\nexport function liveFieldAliases(selectedFields: SelectedFields | undefined): string[] | undefined {\n if (selectedFields == null) return undefined;\n const aliases: string[] = [];\n const walk = (fields: SelectedFields): void => {\n for (const field of Object.values(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n aliases.push(liveFieldAliasAt(aliases.length));\n } else if (field != null && typeof field === \"object\") {\n walk(field as SelectedFields);\n } else {\n aliases.push(liveFieldAliasAt(aliases.length));\n }\n }\n };\n walk(selectedFields);\n return aliases.length > 0 ? aliases : undefined;\n}\n\n/**\n * Map a live row that came back from the ALIAS-WRAPPED query (keyed by the positional `__pgx_cN` aliases\n * {@link liveFieldAliases} produced) onto the Drizzle select's field keys. Walks `selectedFields` in the\n * same order, so the Nth leaf reads `row[__pgx_cN]`; nested selections recurse. The alias-space\n * counterpart to {@link remapLiveRow} — which keys by the underlying column name and cannot survive a\n * same-named-column collision. Returns the row unchanged when there is no field map (a raw query).\n */\nexport function remapAliasedLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const cursor = { index: 0 };\n const walk = (fields: SelectedFields): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n } else if (field != null && typeof field === \"object\") {\n out[key] = walk(field as SelectedFields);\n } else {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n }\n }\n return out;\n };\n return walk(selectedFields);\n}\n","import type { LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport {\n type ClientPGlite,\n type LiveRowsSubscription,\n type MutationListOptions,\n type MutationSummaryDetail,\n type MutationSummarySubscription,\n type SyncClient,\n syncDebug,\n} from \"@pgxsinkit/client\";\nimport type { MutationSummary, SyncTableName, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { liveFieldAliases, remapAliasedLiveRow, remapLiveRow, type SelectedFields } from \"./remap-live-row\";\n\n/**\n * Minimal interface satisfied by every Drizzle select/query builder.\n * Calling `.toSQL()` extracts the SQL string and positional params without\n * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the\n * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys\n * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.\n */\ninterface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n readonly _?: { readonly selectedFields?: SelectedFields };\n}\n\n/**\n * Reactive read result. `hydrating` is true from mount until every consistency group the query reads —\n * eager OR lazy — has completed its initial catch-up (`client.groupReady`) and the caught-up rows have\n * been delivered to this subscription, not merely started its stream. Rows flow while it is true\n * (local/cached rows paint immediately; catch-up rows stream in), so render an empty state only when\n * `!loading && !hydrating` — zero rows before that means \"not loaded yet\", not \"empty\". A subscription\n * whose groups are all already caught up at mount (the steady-state fast path) clears `hydrating` at the\n * first snapshot with no extra work.\n */\ninterface LiveRowsState<TRows> {\n rows: TRows;\n loading: boolean;\n hydrating: boolean;\n error: Error | null;\n}\n\n/**\n * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).\n * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the\n * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.\n */\nfunction subscribeRawPglite<TRow extends Record<string, unknown>>(\n pglite: ClientPGlite,\n query: string,\n params: unknown[],\n onRows: (rows: TRow[]) => void,\n): Promise<LiveRowsSubscription<TRow>> {\n return pglite.live.query<TRow>(query, params).then((registered: LiveQuery<TRow>) => {\n const listener = (results: LiveQueryResults<TRow>) => onRows(results.rows);\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows,\n unsubscribe: () => void registered.unsubscribe(listener),\n };\n });\n}\n\nconst EMPTY_MUTATION_SUMMARY: MutationSummary = {\n pendingCount: 0,\n sendingCount: 0,\n ackedCount: 0,\n failedCount: 0,\n rejectedCount: 0,\n conflictedCount: 0,\n quarantinedCount: 0,\n unsettledCount: 0,\n settledCount: 0,\n};\n\n/**\n * Creates a set of React hooks and a context provider bound to a specific\n * `SyncTableRegistry` type. Call this once at the module level in your app:\n *\n * ```ts\n * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows, useLiveQueryRaw } =\n * createSyncClientHooks<typeof mySyncRegistry>();\n * ```\n */\nexport function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {\n const SyncClientContext = createContext<SyncClient<TRegistry> | null>(null);\n\n // ─── Provider ────────────────────────────────────────────────────────────\n\n function SyncClientProvider({ client, children }: { client: SyncClient<TRegistry> | null; children: ReactNode }) {\n return <SyncClientContext.Provider value={client}>{children}</SyncClientContext.Provider>;\n }\n\n function useSyncClient(): SyncClient<TRegistry> {\n const client = useContext(SyncClientContext);\n if (client == null) {\n throw new Error(\"[pgxsinkit] useSyncClient must be called inside <SyncClientProvider>\");\n }\n return client;\n }\n\n // ─── Raw SQL live hooks ───────────────────────────────────────────────────\n\n /**\n * Reactive raw-SQL query. This is the **unguarded** escape hatch: it does not participate in the\n * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a\n * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.\n * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.\n */\n function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: {\n params?: readonly unknown[];\n ready?: boolean;\n /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */\n pglite?: ClientPGlite;\n },\n ): { rows: TRow[]; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query\n // runs through the client's live-rows seam, so this hook works against the worker-attached client too\n // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).\n const overridePglite = options?.pglite;\n const ready = options?.ready ?? true;\n\n const paramsKey = JSON.stringify(options?.params ?? []);\n const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);\n\n const [state, setState] = useState<{ rows: TRow[]; loading: boolean; error: Error | null }>({\n rows: [],\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n const canRun = ready && (overridePglite != null || contextClient != null);\n if (!canRun) {\n setState({ rows: [], loading: ready, error: null });\n return;\n }\n\n let active = true;\n let subscription: LiveRowsSubscription<TRow> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n const onRows = (rows: TRow[]) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState({ rows, loading: false, error: null });\n }\n };\n\n // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`\n // wrapper the in-process client exposes, so behaviour is identical when no override is given.\n const subscribe = overridePglite\n ? subscribeRawPglite<TRow>(overridePglite, query, stableParams, onRows)\n : contextClient!.subscribeLiveRows<Record<string, unknown>>({ sql: query, params: stableParams }, (rows) =>\n onRows(rows as TRow[]),\n );\n\n void subscribe\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered as LiveRowsSubscription<TRow>;\n setState({ rows: registered.initialRows as TRow[], loading: false, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [contextClient, overridePglite, query, ready, stableParams]);\n\n return state;\n }\n\n function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },\n ): { row: TRow | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveRows<TRow>(query, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n // ─── Drizzle typed live hooks ─────────────────────────────────────────────\n\n /**\n * Shared implementation behind {@link useLiveDrizzleRows} and {@link useLiveQueryRaw}. Builds the query,\n * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional\n * `use`), activates + hydrates them, and only then subscribes the live query — so it is never\n * registered against an un-hydrated lazy relation (ADR-0021).\n */\n function useGuardedDrizzleLive<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; use?: readonly SyncTableName<TRegistry>[]; keepAliveMs?: number },\n ): LiveRowsState<TRows> {\n const contextClient = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n const useList = options?.use;\n // Per-subscription keep-alive hint (ADR-0040 decision 4). Read at subscribe time and forwarded to the\n // seam; changing it does not resubscribe (it is not a query input — only a retention preference at unmount,\n // honoured in worker mode). See `SubscribeLiveRowsInput.keepAliveMs`.\n const keepAliveMs = options?.keepAliveMs;\n const useKey = useList != null ? JSON.stringify(useList) : \"\";\n\n const queryInfo = useMemo(\n () => {\n if (contextClient == null) return null;\n const query = buildQuery(contextClient);\n return { sql: query.toSQL(), selectedFields: query._?.selectedFields };\n },\n // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design\n [contextClient, ...deps],\n );\n\n const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;\n\n const [state, setState] = useState<LiveRowsState<TRows>>({\n rows: [] as unknown as TRows,\n loading: ready,\n hydrating: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || contextClient == null || queryInfo == null) {\n setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });\n return;\n }\n\n const { sql, selectedFields } = queryInfo;\n // Render the query safe to MATERIALISE: hand the seam the select's unique field aliases so it wraps a\n // JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise PGlite's\n // live query refuses it (`column \"title\" specified more than once`) and same-named columns collapse.\n // With `fields` the rows come back keyed by those aliases, so map by alias; without a field map (a raw\n // query) the seam leaves the SQL unwrapped and rows stay name-keyed (`remapLiveRow`).\n const fields = liveFieldAliases(selectedFields);\n const mapRows = (rows: readonly unknown[]): TRows =>\n rows.map((row) =>\n fields\n ? remapAliasedLiveRow(selectedFields, row as Record<string, unknown>)\n : remapLiveRow(selectedFields, row as Record<string, unknown>),\n ) as unknown as TRows;\n\n let active = true;\n let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));\n\n // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), ACTIVATE them (streams\n // started, tripwire satisfied), THEN subscribe via the client's live-rows seam — so a query is never\n // registered against a dormant lazy relation (ADR-0021), and the same hook drives both the in-process\n // client (seam over `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).\n // Activation is NOT catch-up: the subscription registers immediately (local/cached rows paint, and an\n // offline client is never blocked behind the network), while `hydrating` stays true until the\n // subscription's `hydrated` promise resolves. That promise now spans EVERY referenced consistency\n // group (eager AND lazy) still catching up — not just the lazy ones — so a cold boot's eager catch-up\n // is covered too; when every referenced group is already ready at subscribe time the seam builds no\n // promise and `hydrating` clears at the first snapshot. The seam guarantees rows-before-signal (it\n // refreshes the live query against the caught-up store before resolving), so clearing `hydrating`\n // here can never present zero rows as \"empty\" while the catch-up rows are still in flight.\n void contextClient\n .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })\n .then(() => {\n if (!active) return undefined;\n return contextClient\n .subscribeLiveRows<Record<string, unknown>>(\n {\n sql: sql.sql,\n params: sql.params,\n ...(fields ? { fields } : {}),\n ...(useList ? { use: useList } : {}),\n ...(keepAliveMs != null ? { keepAliveMs } : {}),\n },\n (rows) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState((prev) => ({ rows: mapRows(rows), loading: false, hydrating: prev.hydrating, error: null }));\n }\n },\n )\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return undefined;\n }\n subscription = registered;\n // The initial render on the rail: \"updated → re-render\" covers only later diffs, so without\n // this line a first snapshot — including an honest zero-row one — is invisible in a debug log.\n syncDebug(\"live query initial → render\", {\n rows: registered.initialRows.length,\n hydrating: registered.hydrated != null,\n });\n setState((prev) => ({\n rows: mapRows(registered.initialRows),\n loading: false,\n hydrating: registered.hydrated != null ? prev.hydrating : false,\n error: null,\n }));\n if (registered.hydrated) {\n void registered.hydrated.then(() => {\n if (active) setState((prev) => ({ ...prev, hydrating: false }));\n });\n }\n return undefined;\n });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n rows: [] as unknown as TRows,\n loading: false,\n hydrating: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n // sqlKey/useKey are stable JSON snapshots; queryInfo is captured inside the effect.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo\n }, [contextClient, sqlKey, useKey, ready]);\n\n return state;\n }\n\n /**\n * Reactive query using a Drizzle select builder. The builder is re-created\n * whenever `deps` changes (same contract as `useEffect`). pgxsinkit scans the compiled SQL and\n * auto-activates any `lazy` relation the query reads — anywhere it appears (FROM, JOIN, subquery,\n * WHERE) — before subscribing. `use` (see {@link useLiveQueryRaw}) is an optional pre-activation hint,\n * not a requirement (ADR-0021).\n *\n * ```ts\n * const { rows } = useLiveDrizzleRows(\n * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),\n * [],\n * );\n * // rows is fully typed from the view definition — no casts needed\n * ```\n */\n function useLiveDrizzleRows<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; keepAliveMs?: number },\n ): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(buildQuery, deps, options);\n }\n\n function useLiveDrizzleRow<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; keepAliveMs?: number },\n ): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useGuardedDrizzleLive(buildQuery, deps, options);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n /**\n * The reactive query for a builder that embeds a raw `sql` fragment (ADR-0021): `use` names the `lazy`\n * relations it reads that the compiled-SQL scan can't see (a bare identifier inside raw SQL), so they\n * are guaranteed activated before it subscribes. The non-live counterpart of\n * `client.queryRaw({ use, build })`. Pure-Drizzle reads use `useLiveDrizzleRows` / `client.query((c) => …)`,\n * which auto-detect every relation and need no `use`.\n *\n * ```ts\n * const { rows, hydrating } = useLiveQueryRaw({\n * use: [\"archive\"],\n * build: (c) => c.drizzle.select().from(archiveTable).where(inArray(archiveTable.id, recentIds)),\n * deps: [recentIds],\n * });\n * ```\n */\n function useLiveQueryRaw<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n keepAliveMs?: number;\n }): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(args.build, args.deps ?? [], {\n ...(args.ready != null ? { ready: args.ready } : {}),\n ...(args.use ? { use: args.use } : {}),\n ...(args.keepAliveMs != null ? { keepAliveMs: args.keepAliveMs } : {}),\n });\n }\n\n function useLiveQueryRawRow<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n keepAliveMs?: number;\n }): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useLiveQueryRaw(args);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n // ─── Mutation-status hooks (slice 4) ─────────────────────────────────────\n\n /**\n * Reactive registry-wide mutation summary (`client.mutations.subscribeSummary`): per-status counts across\n * EVERY writable journal, folded to one {@link MutationSummary}. ONE subscription drives a global sync\n * indicator — no `hydrating` flag, because journals are local and never network-hydrated. Cheap enough to\n * mount permanently (ADR-0040 dedup: one registration regardless of subscriber count).\n */\n function useMutationSummary(options?: { ready?: boolean }): {\n summary: MutationSummary;\n loading: boolean;\n error: Error | null;\n } {\n const client = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n\n const [state, setState] = useState<{ summary: MutationSummary; loading: boolean; error: Error | null }>({\n summary: EMPTY_MUTATION_SUMMARY,\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || client == null) {\n setState({ summary: EMPTY_MUTATION_SUMMARY, loading: ready, error: null });\n return;\n }\n\n let active = true;\n let subscription: MutationSummarySubscription | undefined;\n setState((prev) => ({ summary: prev.summary, loading: true, error: null }));\n\n void client.mutations\n .subscribeSummary((summary) => {\n if (active) setState({ summary, loading: false, error: null });\n })\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered;\n setState({ summary: registered.initial, loading: false, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n summary: EMPTY_MUTATION_SUMMARY,\n loading: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [client, ready]);\n\n return state;\n }\n\n /**\n * Reactive filtered mutation detail list (`client.mutations.subscribe`): normalized journal rows across\n * every writable table, filtered by `table` / `entityKey` / `statuses` / `limit`, ordered newest-first.\n * Route/feature-scoped — mount it where a diagnostics view is open, not app-wide (prefer\n * {@link useMutationSummary} for a global indicator). No `hydrating` flag (journals are local).\n */\n function useMutationList(options?: MutationListOptions<TRegistry> & { ready?: boolean }): {\n rows: MutationSummaryDetail[];\n loading: boolean;\n error: Error | null;\n } {\n const client = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n // Split the `ready` UI flag off the query filters so it never becomes a filter.\n const { ready: _ready, ...filters } = options ?? {};\n void _ready;\n const filtersKey = JSON.stringify(filters);\n const stableFilters = useMemo<MutationListOptions<TRegistry>>(\n () => JSON.parse(filtersKey) as MutationListOptions<TRegistry>,\n [filtersKey],\n );\n\n const [state, setState] = useState<{ rows: MutationSummaryDetail[]; loading: boolean; error: Error | null }>({\n rows: [],\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || client == null) {\n setState({ rows: [], loading: ready, error: null });\n return;\n }\n\n let active = true;\n let subscription: { unsubscribe: () => void } | undefined;\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n void client.mutations\n .subscribe(stableFilters, (rows) => {\n if (active) setState({ rows, loading: false, error: null });\n })\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered;\n setState({ rows: registered.initial, loading: false, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n // stableFilters is the JSON-stable proxy for the filter inputs.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- filtersKey is the stable proxy for stableFilters\n }, [client, ready, filtersKey]);\n\n return state;\n }\n\n return {\n SyncClientProvider,\n useSyncClient,\n useLiveRows,\n useLiveRow,\n useLiveDrizzleRows,\n useLiveDrizzleRow,\n useLiveQueryRaw,\n useLiveQueryRawRow,\n useMutationSummary,\n useMutationList,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,aACd,gBACA,KACyB;CACzB,IAAI,kBAAkB,MAAM,OAAO;CACnC,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACtD,IAAI,GAAG,OAAO,MAAM,GAClB,IAAI,OAAO,IAAI,MAAM;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AC;EAE9B,OAAO;CACT;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/remap-live-row.ts","../src/create-hooks.tsx"],"sourcesContent":["import { Column, is, SQL } from \"drizzle-orm\";\n\n/** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */\nexport type SelectedFields = Record<string, unknown>;\n\n/**\n * Map a raw PGlite live-query row onto a Drizzle select's field keys.\n *\n * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which\n * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`\n * produces SQL `select \"assignee_id\"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.\n * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it\n * by name using the select's field metadata:\n *\n * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;\n * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;\n * - a nested selection object recurses;\n * - with no field map (a raw query) the row is returned unchanged.\n */\nexport function remapLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(selectedFields)) {\n if (is(field, Column)) {\n out[key] = row[field.name];\n } else if (is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[key];\n } else if (field != null && typeof field === \"object\") {\n out[key] = remapLiveRow(field as SelectedFields, row);\n } else {\n out[key] = row[key];\n }\n }\n return out;\n}\n\n// ─── Materialization-safe live reads (JOINs with same-named columns) ─────────────────────────────────\n//\n// Reading by the underlying column NAME (as `remapLiveRow` does) is unsound when a JOIN's tables share a\n// column name — `select({ courseTitle: course.title, moduleTitle: module.title })` compiles to a SELECT\n// with two `title` output columns. PGlite's `live` extension MATERIALISES the query and fails hard\n// (`column \"title\" specified more than once`); even a plain query would silently collapse both `title`s\n// into one value. The seam (`client.subscribeLiveRows`) fixes this by wrapping the query with a POSITIONAL\n// column-alias-list when it is handed `fields` — the unique aliases below — so every output column is\n// renamed to a distinct name. Rows then come back keyed by THOSE aliases, and `remapAliasedLiveRow` maps\n// them onto the select's field keys positionally.\n\n/** The prefix for the positional output aliases the live-rows seam renames a materialised query's columns to. */\nconst LIVE_FIELD_ALIAS_PREFIX = \"__pgx_c\";\n\n/** Assign a positional alias to the `index`-th output column: `__pgx_c0`, `__pgx_c1`, … (unique by index). */\nfunction liveFieldAliasAt(index: number): string {\n return `${LIVE_FIELD_ALIAS_PREFIX}${index}`;\n}\n\n/**\n * Flatten a Drizzle select's `selectedFields` into the ordered list of UNIQUE output aliases needed to\n * make its live query safe to materialise. The walk order (depth-first over the field keys, recursing\n * into nested selection objects) matches Drizzle's column-emission order in the compiled SQL, so the\n * `index`-th leaf here is the `index`-th output column there — the invariant the positional\n * column-alias-list depends on. Returns `undefined` for a raw query (no field map): the seam then leaves\n * the SQL unwrapped and rows stay keyed by the underlying column names ({@link remapLiveRow}).\n */\nexport function liveFieldAliases(selectedFields: SelectedFields | undefined): string[] | undefined {\n if (selectedFields == null) return undefined;\n const aliases: string[] = [];\n const walk = (fields: SelectedFields): void => {\n for (const field of Object.values(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n aliases.push(liveFieldAliasAt(aliases.length));\n } else if (field != null && typeof field === \"object\") {\n walk(field as SelectedFields);\n } else {\n aliases.push(liveFieldAliasAt(aliases.length));\n }\n }\n };\n walk(selectedFields);\n return aliases.length > 0 ? aliases : undefined;\n}\n\n/**\n * Map a live row that came back from the ALIAS-WRAPPED query (keyed by the positional `__pgx_cN` aliases\n * {@link liveFieldAliases} produced) onto the Drizzle select's field keys. Walks `selectedFields` in the\n * same order, so the Nth leaf reads `row[__pgx_cN]`; nested selections recurse. The alias-space\n * counterpart to {@link remapLiveRow} — which keys by the underlying column name and cannot survive a\n * same-named-column collision. Returns the row unchanged when there is no field map (a raw query).\n */\nexport function remapAliasedLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const cursor = { index: 0 };\n const walk = (fields: SelectedFields): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(fields)) {\n if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n } else if (field != null && typeof field === \"object\") {\n out[key] = walk(field as SelectedFields);\n } else {\n out[key] = row[liveFieldAliasAt(cursor.index)];\n cursor.index += 1;\n }\n }\n return out;\n };\n return walk(selectedFields);\n}\n","import type { LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport {\n type ClientPGlite,\n type LiveRowsSubscription,\n type MutationListOptions,\n type MutationSummaryDetail,\n type MutationSummarySubscription,\n type SyncClient,\n syncDebug,\n} from \"@pgxsinkit/client\";\nimport type { MutationSummary, SyncTableName, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { liveFieldAliases, remapAliasedLiveRow, remapLiveRow, type SelectedFields } from \"./remap-live-row\";\n\n/**\n * Minimal interface satisfied by every Drizzle select/query builder.\n * Calling `.toSQL()` extracts the SQL string and positional params without\n * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the\n * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys\n * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.\n */\ninterface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n readonly _?: { readonly selectedFields?: SelectedFields };\n}\n\n/**\n * Reactive read result. `hydrating` is true from mount until every consistency group the query reads —\n * eager OR lazy — has completed its initial catch-up (`client.groupReady`) and the caught-up rows have\n * been delivered to this subscription, not merely started its stream. Rows flow while it is true\n * (local/cached rows paint immediately; catch-up rows stream in), so render an empty state only when\n * `!loading && !hydrating` — zero rows before that means \"not loaded yet\", not \"empty\". A subscription\n * whose groups are all already caught up at mount (the steady-state fast path) clears `hydrating` at the\n * first snapshot with no extra work.\n */\ninterface LiveRowsState<TRows> {\n rows: TRows;\n loading: boolean;\n hydrating: boolean;\n error: Error | null;\n}\n\n/**\n * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).\n * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the\n * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.\n */\nfunction subscribeRawPglite<TRow extends Record<string, unknown>>(\n pglite: ClientPGlite,\n query: string,\n params: unknown[],\n onRows: (rows: TRow[]) => void,\n): Promise<LiveRowsSubscription<TRow>> {\n return pglite.live.query<TRow>(query, params).then((registered: LiveQuery<TRow>) => {\n const listener = (results: LiveQueryResults<TRow>) => onRows(results.rows);\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows,\n unsubscribe: () => void registered.unsubscribe(listener),\n };\n });\n}\n\n/**\n * Shared \"no subscription yet\" rows. The hooks DERIVE their return value during render, so this has to be\n * one stable identity — a fresh `[]` per render would defeat the memoised return object and re-fire every\n * consumer effect that depends on `rows`.\n */\nconst EMPTY_ROWS: never[] = [];\n\nconst EMPTY_MUTATION_SUMMARY: MutationSummary = {\n pendingCount: 0,\n sendingCount: 0,\n ackedCount: 0,\n failedCount: 0,\n rejectedCount: 0,\n conflictedCount: 0,\n quarantinedCount: 0,\n unsettledCount: 0,\n settledCount: 0,\n};\n\n/**\n * Creates a set of React hooks and a context provider bound to a specific\n * `SyncTableRegistry` type. Call this once at the module level in your app:\n *\n * ```ts\n * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows, useLiveQueryRaw } =\n * createSyncClientHooks<typeof mySyncRegistry>();\n * ```\n */\nexport function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {\n const SyncClientContext = createContext<SyncClient<TRegistry> | null>(null);\n\n // ─── Provider ────────────────────────────────────────────────────────────\n\n function SyncClientProvider({ client, children }: { client: SyncClient<TRegistry> | null; children: ReactNode }) {\n return <SyncClientContext.Provider value={client}>{children}</SyncClientContext.Provider>;\n }\n\n function useSyncClient(): SyncClient<TRegistry> {\n const client = useContext(SyncClientContext);\n if (client == null) {\n throw new Error(\"[pgxsinkit] useSyncClient must be called inside <SyncClientProvider>\");\n }\n return client;\n }\n\n // ─── Raw SQL live hooks ───────────────────────────────────────────────────\n\n /**\n * Reactive raw-SQL query. This is the **unguarded** escape hatch: it does not participate in the\n * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a\n * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.\n * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.\n *\n * `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a\n * `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes\n * (`loading: true`) instead of briefly reporting zero rows — the same \"keep the previous rows while\n * loading\" policy already applied across a query change.\n */\n function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: {\n params?: readonly unknown[];\n ready?: boolean;\n /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */\n pglite?: ClientPGlite;\n },\n ): { rows: TRow[]; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query\n // runs through the client's live-rows seam, so this hook works against the worker-attached client too\n // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).\n const overridePglite = options?.pglite;\n const ready = options?.ready ?? true;\n\n const paramsKey = JSON.stringify(options?.params ?? []);\n const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);\n\n const canRun = ready && (overridePglite != null || contextClient != null);\n // The run token: ONE object whose identity changes exactly when the subscription inputs change, and\n // `null` when the hook cannot subscribe. It is the effect's only dependency AND the tag on every\n // snapshot the effect writes, so `loading` is derived during render (\"does the snapshot belong to the\n // current run?\") instead of being written synchronously from the effect.\n const run = useMemo(\n () => (canRun ? { query, params: stableParams, client: contextClient, pglite: overridePglite } : null),\n [canRun, query, stableParams, contextClient, overridePglite],\n );\n\n const [snapshot, setSnapshot] = useState<{ run: typeof run; rows: TRow[]; error: Error | null }>({\n run: null,\n rows: EMPTY_ROWS,\n error: null,\n });\n\n useEffect(() => {\n if (run == null) return;\n\n let active = true;\n let subscription: LiveRowsSubscription<TRow> | undefined;\n\n const onRows = (rows: TRow[]) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setSnapshot({ run, rows, error: null });\n }\n };\n\n // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`\n // wrapper the in-process client exposes, so behaviour is identical when no override is given.\n const subscribe = run.pglite\n ? subscribeRawPglite<TRow>(run.pglite, run.query, run.params, onRows)\n : run.client!.subscribeLiveRows<Record<string, unknown>>({ sql: run.query, params: run.params }, (rows) =>\n onRows(rows as TRow[]),\n );\n\n void subscribe\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered as LiveRowsSubscription<TRow>;\n setSnapshot({ run, rows: registered.initialRows as TRow[], error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setSnapshot({ run, rows: EMPTY_ROWS, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [run]);\n\n // Derived, never stored: a snapshot is authoritative only for the run it was tagged with. Holding the\n // previous run's rows until the new one settles is exactly what the old synchronous\n // `setState({ rows: prev.rows, loading: true })` did; no client (or `ready: false`) reads as no rows.\n const settled = run != null && snapshot.run === run;\n const rows = run == null ? EMPTY_ROWS : snapshot.rows;\n const loading = ready && !settled;\n const error = settled ? snapshot.error : null;\n\n return useMemo(() => ({ rows, loading, error }), [rows, loading, error]);\n }\n\n function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },\n ): { row: TRow | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveRows<TRow>(query, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n // ─── Drizzle typed live hooks ─────────────────────────────────────────────\n\n /**\n * Shared implementation behind {@link useLiveDrizzleRows} and {@link useLiveQueryRaw}. Builds the query,\n * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional\n * `use`), activates + hydrates them, and only then subscribes the live query — so it is never\n * registered against an un-hydrated lazy relation (ADR-0021).\n *\n * `loading`/`hydrating`/`rows` are derived from which subscription the latest snapshot belongs to, so a\n * `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes\n * (`loading: true`) instead of briefly reporting zero rows — the same \"keep the previous rows while\n * loading\" policy already applied across a query change.\n */\n function useGuardedDrizzleLive<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; use?: readonly SyncTableName<TRegistry>[]; keepAliveMs?: number },\n ): LiveRowsState<TRows> {\n const contextClient = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n const useList = options?.use;\n // Per-subscription keep-alive hint (ADR-0040 decision 4). Read at subscribe time and forwarded to the\n // seam; changing it does not resubscribe (it is not a query input — only a retention preference at unmount,\n // honoured in worker mode). See `SubscribeLiveRowsInput.keepAliveMs`.\n const keepAliveMs = options?.keepAliveMs;\n const useKey = useList != null ? JSON.stringify(useList) : \"\";\n\n const queryInfo = useMemo(\n () => {\n if (contextClient == null) return null;\n const query = buildQuery(contextClient);\n return { sql: query.toSQL(), selectedFields: query._?.selectedFields };\n },\n // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design\n [contextClient, ...deps],\n );\n\n const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;\n\n // The run token: ONE object whose identity changes exactly when the subscription must be rebuilt, and\n // `null` when the hook cannot subscribe. It is the effect's only dependency AND the tag on every\n // snapshot the effect writes, so `loading`/`hydrating` are derived during render instead of being\n // written synchronously from the effect. `keepAliveMs` rides along inside the token precisely because\n // it is NOT a dep: it is read at subscribe time and never resubscribes (ADR-0040 decision 4, above).\n const run = useMemo(\n () =>\n ready && contextClient != null && queryInfo != null\n ? { client: contextClient, queryInfo, useList, keepAliveMs }\n : null,\n // sqlKey/useKey are stable JSON snapshots; queryInfo/useList/keepAliveMs are captured in the token.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo\n [contextClient, sqlKey, useKey, ready],\n );\n\n const [snapshot, setSnapshot] = useState<{\n run: typeof run;\n rows: TRows;\n hydrated: boolean;\n error: Error | null;\n }>({\n run: null,\n rows: EMPTY_ROWS as unknown as TRows,\n hydrated: false,\n error: null,\n });\n\n useEffect(() => {\n if (run == null) return;\n\n const { sql, selectedFields } = run.queryInfo;\n // Render the query safe to MATERIALISE: hand the seam the select's unique field aliases so it wraps a\n // JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise PGlite's\n // live query refuses it (`column \"title\" specified more than once`) and same-named columns collapse.\n // With `fields` the rows come back keyed by those aliases, so map by alias; without a field map (a raw\n // query) the seam leaves the SQL unwrapped and rows stay name-keyed (`remapLiveRow`).\n const fields = liveFieldAliases(selectedFields);\n const mapRows = (rows: readonly unknown[]): TRows =>\n rows.map((row) =>\n fields\n ? remapAliasedLiveRow(selectedFields, row as Record<string, unknown>)\n : remapLiveRow(selectedFields, row as Record<string, unknown>),\n ) as unknown as TRows;\n\n let active = true;\n let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;\n\n // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), ACTIVATE them (streams\n // started, tripwire satisfied), THEN subscribe via the client's live-rows seam — so a query is never\n // registered against a dormant lazy relation (ADR-0021), and the same hook drives both the in-process\n // client (seam over `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).\n // Activation is NOT catch-up: the subscription registers immediately (local/cached rows paint, and an\n // offline client is never blocked behind the network), while `hydrating` stays true until the\n // subscription's `hydrated` promise resolves. That promise now spans EVERY referenced consistency\n // group (eager AND lazy) still catching up — not just the lazy ones — so a cold boot's eager catch-up\n // is covered too; when every referenced group is already ready at subscribe time the seam builds no\n // promise and `hydrating` clears at the first snapshot. The seam guarantees rows-before-signal (it\n // refreshes the live query against the caught-up store before resolving), so clearing `hydrating`\n // here can never present zero rows as \"empty\" while the catch-up rows are still in flight.\n void run.client\n .prepareQuery({ sql: sql.sql, ...(run.useList ? { use: run.useList } : {}) })\n .then(() => {\n if (!active) return undefined;\n return run.client\n .subscribeLiveRows<Record<string, unknown>>(\n {\n sql: sql.sql,\n params: sql.params,\n ...(fields ? { fields } : {}),\n ...(run.useList ? { use: run.useList } : {}),\n ...(run.keepAliveMs != null ? { keepAliveMs: run.keepAliveMs } : {}),\n },\n (rows) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n // A diff can land before the initial snapshot, so carry `hydrated` over only when the\n // previous snapshot belongs to THIS run — otherwise it is the previous run's flag.\n setSnapshot((prev) => ({\n run,\n rows: mapRows(rows),\n hydrated: prev.run === run ? prev.hydrated : false,\n error: null,\n }));\n }\n },\n )\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return undefined;\n }\n subscription = registered;\n // The initial render on the rail: \"updated → re-render\" covers only later diffs, so without\n // this line a first snapshot — including an honest zero-row one — is invisible in a debug log.\n syncDebug(\"live query initial → render\", {\n rows: registered.initialRows.length,\n hydrating: registered.hydrated != null,\n });\n // No `hydrated` promise ⇒ every referenced group was already caught up at subscribe time, so\n // this first snapshot IS the hydrated one (the steady-state fast path).\n setSnapshot({\n run,\n rows: mapRows(registered.initialRows),\n hydrated: registered.hydrated == null,\n error: null,\n });\n if (registered.hydrated) {\n void registered.hydrated.then(() => {\n if (active) setSnapshot((prev) => (prev.run === run ? { ...prev, hydrated: true } : prev));\n });\n }\n return undefined;\n });\n })\n .catch((error: unknown) => {\n if (active) {\n setSnapshot({\n run,\n rows: EMPTY_ROWS as unknown as TRows,\n hydrated: true,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [run]);\n\n // Derived, never stored: a snapshot is authoritative only for the run it was tagged with, and it is\n // \"hydrated\" only once the subscription's `hydrated` promise resolved (or there was none to await).\n // A failed run settles hydrated so an error is not reported as a permanent catch-up, and with no run\n // there is nothing catching up, so `hydrating` is false (`loading` alone reports the missing client).\n const settled = run != null && snapshot.run === run;\n const rows = run == null ? (EMPTY_ROWS as unknown as TRows) : snapshot.rows;\n const loading = ready && !settled;\n const hydrating = run != null && !(settled && snapshot.hydrated);\n const error = settled ? snapshot.error : null;\n\n return useMemo(() => ({ rows, loading, hydrating, error }), [rows, loading, hydrating, error]);\n }\n\n /**\n * Reactive query using a Drizzle select builder. The builder is re-created\n * whenever `deps` changes (same contract as `useEffect`). pgxsinkit scans the compiled SQL and\n * auto-activates any `lazy` relation the query reads — anywhere it appears (FROM, JOIN, subquery,\n * WHERE) — before subscribing. `use` (see {@link useLiveQueryRaw}) is an optional pre-activation hint,\n * not a requirement (ADR-0021).\n *\n * ```ts\n * const { rows } = useLiveDrizzleRows(\n * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),\n * [],\n * );\n * // rows is fully typed from the view definition — no casts needed\n * ```\n */\n function useLiveDrizzleRows<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; keepAliveMs?: number },\n ): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(buildQuery, deps, options);\n }\n\n function useLiveDrizzleRow<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; keepAliveMs?: number },\n ): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useGuardedDrizzleLive(buildQuery, deps, options);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n /**\n * The reactive query for a builder that embeds a raw `sql` fragment (ADR-0021): `use` names the `lazy`\n * relations it reads that the compiled-SQL scan can't see (a bare identifier inside raw SQL), so they\n * are guaranteed activated before it subscribes. The non-live counterpart of\n * `client.queryRaw({ use, build })`. Pure-Drizzle reads use `useLiveDrizzleRows` / `client.query((c) => …)`,\n * which auto-detect every relation and need no `use`.\n *\n * ```ts\n * const { rows, hydrating } = useLiveQueryRaw({\n * use: [\"archive\"],\n * build: (c) => c.drizzle.select().from(archiveTable).where(inArray(archiveTable.id, recentIds)),\n * deps: [recentIds],\n * });\n * ```\n */\n function useLiveQueryRaw<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n keepAliveMs?: number;\n }): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(args.build, args.deps ?? [], {\n ...(args.ready != null ? { ready: args.ready } : {}),\n ...(args.use ? { use: args.use } : {}),\n ...(args.keepAliveMs != null ? { keepAliveMs: args.keepAliveMs } : {}),\n });\n }\n\n function useLiveQueryRawRow<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n keepAliveMs?: number;\n }): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useLiveQueryRaw(args);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n // ─── Mutation-status hooks (slice 4) ─────────────────────────────────────\n\n /**\n * Reactive registry-wide mutation summary (`client.mutations.subscribeSummary`): per-status counts across\n * EVERY writable journal, folded to one {@link MutationSummary}. ONE subscription drives a global sync\n * indicator — no `hydrating` flag, because journals are local and never network-hydrated. Cheap enough to\n * mount permanently (ADR-0040 dedup: one registration regardless of subscriber count).\n *\n * `loading` and `summary` are derived from which subscription the latest snapshot belongs to, so a\n * `ready: false → true` interlude keeps the previous summary while it re-subscribes (`loading: true`)\n * instead of briefly reporting the zero summary.\n */\n function useMutationSummary(options?: { ready?: boolean }): {\n summary: MutationSummary;\n loading: boolean;\n error: Error | null;\n } {\n const client = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n\n // The run token (see `useLiveRows`): the client is the only subscription input, wrapped so that a\n // `ready` flip yields a fresh identity — otherwise the pre-flip snapshot would read as settled.\n const run = useMemo(() => (ready && client != null ? { client } : null), [ready, client]);\n\n const [snapshot, setSnapshot] = useState<{ run: typeof run; summary: MutationSummary; error: Error | null }>({\n run: null,\n summary: EMPTY_MUTATION_SUMMARY,\n error: null,\n });\n\n useEffect(() => {\n if (run == null) return;\n\n let active = true;\n let subscription: MutationSummarySubscription | undefined;\n\n void run.client.mutations\n .subscribeSummary((summary) => {\n if (active) setSnapshot({ run, summary, error: null });\n })\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered;\n setSnapshot({ run, summary: registered.initial, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setSnapshot({\n run,\n summary: EMPTY_MUTATION_SUMMARY,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [run]);\n\n // Derived, never stored — see `useLiveRows`.\n const settled = run != null && snapshot.run === run;\n const summary = run == null ? EMPTY_MUTATION_SUMMARY : snapshot.summary;\n const loading = ready && !settled;\n const error = settled ? snapshot.error : null;\n\n return useMemo(() => ({ summary, loading, error }), [summary, loading, error]);\n }\n\n /**\n * Reactive filtered mutation detail list (`client.mutations.subscribe`): normalized journal rows across\n * every writable table, filtered by `table` / `entityKey` / `statuses` / `limit`, ordered newest-first.\n * Route/feature-scoped — mount it where a diagnostics view is open, not app-wide (prefer\n * {@link useMutationSummary} for a global indicator). No `hydrating` flag (journals are local).\n *\n * `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a\n * `ready: false → true` interlude with unchanged filters keeps the previous rows while it re-subscribes\n * (`loading: true`) instead of briefly reporting zero rows — the same \"keep the previous rows while\n * loading\" policy already applied across a filter change.\n */\n function useMutationList(options?: MutationListOptions<TRegistry> & { ready?: boolean }): {\n rows: MutationSummaryDetail[];\n loading: boolean;\n error: Error | null;\n } {\n const client = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n // Split the `ready` UI flag off the query filters so it never becomes a filter.\n const { ready: _ready, ...filters } = options ?? {};\n void _ready;\n const filtersKey = JSON.stringify(filters);\n const stableFilters = useMemo<MutationListOptions<TRegistry>>(\n () => JSON.parse(filtersKey) as MutationListOptions<TRegistry>,\n [filtersKey],\n );\n\n // The run token (see `useLiveRows`): the client and the JSON-stable filters are the only subscription\n // inputs, so its identity changes exactly when the subscription must be rebuilt — which lets `loading`\n // be derived during render instead of written synchronously from the effect.\n const run = useMemo(\n () => (ready && client != null ? { client, filters: stableFilters } : null),\n [ready, client, stableFilters],\n );\n\n const [snapshot, setSnapshot] = useState<{ run: typeof run; rows: MutationSummaryDetail[]; error: Error | null }>({\n run: null,\n rows: EMPTY_ROWS,\n error: null,\n });\n\n useEffect(() => {\n if (run == null) return;\n\n let active = true;\n let subscription: { unsubscribe: () => void } | undefined;\n\n void run.client.mutations\n .subscribe(run.filters, (rows) => {\n if (active) setSnapshot({ run, rows, error: null });\n })\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered;\n setSnapshot({ run, rows: registered.initial, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setSnapshot({ run, rows: EMPTY_ROWS, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [run]);\n\n // Derived, never stored — see `useLiveRows`.\n const settled = run != null && snapshot.run === run;\n const rows = run == null ? EMPTY_ROWS : snapshot.rows;\n const loading = ready && !settled;\n const error = settled ? snapshot.error : null;\n\n return useMemo(() => ({ rows, loading, error }), [rows, loading, error]);\n }\n\n return {\n SyncClientProvider,\n useSyncClient,\n useLiveRows,\n useLiveRow,\n useLiveDrizzleRows,\n useLiveDrizzleRow,\n useLiveQueryRaw,\n useLiveQueryRawRow,\n useMutationSummary,\n useMutationList,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,aACd,gBACA,KACyB;CACzB,IAAI,kBAAkB,MAAM,OAAO;CACnC,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACtD,IAAI,GAAG,OAAO,MAAM,GAClB,IAAI,OAAO,IAAI,MAAM;MAChB,IAAI,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,IAAI,OAAO,GAChD,IAAI,OAAO,IAAI;MACV,IAAI,SAAS,QAAQ,OAAO,UAAU,UAC3C,IAAI,OAAO,aAAa,OAAyB,GAAG;MAEpD,IAAI,OAAO,IAAI;CAGnB,OAAO;AACT;;AAcA,IAAM,0BAA0B;;AAGhC,SAAS,iBAAiB,OAAuB;CAC/C,OAAO,GAAG,0BAA0B;AACtC;;;;;;;;;AAUA,SAAgB,iBAAiB,gBAAkE;CACjG,IAAI,kBAAkB,MAAM,OAAO,KAAA;CACnC,MAAM,UAAoB,CAAC;CAC3B,MAAM,QAAQ,WAAiC;EAC7C,KAAK,MAAM,SAAS,OAAO,OAAO,MAAM,GACtC,IAAI,GAAG,OAAO,MAAM,KAAK,GAAG,OAAO,GAAG,KAAK,GAAG,OAAO,IAAI,OAAO,GAC9D,QAAQ,KAAK,iBAAiB,QAAQ,M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G,CAAC,GAAG,CAAC;EAGR,MAAM,UAAU,OAAO,QAAQ,SAAS,QAAQ;EAChD,MAAM,OAAO,OAAO,OAAO,aAAa,SAAS;EACjD,MAAM,UAAU,SAAS,CAAC;EAC1B,MAAM,QAAQ,UAAU,SAAS,QAAQ;EAEzC,OAAO,eAAe;GAAE;GAAM;GAAS;EAAM,IAAI;GAAC;GAAM;GAAS;EAAK,CAAC;CACzE;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pgxsinkit/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"tanstack-intent"
|
|
6
6
|
],
|
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
"build": "bun --cwd ../.. run build:public-packages"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@pgxsinkit/client": "0.
|
|
31
|
-
"@pgxsinkit/contracts": "0.
|
|
30
|
+
"@pgxsinkit/client": "0.3.0",
|
|
31
|
+
"@pgxsinkit/contracts": "0.3.0"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
|
-
"@electric-sql/pglite": ">=0.5.
|
|
34
|
+
"@electric-sql/pglite": ">=0.5.5-pgx.0 <0.5.5",
|
|
35
35
|
"drizzle-orm": "1.0.0-rc.4",
|
|
36
36
|
"react": ">=19.2.8"
|
|
37
37
|
},
|
package/skills/react/SKILL.md
CHANGED
|
@@ -16,7 +16,7 @@ metadata:
|
|
|
16
16
|
type: framework
|
|
17
17
|
framework: react
|
|
18
18
|
library: "@pgxsinkit/react"
|
|
19
|
-
library_version: "0.
|
|
19
|
+
library_version: "0.3.0"
|
|
20
20
|
source: https://pgxsinkit.github.io/
|
|
21
21
|
requires:
|
|
22
22
|
- react
|
|
@@ -67,9 +67,10 @@ if (rows.length === 0) return <EmptyState />;
|
|
|
67
67
|
## Gate authenticated lazy groups until the session exists
|
|
68
68
|
|
|
69
69
|
A live query that references one `subscription: "lazy"` relation activates its **whole consistency
|
|
70
|
-
group**.
|
|
71
|
-
|
|
72
|
-
|
|
70
|
+
group**. It subscribes with the claims available at that moment. If the group's row filters return
|
|
71
|
+
`DENY_ALL_PREDICATE` without a user claim, mounting the query while auth is unresolved subscribes
|
|
72
|
+
anonymously — the control plane grants nothing, and the group stays empty rather than filling in when the
|
|
73
|
+
session arrives.
|
|
73
74
|
|
|
74
75
|
Use the hook's `ready` option to make first activation coincide with the authenticated session:
|
|
75
76
|
|
|
@@ -82,9 +83,9 @@ useLiveDrizzleRows((client) => client.drizzle.select({ id: workflowView.id }).fr
|
|
|
82
83
|
```
|
|
83
84
|
|
|
84
85
|
You no longer need a separate activator component for writes. An ordinary optimistic create/update/delete
|
|
85
|
-
self-activates its target's lazy group at enqueue, so the Postgres commit echoes back
|
|
86
|
-
retires the acknowledged journal row on its own. But that write-triggered activation still uses the
|
|
87
|
-
available at the time, so gate the **write** on auth the same way — do not write to an authenticated-only
|
|
86
|
+
self-activates its target's lazy group at enqueue, so the Postgres commit echoes back down the read path
|
|
87
|
+
and retires the acknowledged journal row on its own. But that write-triggered activation still uses the
|
|
88
|
+
claims available at the time, so gate the **write** on auth the same way — do not write to an authenticated-only
|
|
88
89
|
group before the session exists. (`updateBlind` is different: it has no overlay, does not activate its
|
|
89
90
|
group, and deliberately retires on the authoritative ack without an echo.) Activating a claims-denied group
|
|
90
91
|
with no token — by read or by write — now logs a `console.warn` naming the group.
|
|
@@ -116,7 +117,7 @@ to that safe shape, so this only affects hand-written raw SQL.
|
|
|
116
117
|
The read hooks are read-only. Mutate via `client.tables.<table>.create/update/delete` (or
|
|
117
118
|
`useSyncClient()` inside a component). Each call stages an optimistic local write (the live query
|
|
118
119
|
re-renders this frame) and **flushes on enqueue** — the optimistic overlay clears when the server value
|
|
119
|
-
streams back
|
|
120
|
+
streams back down the read path. See the `core` skill for the write model and `operating` for convergence
|
|
120
121
|
cadence and the `globalThis.__pgxsinkitDebug` latency instrumentation.
|
|
121
122
|
|
|
122
123
|
## Common mistakes
|
|
@@ -127,8 +128,8 @@ cadence and the `globalThis.__pgxsinkitDebug` latency instrumentation.
|
|
|
127
128
|
saturates the single WASM thread.
|
|
128
129
|
- Mutating local tables directly instead of through `client.tables.<t>` (the one write path).
|
|
129
130
|
- Reading before the client is ready instead of gating with `ready: false`.
|
|
130
|
-
- Reading OR writing an authenticated lazy group before auth resolves — it
|
|
131
|
-
claims (now flagged by a console warning)
|
|
132
|
-
on
|
|
131
|
+
- Reading OR writing an authenticated lazy group before auth resolves — it subscribes against anonymous
|
|
132
|
+
claims (now flagged by a console warning), is granted nothing, and stays empty. Gate on the session, not
|
|
133
|
+
on a manual activator (writes self-activate their group).
|
|
133
134
|
|
|
134
135
|
Reference: <https://pgxsinkit.github.io/>.
|
package/src/create-hooks.tsx
CHANGED
|
@@ -63,6 +63,13 @@ function subscribeRawPglite<TRow extends Record<string, unknown>>(
|
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Shared "no subscription yet" rows. The hooks DERIVE their return value during render, so this has to be
|
|
68
|
+
* one stable identity — a fresh `[]` per render would defeat the memoised return object and re-fire every
|
|
69
|
+
* consumer effect that depends on `rows`.
|
|
70
|
+
*/
|
|
71
|
+
const EMPTY_ROWS: never[] = [];
|
|
72
|
+
|
|
66
73
|
const EMPTY_MUTATION_SUMMARY: MutationSummary = {
|
|
67
74
|
pendingCount: 0,
|
|
68
75
|
sendingCount: 0,
|
|
@@ -108,6 +115,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
108
115
|
* lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a
|
|
109
116
|
* `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.
|
|
110
117
|
* Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.
|
|
118
|
+
*
|
|
119
|
+
* `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a
|
|
120
|
+
* `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes
|
|
121
|
+
* (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
|
|
122
|
+
* loading" policy already applied across a query change.
|
|
111
123
|
*/
|
|
112
124
|
function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(
|
|
113
125
|
query: string,
|
|
@@ -128,36 +140,40 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
128
140
|
const paramsKey = JSON.stringify(options?.params ?? []);
|
|
129
141
|
const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);
|
|
130
142
|
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
143
|
+
const canRun = ready && (overridePglite != null || contextClient != null);
|
|
144
|
+
// The run token: ONE object whose identity changes exactly when the subscription inputs change, and
|
|
145
|
+
// `null` when the hook cannot subscribe. It is the effect's only dependency AND the tag on every
|
|
146
|
+
// snapshot the effect writes, so `loading` is derived during render ("does the snapshot belong to the
|
|
147
|
+
// current run?") instead of being written synchronously from the effect.
|
|
148
|
+
const run = useMemo(
|
|
149
|
+
() => (canRun ? { query, params: stableParams, client: contextClient, pglite: overridePglite } : null),
|
|
150
|
+
[canRun, query, stableParams, contextClient, overridePglite],
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
const [snapshot, setSnapshot] = useState<{ run: typeof run; rows: TRow[]; error: Error | null }>({
|
|
154
|
+
run: null,
|
|
155
|
+
rows: EMPTY_ROWS,
|
|
134
156
|
error: null,
|
|
135
157
|
});
|
|
136
158
|
|
|
137
159
|
useEffect(() => {
|
|
138
|
-
|
|
139
|
-
if (!canRun) {
|
|
140
|
-
setState({ rows: [], loading: ready, error: null });
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
160
|
+
if (run == null) return;
|
|
143
161
|
|
|
144
162
|
let active = true;
|
|
145
163
|
let subscription: LiveRowsSubscription<TRow> | undefined;
|
|
146
164
|
|
|
147
|
-
setState((prev) => ({ rows: prev.rows, loading: true, error: null }));
|
|
148
|
-
|
|
149
165
|
const onRows = (rows: TRow[]) => {
|
|
150
166
|
if (active) {
|
|
151
167
|
syncDebug("live query updated → re-render", { rows: rows.length });
|
|
152
|
-
|
|
168
|
+
setSnapshot({ run, rows, error: null });
|
|
153
169
|
}
|
|
154
170
|
};
|
|
155
171
|
|
|
156
172
|
// The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`
|
|
157
173
|
// wrapper the in-process client exposes, so behaviour is identical when no override is given.
|
|
158
|
-
const subscribe =
|
|
159
|
-
? subscribeRawPglite<TRow>(
|
|
160
|
-
:
|
|
174
|
+
const subscribe = run.pglite
|
|
175
|
+
? subscribeRawPglite<TRow>(run.pglite, run.query, run.params, onRows)
|
|
176
|
+
: run.client!.subscribeLiveRows<Record<string, unknown>>({ sql: run.query, params: run.params }, (rows) =>
|
|
161
177
|
onRows(rows as TRow[]),
|
|
162
178
|
);
|
|
163
179
|
|
|
@@ -168,11 +184,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
168
184
|
return;
|
|
169
185
|
}
|
|
170
186
|
subscription = registered as LiveRowsSubscription<TRow>;
|
|
171
|
-
|
|
187
|
+
setSnapshot({ run, rows: registered.initialRows as TRow[], error: null });
|
|
172
188
|
})
|
|
173
189
|
.catch((error: unknown) => {
|
|
174
190
|
if (active) {
|
|
175
|
-
|
|
191
|
+
setSnapshot({ run, rows: EMPTY_ROWS, error: error instanceof Error ? error : new Error(String(error)) });
|
|
176
192
|
}
|
|
177
193
|
});
|
|
178
194
|
|
|
@@ -180,9 +196,17 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
180
196
|
active = false;
|
|
181
197
|
subscription?.unsubscribe();
|
|
182
198
|
};
|
|
183
|
-
}, [
|
|
199
|
+
}, [run]);
|
|
200
|
+
|
|
201
|
+
// Derived, never stored: a snapshot is authoritative only for the run it was tagged with. Holding the
|
|
202
|
+
// previous run's rows until the new one settles is exactly what the old synchronous
|
|
203
|
+
// `setState({ rows: prev.rows, loading: true })` did; no client (or `ready: false`) reads as no rows.
|
|
204
|
+
const settled = run != null && snapshot.run === run;
|
|
205
|
+
const rows = run == null ? EMPTY_ROWS : snapshot.rows;
|
|
206
|
+
const loading = ready && !settled;
|
|
207
|
+
const error = settled ? snapshot.error : null;
|
|
184
208
|
|
|
185
|
-
return
|
|
209
|
+
return useMemo(() => ({ rows, loading, error }), [rows, loading, error]);
|
|
186
210
|
}
|
|
187
211
|
|
|
188
212
|
function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(
|
|
@@ -200,6 +224,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
200
224
|
* then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional
|
|
201
225
|
* `use`), activates + hydrates them, and only then subscribes the live query — so it is never
|
|
202
226
|
* registered against an un-hydrated lazy relation (ADR-0021).
|
|
227
|
+
*
|
|
228
|
+
* `loading`/`hydrating`/`rows` are derived from which subscription the latest snapshot belongs to, so a
|
|
229
|
+
* `ready: false → true` interlude with unchanged inputs keeps the previous rows while it re-subscribes
|
|
230
|
+
* (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
|
|
231
|
+
* loading" policy already applied across a query change.
|
|
203
232
|
*/
|
|
204
233
|
function useGuardedDrizzleLive<TRows extends readonly unknown[]>(
|
|
205
234
|
buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,
|
|
@@ -228,20 +257,37 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
228
257
|
|
|
229
258
|
const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;
|
|
230
259
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
260
|
+
// The run token: ONE object whose identity changes exactly when the subscription must be rebuilt, and
|
|
261
|
+
// `null` when the hook cannot subscribe. It is the effect's only dependency AND the tag on every
|
|
262
|
+
// snapshot the effect writes, so `loading`/`hydrating` are derived during render instead of being
|
|
263
|
+
// written synchronously from the effect. `keepAliveMs` rides along inside the token precisely because
|
|
264
|
+
// it is NOT a dep: it is read at subscribe time and never resubscribes (ADR-0040 decision 4, above).
|
|
265
|
+
const run = useMemo(
|
|
266
|
+
() =>
|
|
267
|
+
ready && contextClient != null && queryInfo != null
|
|
268
|
+
? { client: contextClient, queryInfo, useList, keepAliveMs }
|
|
269
|
+
: null,
|
|
270
|
+
// sqlKey/useKey are stable JSON snapshots; queryInfo/useList/keepAliveMs are captured in the token.
|
|
271
|
+
// oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo
|
|
272
|
+
[contextClient, sqlKey, useKey, ready],
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
const [snapshot, setSnapshot] = useState<{
|
|
276
|
+
run: typeof run;
|
|
277
|
+
rows: TRows;
|
|
278
|
+
hydrated: boolean;
|
|
279
|
+
error: Error | null;
|
|
280
|
+
}>({
|
|
281
|
+
run: null,
|
|
282
|
+
rows: EMPTY_ROWS as unknown as TRows,
|
|
283
|
+
hydrated: false,
|
|
235
284
|
error: null,
|
|
236
285
|
});
|
|
237
286
|
|
|
238
287
|
useEffect(() => {
|
|
239
|
-
if (
|
|
240
|
-
setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
288
|
+
if (run == null) return;
|
|
243
289
|
|
|
244
|
-
const { sql, selectedFields } = queryInfo;
|
|
290
|
+
const { sql, selectedFields } = run.queryInfo;
|
|
245
291
|
// Render the query safe to MATERIALISE: hand the seam the select's unique field aliases so it wraps a
|
|
246
292
|
// JOIN with same-named columns (two `title`) under a positional column-alias-list — otherwise PGlite's
|
|
247
293
|
// live query refuses it (`column "title" specified more than once`) and same-named columns collapse.
|
|
@@ -258,8 +304,6 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
258
304
|
let active = true;
|
|
259
305
|
let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;
|
|
260
306
|
|
|
261
|
-
setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));
|
|
262
|
-
|
|
263
307
|
// Scan the compiled SQL for the lazy relations the query reads (∪ `use`), ACTIVATE them (streams
|
|
264
308
|
// started, tripwire satisfied), THEN subscribe via the client's live-rows seam — so a query is never
|
|
265
309
|
// registered against a dormant lazy relation (ADR-0021), and the same hook drives both the in-process
|
|
@@ -272,23 +316,30 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
272
316
|
// promise and `hydrating` clears at the first snapshot. The seam guarantees rows-before-signal (it
|
|
273
317
|
// refreshes the live query against the caught-up store before resolving), so clearing `hydrating`
|
|
274
318
|
// here can never present zero rows as "empty" while the catch-up rows are still in flight.
|
|
275
|
-
void
|
|
276
|
-
.prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })
|
|
319
|
+
void run.client
|
|
320
|
+
.prepareQuery({ sql: sql.sql, ...(run.useList ? { use: run.useList } : {}) })
|
|
277
321
|
.then(() => {
|
|
278
322
|
if (!active) return undefined;
|
|
279
|
-
return
|
|
323
|
+
return run.client
|
|
280
324
|
.subscribeLiveRows<Record<string, unknown>>(
|
|
281
325
|
{
|
|
282
326
|
sql: sql.sql,
|
|
283
327
|
params: sql.params,
|
|
284
328
|
...(fields ? { fields } : {}),
|
|
285
|
-
...(useList ? { use: useList } : {}),
|
|
286
|
-
...(keepAliveMs != null ? { keepAliveMs } : {}),
|
|
329
|
+
...(run.useList ? { use: run.useList } : {}),
|
|
330
|
+
...(run.keepAliveMs != null ? { keepAliveMs: run.keepAliveMs } : {}),
|
|
287
331
|
},
|
|
288
332
|
(rows) => {
|
|
289
333
|
if (active) {
|
|
290
334
|
syncDebug("live query updated → re-render", { rows: rows.length });
|
|
291
|
-
|
|
335
|
+
// A diff can land before the initial snapshot, so carry `hydrated` over only when the
|
|
336
|
+
// previous snapshot belongs to THIS run — otherwise it is the previous run's flag.
|
|
337
|
+
setSnapshot((prev) => ({
|
|
338
|
+
run,
|
|
339
|
+
rows: mapRows(rows),
|
|
340
|
+
hydrated: prev.run === run ? prev.hydrated : false,
|
|
341
|
+
error: null,
|
|
342
|
+
}));
|
|
292
343
|
}
|
|
293
344
|
},
|
|
294
345
|
)
|
|
@@ -304,15 +355,17 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
304
355
|
rows: registered.initialRows.length,
|
|
305
356
|
hydrating: registered.hydrated != null,
|
|
306
357
|
});
|
|
307
|
-
|
|
358
|
+
// No `hydrated` promise ⇒ every referenced group was already caught up at subscribe time, so
|
|
359
|
+
// this first snapshot IS the hydrated one (the steady-state fast path).
|
|
360
|
+
setSnapshot({
|
|
361
|
+
run,
|
|
308
362
|
rows: mapRows(registered.initialRows),
|
|
309
|
-
|
|
310
|
-
hydrating: registered.hydrated != null ? prev.hydrating : false,
|
|
363
|
+
hydrated: registered.hydrated == null,
|
|
311
364
|
error: null,
|
|
312
|
-
})
|
|
365
|
+
});
|
|
313
366
|
if (registered.hydrated) {
|
|
314
367
|
void registered.hydrated.then(() => {
|
|
315
|
-
if (active)
|
|
368
|
+
if (active) setSnapshot((prev) => (prev.run === run ? { ...prev, hydrated: true } : prev));
|
|
316
369
|
});
|
|
317
370
|
}
|
|
318
371
|
return undefined;
|
|
@@ -320,10 +373,10 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
320
373
|
})
|
|
321
374
|
.catch((error: unknown) => {
|
|
322
375
|
if (active) {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
376
|
+
setSnapshot({
|
|
377
|
+
run,
|
|
378
|
+
rows: EMPTY_ROWS as unknown as TRows,
|
|
379
|
+
hydrated: true,
|
|
327
380
|
error: error instanceof Error ? error : new Error(String(error)),
|
|
328
381
|
});
|
|
329
382
|
}
|
|
@@ -333,11 +386,19 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
333
386
|
active = false;
|
|
334
387
|
subscription?.unsubscribe();
|
|
335
388
|
};
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
389
|
+
}, [run]);
|
|
390
|
+
|
|
391
|
+
// Derived, never stored: a snapshot is authoritative only for the run it was tagged with, and it is
|
|
392
|
+
// "hydrated" only once the subscription's `hydrated` promise resolved (or there was none to await).
|
|
393
|
+
// A failed run settles hydrated so an error is not reported as a permanent catch-up, and with no run
|
|
394
|
+
// there is nothing catching up, so `hydrating` is false (`loading` alone reports the missing client).
|
|
395
|
+
const settled = run != null && snapshot.run === run;
|
|
396
|
+
const rows = run == null ? (EMPTY_ROWS as unknown as TRows) : snapshot.rows;
|
|
397
|
+
const loading = ready && !settled;
|
|
398
|
+
const hydrating = run != null && !(settled && snapshot.hydrated);
|
|
399
|
+
const error = settled ? snapshot.error : null;
|
|
400
|
+
|
|
401
|
+
return useMemo(() => ({ rows, loading, hydrating, error }), [rows, loading, hydrating, error]);
|
|
341
402
|
}
|
|
342
403
|
|
|
343
404
|
/**
|
|
@@ -419,6 +480,10 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
419
480
|
* EVERY writable journal, folded to one {@link MutationSummary}. ONE subscription drives a global sync
|
|
420
481
|
* indicator — no `hydrating` flag, because journals are local and never network-hydrated. Cheap enough to
|
|
421
482
|
* mount permanently (ADR-0040 dedup: one registration regardless of subscriber count).
|
|
483
|
+
*
|
|
484
|
+
* `loading` and `summary` are derived from which subscription the latest snapshot belongs to, so a
|
|
485
|
+
* `ready: false → true` interlude keeps the previous summary while it re-subscribes (`loading: true`)
|
|
486
|
+
* instead of briefly reporting the zero summary.
|
|
422
487
|
*/
|
|
423
488
|
function useMutationSummary(options?: { ready?: boolean }): {
|
|
424
489
|
summary: MutationSummary;
|
|
@@ -428,25 +493,25 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
428
493
|
const client = useContext(SyncClientContext);
|
|
429
494
|
const ready = options?.ready ?? true;
|
|
430
495
|
|
|
431
|
-
|
|
496
|
+
// The run token (see `useLiveRows`): the client is the only subscription input, wrapped so that a
|
|
497
|
+
// `ready` flip yields a fresh identity — otherwise the pre-flip snapshot would read as settled.
|
|
498
|
+
const run = useMemo(() => (ready && client != null ? { client } : null), [ready, client]);
|
|
499
|
+
|
|
500
|
+
const [snapshot, setSnapshot] = useState<{ run: typeof run; summary: MutationSummary; error: Error | null }>({
|
|
501
|
+
run: null,
|
|
432
502
|
summary: EMPTY_MUTATION_SUMMARY,
|
|
433
|
-
loading: ready,
|
|
434
503
|
error: null,
|
|
435
504
|
});
|
|
436
505
|
|
|
437
506
|
useEffect(() => {
|
|
438
|
-
if (
|
|
439
|
-
setState({ summary: EMPTY_MUTATION_SUMMARY, loading: ready, error: null });
|
|
440
|
-
return;
|
|
441
|
-
}
|
|
507
|
+
if (run == null) return;
|
|
442
508
|
|
|
443
509
|
let active = true;
|
|
444
510
|
let subscription: MutationSummarySubscription | undefined;
|
|
445
|
-
setState((prev) => ({ summary: prev.summary, loading: true, error: null }));
|
|
446
511
|
|
|
447
|
-
void client.mutations
|
|
512
|
+
void run.client.mutations
|
|
448
513
|
.subscribeSummary((summary) => {
|
|
449
|
-
if (active)
|
|
514
|
+
if (active) setSnapshot({ run, summary, error: null });
|
|
450
515
|
})
|
|
451
516
|
.then((registered) => {
|
|
452
517
|
if (!active) {
|
|
@@ -454,13 +519,13 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
454
519
|
return;
|
|
455
520
|
}
|
|
456
521
|
subscription = registered;
|
|
457
|
-
|
|
522
|
+
setSnapshot({ run, summary: registered.initial, error: null });
|
|
458
523
|
})
|
|
459
524
|
.catch((error: unknown) => {
|
|
460
525
|
if (active) {
|
|
461
|
-
|
|
526
|
+
setSnapshot({
|
|
527
|
+
run,
|
|
462
528
|
summary: EMPTY_MUTATION_SUMMARY,
|
|
463
|
-
loading: false,
|
|
464
529
|
error: error instanceof Error ? error : new Error(String(error)),
|
|
465
530
|
});
|
|
466
531
|
}
|
|
@@ -470,9 +535,15 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
470
535
|
active = false;
|
|
471
536
|
subscription?.unsubscribe();
|
|
472
537
|
};
|
|
473
|
-
}, [
|
|
538
|
+
}, [run]);
|
|
474
539
|
|
|
475
|
-
|
|
540
|
+
// Derived, never stored — see `useLiveRows`.
|
|
541
|
+
const settled = run != null && snapshot.run === run;
|
|
542
|
+
const summary = run == null ? EMPTY_MUTATION_SUMMARY : snapshot.summary;
|
|
543
|
+
const loading = ready && !settled;
|
|
544
|
+
const error = settled ? snapshot.error : null;
|
|
545
|
+
|
|
546
|
+
return useMemo(() => ({ summary, loading, error }), [summary, loading, error]);
|
|
476
547
|
}
|
|
477
548
|
|
|
478
549
|
/**
|
|
@@ -480,6 +551,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
480
551
|
* every writable table, filtered by `table` / `entityKey` / `statuses` / `limit`, ordered newest-first.
|
|
481
552
|
* Route/feature-scoped — mount it where a diagnostics view is open, not app-wide (prefer
|
|
482
553
|
* {@link useMutationSummary} for a global indicator). No `hydrating` flag (journals are local).
|
|
554
|
+
*
|
|
555
|
+
* `loading` and `rows` are derived from which subscription the latest snapshot belongs to, so a
|
|
556
|
+
* `ready: false → true` interlude with unchanged filters keeps the previous rows while it re-subscribes
|
|
557
|
+
* (`loading: true`) instead of briefly reporting zero rows — the same "keep the previous rows while
|
|
558
|
+
* loading" policy already applied across a filter change.
|
|
483
559
|
*/
|
|
484
560
|
function useMutationList(options?: MutationListOptions<TRegistry> & { ready?: boolean }): {
|
|
485
561
|
rows: MutationSummaryDetail[];
|
|
@@ -497,25 +573,29 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
497
573
|
[filtersKey],
|
|
498
574
|
);
|
|
499
575
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
576
|
+
// The run token (see `useLiveRows`): the client and the JSON-stable filters are the only subscription
|
|
577
|
+
// inputs, so its identity changes exactly when the subscription must be rebuilt — which lets `loading`
|
|
578
|
+
// be derived during render instead of written synchronously from the effect.
|
|
579
|
+
const run = useMemo(
|
|
580
|
+
() => (ready && client != null ? { client, filters: stableFilters } : null),
|
|
581
|
+
[ready, client, stableFilters],
|
|
582
|
+
);
|
|
583
|
+
|
|
584
|
+
const [snapshot, setSnapshot] = useState<{ run: typeof run; rows: MutationSummaryDetail[]; error: Error | null }>({
|
|
585
|
+
run: null,
|
|
586
|
+
rows: EMPTY_ROWS,
|
|
503
587
|
error: null,
|
|
504
588
|
});
|
|
505
589
|
|
|
506
590
|
useEffect(() => {
|
|
507
|
-
if (
|
|
508
|
-
setState({ rows: [], loading: ready, error: null });
|
|
509
|
-
return;
|
|
510
|
-
}
|
|
591
|
+
if (run == null) return;
|
|
511
592
|
|
|
512
593
|
let active = true;
|
|
513
594
|
let subscription: { unsubscribe: () => void } | undefined;
|
|
514
|
-
setState((prev) => ({ rows: prev.rows, loading: true, error: null }));
|
|
515
595
|
|
|
516
|
-
void client.mutations
|
|
517
|
-
.subscribe(
|
|
518
|
-
if (active)
|
|
596
|
+
void run.client.mutations
|
|
597
|
+
.subscribe(run.filters, (rows) => {
|
|
598
|
+
if (active) setSnapshot({ run, rows, error: null });
|
|
519
599
|
})
|
|
520
600
|
.then((registered) => {
|
|
521
601
|
if (!active) {
|
|
@@ -523,11 +603,11 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
523
603
|
return;
|
|
524
604
|
}
|
|
525
605
|
subscription = registered;
|
|
526
|
-
|
|
606
|
+
setSnapshot({ run, rows: registered.initial, error: null });
|
|
527
607
|
})
|
|
528
608
|
.catch((error: unknown) => {
|
|
529
609
|
if (active) {
|
|
530
|
-
|
|
610
|
+
setSnapshot({ run, rows: EMPTY_ROWS, error: error instanceof Error ? error : new Error(String(error)) });
|
|
531
611
|
}
|
|
532
612
|
});
|
|
533
613
|
|
|
@@ -535,11 +615,15 @@ export function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {
|
|
|
535
615
|
active = false;
|
|
536
616
|
subscription?.unsubscribe();
|
|
537
617
|
};
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
618
|
+
}, [run]);
|
|
619
|
+
|
|
620
|
+
// Derived, never stored — see `useLiveRows`.
|
|
621
|
+
const settled = run != null && snapshot.run === run;
|
|
622
|
+
const rows = run == null ? EMPTY_ROWS : snapshot.rows;
|
|
623
|
+
const loading = ready && !settled;
|
|
624
|
+
const error = settled ? snapshot.error : null;
|
|
541
625
|
|
|
542
|
-
return
|
|
626
|
+
return useMemo(() => ({ rows, loading, error }), [rows, loading, error]);
|
|
543
627
|
}
|
|
544
628
|
|
|
545
629
|
return {
|