@marktiderman/genesis-core 1.14.1 → 1.16.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/README.md +20 -8
- package/dist/{chunk-YFTGLQDQ.js → chunk-CQ3RR2ST.js} +5 -5
- package/dist/{chunk-YFTGLQDQ.js.map → chunk-CQ3RR2ST.js.map} +1 -1
- package/dist/{chunk-RF6YVWHX.js → chunk-CZOFWG54.js} +4 -4
- package/dist/{chunk-RF6YVWHX.js.map → chunk-CZOFWG54.js.map} +1 -1
- package/dist/{chunk-4VRVVN2S.js → chunk-E4777JKI.js} +3 -3
- package/dist/{chunk-4VRVVN2S.js.map → chunk-E4777JKI.js.map} +1 -1
- package/dist/{chunk-K7K6NY3C.js → chunk-IOTHEKO7.js} +69 -59
- package/dist/chunk-IOTHEKO7.js.map +1 -0
- package/dist/{chunk-UV3ROHQA.js → chunk-K4ZNAF3G.js} +3 -3
- package/dist/{chunk-UV3ROHQA.js.map → chunk-K4ZNAF3G.js.map} +1 -1
- package/dist/{chunk-3LZAZ5KB.js → chunk-K7WEY5WR.js} +3 -3
- package/dist/{chunk-3LZAZ5KB.js.map → chunk-K7WEY5WR.js.map} +1 -1
- package/dist/{chunk-BQOJX67X.js → chunk-LGTXQTHA.js} +3 -3
- package/dist/{chunk-BQOJX67X.js.map → chunk-LGTXQTHA.js.map} +1 -1
- package/dist/{chunk-GGSXSI6Z.js → chunk-VDEW4AOS.js} +9 -6
- package/dist/chunk-VDEW4AOS.js.map +1 -0
- package/dist/{chunk-7YHGNPPO.js → chunk-VMRLCTZR.js} +5 -5
- package/dist/{chunk-7YHGNPPO.js.map → chunk-VMRLCTZR.js.map} +1 -1
- package/dist/{chunk-UGGMJUFQ.js → chunk-Y452U45I.js} +15 -7
- package/dist/chunk-Y452U45I.js.map +1 -0
- package/dist/hooks/index.js +9 -9
- package/dist/hooks/mutation-mode.js +3 -3
- package/dist/hooks/use-capabilities.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +8 -0
- package/dist/hooks/use-infinite-resource.js +3 -3
- package/dist/hooks/use-live.js +2 -2
- package/dist/hooks/use-one.js +3 -3
- package/dist/hooks/use-resource-form.js +6 -6
- package/dist/hooks/use-resource.js +5 -5
- package/dist/index.js +10 -10
- package/dist/provider/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-GGSXSI6Z.js.map +0 -1
- package/dist/chunk-K7K6NY3C.js.map +0 -1
- package/dist/chunk-UGGMJUFQ.js.map +0 -1
|
@@ -46,6 +46,10 @@ function decodeCursor(cursor) {
|
|
|
46
46
|
if (!state || typeof state !== "object" || typeof state.k !== "string" || !isIdentifier(state.id)) return void 0;
|
|
47
47
|
if (state.o !== "asc" && state.o !== "desc") return void 0;
|
|
48
48
|
if (state.d !== void 0 && state.d !== "b") return void 0;
|
|
49
|
+
if (state.c !== void 0) {
|
|
50
|
+
if (!Array.isArray(state.c) || !Array.isArray(state.vs) || state.c.length !== state.vs.length) return void 0;
|
|
51
|
+
if (!state.c.every((col) => col && typeof col.s === "string" && (col.o === "asc" || col.o === "desc"))) return void 0;
|
|
52
|
+
}
|
|
49
53
|
return state;
|
|
50
54
|
} catch {
|
|
51
55
|
return void 0;
|
|
@@ -54,36 +58,44 @@ function decodeCursor(cursor) {
|
|
|
54
58
|
function quoteFilterValue(value) {
|
|
55
59
|
return `"${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
56
60
|
}
|
|
57
|
-
function
|
|
58
|
-
if (state.
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
61
|
+
function cursorColumns(state) {
|
|
62
|
+
if (state.c) return { cols: state.c.map((col, i) => ({ ...col, v: state.vs[i] ?? null })), keyOrder: "asc" };
|
|
63
|
+
if (state.s === null) return { cols: [], keyOrder: state.o };
|
|
64
|
+
return { cols: [{ s: state.s, o: state.o, v: state.v ?? null }], keyOrder: "asc" };
|
|
65
|
+
}
|
|
66
|
+
function sortColumns(params, key) {
|
|
67
|
+
const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];
|
|
68
|
+
const columns = [];
|
|
69
|
+
for (const sort of requested) {
|
|
70
|
+
if (sort.field === key) return { columns, keyOrder: sort.order ?? "asc" };
|
|
71
|
+
if (!columns.some((c) => c.field === sort.field)) columns.push({ field: sort.field, order: sort.order ?? "asc" });
|
|
68
72
|
}
|
|
69
|
-
|
|
70
|
-
const ties = afterInTies(`${s}.eq.${V}`);
|
|
71
|
-
return state.o === "asc" ? `${s}.gt.${V},${ties},${s}.is.null` : `${s}.lt.${V},${ties}`;
|
|
73
|
+
return { columns, keyOrder: "asc" };
|
|
72
74
|
}
|
|
73
|
-
function
|
|
75
|
+
function keysetClauses(state) {
|
|
76
|
+
const back = state.d === "b";
|
|
74
77
|
const k = state.k;
|
|
75
78
|
const K = quoteFilterValue(state.id);
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
79
|
+
const { cols, keyOrder } = cursorColumns(state);
|
|
80
|
+
const keyAhead = `${k}.${keyOrder === "asc" !== back ? "gt" : "lt"}.${K}`;
|
|
81
|
+
if (cols.length === 0) return keyAhead;
|
|
82
|
+
const main = [];
|
|
83
|
+
const tail = [];
|
|
84
|
+
const equal = [];
|
|
85
|
+
const within = (piece) => equal.length ? `and(${equal.join(",")},${piece})` : piece;
|
|
86
|
+
for (const { s, o, v } of cols) {
|
|
87
|
+
const nullsAhead = o === "asc" !== back;
|
|
88
|
+
if (v === null) {
|
|
89
|
+
if (!nullsAhead) main.push(within(`${s}.not.is.null`));
|
|
90
|
+
equal.push(`${s}.is.null`);
|
|
91
|
+
} else {
|
|
92
|
+
const V = quoteFilterValue(v);
|
|
93
|
+
main.push(within(`${s}.${o === "asc" !== back ? "gt" : "lt"}.${V}`));
|
|
94
|
+
if (nullsAhead) tail.push(within(`${s}.is.null`));
|
|
95
|
+
equal.push(`${s}.eq.${V}`);
|
|
96
|
+
}
|
|
83
97
|
}
|
|
84
|
-
|
|
85
|
-
const ties = beforeInTies(`${s}.eq.${V}`);
|
|
86
|
-
return state.o === "asc" ? `${s}.lt.${V},${ties}` : `${s}.gt.${V},${ties},${s}.is.null`;
|
|
98
|
+
return [...main, `and(${equal.join(",")},${keyAhead})`, ...tail].join(",");
|
|
87
99
|
}
|
|
88
100
|
function realtimeTable(resource) {
|
|
89
101
|
const dot = resource.indexOf(".");
|
|
@@ -327,17 +339,18 @@ function createSupabaseProvider(client, options = {}) {
|
|
|
327
339
|
return refuseCursor(resource, "cursor paging needs a unique key column to order by; its orderKey is false. Set orderKey to a unique, non-null column, or page by offset.");
|
|
328
340
|
}
|
|
329
341
|
if (!PLAIN_COLUMN.test(key)) return refuseCursor(resource, `the key column "${key}" can't be used in a cursor.`);
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
const
|
|
335
|
-
const
|
|
342
|
+
const { columns, keyOrder } = sortColumns(params, key);
|
|
343
|
+
const unplain = columns.find((c) => !PLAIN_COLUMN.test(c.field));
|
|
344
|
+
if (unplain) return refuseCursor(resource, `cursor paging can sort only by a plain column, not "${unplain.field}".`);
|
|
345
|
+
const sortFields = columns.map((c) => c.field);
|
|
346
|
+
const shape = (values) => columns.length === 0 ? { s: null, o: keyOrder } : columns.length === 1 ? { s: columns[0].field, o: columns[0].order, v: values[0] ?? null } : { s: null, o: "asc", c: columns.map((c) => ({ s: c.field, o: c.order })), vs: values };
|
|
347
|
+
const sortId = JSON.stringify([columns.map((c) => [c.field, c.order]), keyOrder]);
|
|
336
348
|
let after;
|
|
337
349
|
if (cursor) {
|
|
338
350
|
after = decodeCursor(cursor);
|
|
339
351
|
if (!after) return refuseCursor(resource, "the cursor is not one this provider made.");
|
|
340
|
-
|
|
352
|
+
const made = cursorColumns(after);
|
|
353
|
+
if (JSON.stringify([made.cols.map((c) => [c.s, c.o]), made.keyOrder]) !== sortId || after.k !== key) {
|
|
341
354
|
return refuseCursor(resource, "the cursor was made for a different sort; start again from the first page (cursor: null).");
|
|
342
355
|
}
|
|
343
356
|
}
|
|
@@ -349,13 +362,11 @@ function createSupabaseProvider(client, options = {}) {
|
|
|
349
362
|
if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);
|
|
350
363
|
else if (search || keyset) query = query.or(search || keyset);
|
|
351
364
|
const back = after?.d === "b";
|
|
352
|
-
|
|
365
|
+
for (const { field, order } of columns) {
|
|
353
366
|
const ascending = order === "asc" !== back;
|
|
354
|
-
query = query.order(
|
|
355
|
-
query = query.order(key, { ascending: !back });
|
|
356
|
-
} else {
|
|
357
|
-
query = query.order(key, { ascending: order === "asc" !== back });
|
|
367
|
+
query = query.order(field, { ascending, nullsFirst: !ascending });
|
|
358
368
|
}
|
|
369
|
+
query = query.order(key, { ascending: keyOrder === "asc" !== back });
|
|
359
370
|
query = query.range(0, perPage);
|
|
360
371
|
const result = await query;
|
|
361
372
|
await throwIfReadError(result, resource, "getList");
|
|
@@ -366,26 +377,23 @@ function createSupabaseProvider(client, options = {}) {
|
|
|
366
377
|
const cursorAt = (row, direction) => {
|
|
367
378
|
if (!row) return null;
|
|
368
379
|
const id = row[key];
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
if (v
|
|
372
|
-
return encodeCursor({
|
|
373
|
-
s: sortField,
|
|
374
|
-
o: order,
|
|
375
|
-
k: key,
|
|
376
|
-
...sortField ? { v: v ?? null } : {},
|
|
377
|
-
id,
|
|
378
|
-
...direction ? { d: direction } : {}
|
|
379
|
-
});
|
|
380
|
+
if (!isIdentifier(id) || sortFields.some((f) => !(f in row))) return false;
|
|
381
|
+
const values = sortFields.map((f) => row[f] ?? null);
|
|
382
|
+
if (values.some((v) => v !== null && typeof v === "object")) return false;
|
|
383
|
+
return encodeCursor({ ...shape(values), k: key, id, ...direction ? { d: direction } : {} });
|
|
380
384
|
};
|
|
381
385
|
const next = back ? cursorAt(page[page.length - 1]) : more ? cursorAt(page[page.length - 1]) : null;
|
|
382
386
|
const prev = back ? more ? cursorAt(page[0], "b") : null : cursor ? cursorAt(page[0], "b") : null;
|
|
383
387
|
if (next === false || prev === false) {
|
|
384
|
-
const objectValued =
|
|
388
|
+
const objectValued = sortFields.find(
|
|
389
|
+
(f) => page.some((row) => f in row && row[f] !== null && typeof row[f] === "object")
|
|
390
|
+
);
|
|
385
391
|
if (objectValued) {
|
|
386
|
-
return refuseCursor(resource, `cursor paging can't sort by "${
|
|
392
|
+
return refuseCursor(resource, `cursor paging can't sort by "${objectValued}": its values aren't plain (text, number, date, boolean).`);
|
|
387
393
|
}
|
|
388
|
-
|
|
394
|
+
const needed = [key, ...sortFields].map((f) => `"${f}"`);
|
|
395
|
+
const list = needed.length === 1 ? needed[0] : `${needed.slice(0, -1).join(", ")} and ${needed[needed.length - 1]}`;
|
|
396
|
+
return refuseCursor(resource, `the selected columns must include ${list} to page by cursor.`);
|
|
389
397
|
}
|
|
390
398
|
return {
|
|
391
399
|
data: page,
|
|
@@ -425,11 +433,13 @@ function createSupabaseProvider(client, options = {}) {
|
|
|
425
433
|
if (clauses) {
|
|
426
434
|
query = query.or(clauses);
|
|
427
435
|
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
});
|
|
432
|
-
|
|
436
|
+
const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];
|
|
437
|
+
if (requested.length > 0 && key) {
|
|
438
|
+
const { columns, keyOrder } = sortColumns(params, key);
|
|
439
|
+
for (const { field, order } of columns) query = query.order(field, { ascending: order === "asc" });
|
|
440
|
+
query = query.order(key, { ascending: keyOrder === "asc" });
|
|
441
|
+
} else if (requested.length > 0) {
|
|
442
|
+
for (const { field, order } of requested) query = query.order(field, { ascending: order === "asc" });
|
|
433
443
|
} else if (params.pagination && key) {
|
|
434
444
|
query = query.order(key, { ascending: true });
|
|
435
445
|
}
|
|
@@ -478,7 +488,7 @@ function createSupabaseProvider(client, options = {}) {
|
|
|
478
488
|
bulkWrites: false,
|
|
479
489
|
versionedWrites: false,
|
|
480
490
|
compositeKeys: false,
|
|
481
|
-
multiSort:
|
|
491
|
+
multiSort: true,
|
|
482
492
|
create: true,
|
|
483
493
|
delete: true,
|
|
484
494
|
maxPerPage,
|
|
@@ -751,5 +761,5 @@ async function createOrAdopt(provider, resource, data, options) {
|
|
|
751
761
|
}
|
|
752
762
|
|
|
753
763
|
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider };
|
|
754
|
-
//# sourceMappingURL=chunk-
|
|
755
|
-
//# sourceMappingURL=chunk-
|
|
764
|
+
//# sourceMappingURL=chunk-IOTHEKO7.js.map
|
|
765
|
+
//# sourceMappingURL=chunk-IOTHEKO7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider/supabase-provider.ts","../src/provider/write-helpers.ts"],"names":["run","from"],"mappings":";;;;;AA+RA,SAAS,eAAA,CAAgB,KAAA,EAAgB,KAAA,EAAe,MAAA,EAAyB;AAC/E,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AAChD,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAQ,GAAI,KAAA;AAC1B,EAAA,IAAI,IAAA,KAAS,OAAA,IAAW,OAAO,OAAA,KAAY,UAAU,OAAO,KAAA;AAC5D,EAAA,MAAM,KAAA,GAAQ,6DAAA,CAA8D,IAAA,CAAK,OAAA,CAAQ,MAAM,CAAA;AAC/F,EAAA,IAAI,CAAC,KAAA,IAAS,KAAA,CAAM,CAAC,CAAA,KAAM,QAAQ,OAAO,KAAA;AAC1C,EAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAG,EAAE,GAAA,EAAI,EAAG,OAAA,CAAQ,IAAA,EAAM,EAAE,CAAA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AU,OAAA,EAAS,IAAA,EAAM,KAAA,EAAO,IAAA,EAAK;AAClF,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,KAAA,GAAQ,QAAQ,CAAA;AACxC,IAAA,IAAI,CAAC,OAAA,IAAW,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,MAAA,KAAW,CAAA,EAAG,OAAO,EAAE,GAAA,EAAK,QAAA,EAAU,OAAA,EAAS,IAAA,EAAM,OAAO,KAAA,EAAM;AACvG,IAAA,OAAO;AAAA,MACL,GAAA,EAAA,CAAM,MAAM,QAAA,CAAS,MAAA,CAAU,QAAA,EAAU,EAAE,EAAA,EAAI,QAAA,CAAS,EAAA,EAAI,IAAA,EAAM,OAAA,EAAS,CAAA,EAAG,IAAA;AAAA,MAC9E,OAAA,EAAS,IAAA;AAAA,MACT,KAAA,EAAO;AAAA,KACT;AAAA,EACF;AACF","file":"chunk-IOTHEKO7.js","sourcesContent":["import type {\n BaseRecord,\n CountMode,\n DataProvider,\n FilterParam,\n Identifier,\n InvalidationKey,\n ListParams,\n ResourceChangeEvent,\n SortParam,\n WriteEvent,\n} from \"./types\";\nimport { DataWriteError } from \"../schema/write-outcome\";\nimport { DataReadError, readFailureMessage } from \"../schema/read-outcome\";\nimport type { FilterOperator, ProviderCapabilities } from \"../schema/types\";\nimport { readOutcomeFromCode, toDataWriteError } from \"./postgrest-errors\";\n\n// ---------------------------------------------------------------------------\n// Minimal Supabase client shape — no hard dependency on @supabase/supabase-js\n// ---------------------------------------------------------------------------\n\n/** A chainable query builder returned by `client.from(table)`. */\ninterface SupabaseQueryBuilder {\n select(\n columns?: string,\n options?: { count?: \"exact\" | \"planned\" | \"estimated\" },\n ): SupabaseQueryBuilder;\n insert(data: Record<string, unknown> | Record<string, unknown>[]): SupabaseQueryBuilder;\n update(data: Record<string, unknown>): SupabaseQueryBuilder;\n delete(): SupabaseQueryBuilder;\n eq(column: string, value: unknown): SupabaseQueryBuilder;\n neq(column: string, value: unknown): SupabaseQueryBuilder;\n gt(column: string, value: unknown): SupabaseQueryBuilder;\n lt(column: string, value: unknown): SupabaseQueryBuilder;\n gte(column: string, value: unknown): SupabaseQueryBuilder;\n lte(column: string, value: unknown): SupabaseQueryBuilder;\n ilike(column: string, value: string): SupabaseQueryBuilder;\n in(column: string, values: unknown[]): SupabaseQueryBuilder;\n is(column: string, value: null): SupabaseQueryBuilder;\n not(column: string, operator: string, value: unknown): SupabaseQueryBuilder;\n or(filters: string): SupabaseQueryBuilder;\n order(column: string, options?: { ascending?: boolean; nullsFirst?: boolean }): SupabaseQueryBuilder;\n range(from: number, to: number): SupabaseQueryBuilder;\n single(): SupabaseQueryBuilder;\n then: Promise<{ data: unknown; error: unknown; count?: number | null }>[\"then\"];\n}\n\n/**\n * Minimal Supabase client interface — the public shape this package has\n * always exposed for a caller that wants to type its own client or a\n * wrapper around one. Unchanged: `from()` still returns `SupabaseQueryBuilder`\n * so existing consumers that annotate a variable with this type and chain\n * off it keep type-checking exactly as before.\n */\nexport interface SupabaseClient {\n from(table: string): SupabaseQueryBuilder;\n /** Supabase Realtime; needed only for `subscribe` (see `SupabaseProviderOptions.realtime`). */\n channel?(name: string): SupabaseRealtimeChannel;\n /** Releases a channel made by `channel()`. */\n removeChannel?(channel: SupabaseRealtimeChannel): unknown;\n}\n\n/**\n * One `postgres_changes` message, as Supabase Realtime sends it. Only the\n * fields the provider reads; a real payload has more.\n */\nexport interface SupabaseRealtimePayload {\n eventType: \"INSERT\" | \"UPDATE\" | \"DELETE\";\n /** The row after an insert or update (empty for a delete). */\n new?: Record<string, unknown>;\n /** For a delete or update: the old row's key (all of it with `REPLICA IDENTITY FULL`). */\n old?: Record<string, unknown>;\n}\n\n/**\n * The part of a Supabase `RealtimeChannel` the provider uses. A real\n * `@supabase/supabase-js` channel satisfies it.\n */\nexport interface SupabaseRealtimeChannel {\n on(\n type: \"postgres_changes\",\n filter: {\n event: \"*\" | \"INSERT\" | \"UPDATE\" | \"DELETE\";\n schema: string;\n table: string;\n filter?: string;\n },\n callback: (payload: SupabaseRealtimePayload) => void,\n ): SupabaseRealtimeChannel;\n subscribe(callback?: (status: string, error?: unknown) => void): SupabaseRealtimeChannel;\n unsubscribe?(): unknown;\n}\n\n/**\n * What `createSupabaseProvider` actually requires from its `client` argument\n * — deliberately looser than the public `SupabaseClient` above, and used\n * ONLY for that one parameter. A real `@supabase/supabase-js` client's\n * `from()` returns a generic, table-typed `PostgrestQueryBuilder` whose chain\n * methods don't structurally match `SupabaseQueryBuilder`, which used to\n * force callers to pass their client through `as never`. Since `unknown` is\n * a supertype of everything, any real client's `from(table: string)`\n * satisfies THIS shape without a cast; `createSupabaseProvider` narrows to\n * `SupabaseQueryBuilder` internally, once, right after each `from()` call.\n * Loosening only the input here — rather than `SupabaseClient` itself —\n * means a caller relying on `SupabaseClient`'s stricter return type for\n * their own chaining is unaffected.\n */\nexport interface SupabaseClientInput {\n from(table: string): unknown;\n /** Database functions, for a resource whose `source` is an `rpc`. Any real client's `rpc` fits. */\n rpc?(fn: string, args?: Record<string, unknown>, options?: { count?: \"exact\" | \"planned\" | \"estimated\" }): unknown;\n /** Supabase Realtime, for `subscribe`. Any real client's `channel` fits. */\n channel?(name: string): unknown;\n removeChannel?(channel: unknown): unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\n/** What a write hook is told about the write it is part of. */\nexport interface SupabaseWriteContext {\n resource: string;\n action: \"create\" | \"update\";\n /** The row's id, for an update. */\n id?: Identifier;\n}\n\n/** Per-resource rules for `createSupabaseProvider`. Every field is optional. */\nexport interface SupabaseResourceConfig {\n /** Singular noun for failure messages, e.g. \"project\". Defaults to \"record\". */\n noun?: string;\n /** Plural for list messages, when it isn't `noun` + \"s\" (\"categories\"). */\n nounPlural?: string;\n /**\n * The columns a search covers. `[]` means the resource can't be searched,\n * and `capabilities(resource).search` reports false so a UI hides the box.\n * Set, they replace the caller's `search.fields`; omitted, those are used\n * as given.\n */\n searchFields?: readonly string[];\n /**\n * The column a sorted list orders by last, so rows with equal sort values\n * keep one order from page to page (none repeats, none is skipped).\n * Default `\"id\"`; `false` for a table or view without one. With the\n * default, a view that turns out to have no `id` column is read as before\n * (without the key order) and a development warning suggests setting this.\n */\n orderKey?: string | false;\n /**\n * `\"bin\"` for a table whose delete trigger moves the row to a recycle bin\n * instead of removing it (see `SupabaseProviderOptions.binTables`).\n * `\"hard\"` forces a plain delete even when `binTables` lists the table.\n */\n deleteMode?: \"hard\" | \"bin\";\n /**\n * Turns submitted values into the row to write: trim, drop read-only keys,\n * validate. Runs before every create and update, including the `create`\n * and `update` overrides. Throw (ideally `DataWriteError(\"invalid\", ...)`)\n * to refuse the write; nothing is sent.\n */\n prepare?: (\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /**\n * Creates the row some other way than an insert, e.g. a security-definer\n * RPC. Return the new row, or its id and the provider reads the row back\n * (if the read-back fails, the create is still reported as saved, with\n * just the id, so the user does not retry and make a second one). Throw to\n * fail; a Supabase `{ message, code }` error is mapped like any other.\n */\n create?: (row: Record<string, unknown>) => Promise<BaseRecord | Identifier>;\n /**\n * Updates the row some other way than an update, e.g. an RPC. Return the\n * updated row, or its id (or `true`) and the provider reads it back.\n * Returning nothing (`undefined`/`null`/`false`) means no row changed: the provider then reads the\n * row to say why (`forbidden` or `gone`), exactly as for a plain update,\n * so a function that silently skips a row never reports a save.\n */\n update?: (\n id: Identifier,\n row: Record<string, unknown>,\n ) => Promise<BaseRecord | Identifier | boolean | null | undefined | void>;\n /** Maps a stored row to edit-form values; see `DataProvider.toFormValues`. */\n toFormValues?: (record: Record<string, unknown>) => Record<string, unknown>;\n /**\n * Other cache keys a committed write to this resource makes stale, e.g.\n * `[[\"staff\"], [\"me\"]]`. Served through `DataProvider.invalidates`, which\n * `useResource` and `useResourceForm` invalidate after their writes.\n */\n invalidates?: InvalidationKey[] | ((event: WriteEvent) => InvalidationKey[]);\n /**\n * Serve `subscribe` for this resource through Supabase Realtime\n * (`postgres_changes`), so `live` lists and records refresh when the table\n * changes. The table must be in the `supabase_realtime` publication, with\n * RLS on. `false` turns it off even when `SupabaseProviderOptions.realtime`\n * covers the resource.\n */\n realtime?: boolean;\n /**\n * Read this resource from somewhere else than its table: a view (joins,\n * counts, aggregations) or a database function that returns rows. Writes\n * still go to the table. Lists keep paging, filters, search, sort, totals\n * and cursors, because PostgREST filters a view or a set-returning function\n * like a table. Realtime still watches the table.\n *\n * Row-level security: a plain view runs as its owner and a SECURITY DEFINER\n * function as its definer, so either one reads past RLS. Create the view\n * `with (security_invoker = true)` and the function `security invoker` (or\n * have it filter by `auth.uid()` itself), or this exposes every row.\n *\n * ```ts\n * resources: {\n * tasks: { source: \"tasks_with_people\" },\n * course_progress: { source: { rpc: \"group_progress\", args: () => ({ group_id: currentGroup() }) } },\n * }\n * ```\n */\n source?: string | { rpc: string; args?: () => Record<string, unknown> };\n /**\n * How lists of this resource count their total (default `exact`). Use\n * `estimated` for large tables, or `none` when no screen shows a count.\n */\n count?: CountMode;\n /** The columns read when the caller names none, e.g. embedded joins: `\"*, person:people(full_name)\"`. Default `\"*\"`. */\n select?: string;\n /**\n * With a `source` (or a `select` that embeds other tables), the table's own\n * columns: creates and updates write only these, so a form built from the\n * richer read row never sends its joined or computed columns to the table.\n * Without it, an update writes only the columns the table's row has.\n */\n writeColumns?: readonly string[];\n}\n\n/** Options for `createSupabaseProvider`. All optional; none changes reads. */\nexport interface SupabaseProviderOptions {\n /**\n * Recycle-bin tables: their delete trigger turns a delete into a \"binned\"\n * mark and the binned row drops out of the caller's view (RLS or a view\n * filter). The database reports such a delete as zero rows, so for these\n * the provider checks the row is visible, deletes it, and reads it back:\n * gone from view is success, still visible is `forbidden`. A row that was\n * not visible beforehand is `gone`.\n */\n binTables?: readonly string[] | ((resource: string) => boolean);\n /** Per-resource rules, keyed by resource (table) name. */\n resources?: Record<string, SupabaseResourceConfig>;\n /**\n * Called after every committed create, update and delete, e.g. to\n * invalidate caches the Genesis hooks don't know about. Awaited, but a\n * failure is logged and never turns a committed write into a failed one.\n */\n onWrite?: (event: WriteEvent) => void | Promise<void>;\n /**\n * The most rows one list page may ask for (PostgREST's `max-rows` caps\n * reads anyway; default 1000). A larger request is refused with an\n * `invalid` `DataReadError` (its `cause` says why) rather than cut short,\n * so page boundaries never disagree with the caller's `perPage`.\n * `capabilities().maxPerPage` reports it.\n */\n maxPerPage?: number;\n /**\n * Called with every failed read, before it is thrown. The thrown\n * `DataReadError` carries a plain message for users; the store's own\n * error (its raw text and code) is its `cause`, for logging here.\n */\n onReadError?: (\n error: DataReadError,\n context: { resource: string; operation: \"getList\" | \"getOne\" | \"getMany\" },\n ) => void | Promise<void>;\n /**\n * Which resources `subscribe` serves through Supabase Realtime: `true` for\n * all, a list of names, or a test. Off by default; a resource's own\n * `resources[name].realtime` wins. Needs a client with `channel()` (any\n * `@supabase/supabase-js` client).\n */\n realtime?: boolean | readonly string[] | ((resource: string) => boolean);\n}\n\n/** A PostgREST \"undefined column\" error (42703) naming `column`. */\n/**\n * A PostgreSQL \"undefined column\" error (42703) for `table`'s own `column`:\n * `column \"id\" does not exist` or `column <table>.id does not exist`. Not a\n * related table's column (`author.id`) or any other message mentioning it.\n */\nfunction isMissingColumn(error: unknown, table: string, column: string): boolean {\n if (!error || typeof error !== \"object\") return false;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (code !== \"42703\" || typeof message !== \"string\") return false;\n const match = /^column (?:\"?([^.\"\\s]+)\"?\\.)?\"?([^.\"\\s]+)\"? does not exist$/.exec(message.trim());\n if (!match || match[2] !== column) return false;\n const ownTable = table.split(\".\").pop()?.replace(/\"/g, \"\");\n return match[1] === undefined || match[1] === ownTable;\n}\n\nconst SERVED_OPERATORS: readonly FilterOperator[] = [\n \"eq\", \"neq\", \"gt\", \"lt\", \"gte\", \"lte\", \"contains\", \"in\", \"between\", \"is_null\", \"is_not_null\",\n];\n\nfunction escapeIlike(value: string): string {\n return value.replace(/[%_\\\\]/g, (char) => `\\\\${char}`);\n}\n\nfunction isIdentifier(value: unknown): value is Identifier {\n return typeof value === \"string\" || typeof value === \"number\";\n}\n\n// ---------------------------------------------------------------------------\n// Cursor (keyset) paging\n// ---------------------------------------------------------------------------\n\ntype CursorValue = string | number | boolean | null;\n\n/** One sort column a cursor was made for. */\ninterface CursorColumn {\n s: string;\n o: \"asc\" | \"desc\";\n}\n\n/**\n * What a cursor holds: the sort it was made for, and the last row's values.\n * A cursor for one sort column is written as `s`/`o`/`v`; for several, as\n * `c` (the columns) and `vs` (their values, in order).\n */\ninterface CursorState {\n /** Sort field, or null when ordered by the key alone (or by several columns, in `c`). */\n s: string | null;\n /** The sort's order; the key's own order when `s` is null and there is no `c`. */\n o: \"asc\" | \"desc\";\n /** The key column. */\n k: string;\n /** The last row's sort value (absent when `s` is null). */\n v?: CursorValue;\n /** Several sort columns, first one first. */\n c?: CursorColumn[];\n /** The last row's values for `c`. */\n vs?: CursorValue[];\n /** The last row's key value (the first row's, for a cursor going back). */\n id: string | number;\n /** \"b\": the rows before this one (a previous page). Absent: the rows after it. */\n d?: \"b\";\n}\n\nconst PLAIN_COLUMN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\nfunction encodeCursor(state: CursorState): string {\n const bytes = new TextEncoder().encode(JSON.stringify(state));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction decodeCursor(cursor: string): CursorState | undefined {\n try {\n const binary = atob(cursor.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n const state = JSON.parse(new TextDecoder().decode(bytes)) as CursorState;\n if (!state || typeof state !== \"object\" || typeof state.k !== \"string\" || !isIdentifier(state.id)) return undefined;\n if (state.o !== \"asc\" && state.o !== \"desc\") return undefined;\n if (state.d !== undefined && state.d !== \"b\") return undefined;\n if (state.c !== undefined) {\n if (!Array.isArray(state.c) || !Array.isArray(state.vs) || state.c.length !== state.vs.length) return undefined;\n if (!state.c.every((col) => col && typeof col.s === \"string\" && (col.o === \"asc\" || col.o === \"desc\"))) return undefined;\n }\n return state;\n } catch {\n return undefined;\n }\n}\n\n/** A value quoted for a PostgREST filter, so commas, dots and parens are literal. */\nfunction quoteFilterValue(value: string | number | boolean): string {\n return `\"${String(value).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/** A cursor's sort columns with the row's values, and the key's order. */\nfunction cursorColumns(state: CursorState): { cols: (CursorColumn & { v: CursorValue })[]; keyOrder: \"asc\" | \"desc\" } {\n if (state.c) return { cols: state.c.map((col, i) => ({ ...col, v: state.vs![i] ?? null })), keyOrder: \"asc\" };\n if (state.s === null) return { cols: [], keyOrder: state.o };\n return { cols: [{ s: state.s, o: state.o, v: state.v ?? null }], keyOrder: \"asc\" };\n}\n\n/**\n * The columns a list is ordered by, first one first, before the key: `sorts`\n * when given, else `sort`. A sort on the key ends the list there (the key is\n * unique, so nothing after it can matter) and sets the key's own order;\n * otherwise the key comes last, ascending. A repeated column counts once.\n */\nfunction sortColumns(params: ListParams, key: string): { columns: SortParam[]; keyOrder: \"asc\" | \"desc\" } {\n const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n const columns: SortParam[] = [];\n for (const sort of requested) {\n if (sort.field === key) return { columns, keyOrder: sort.order ?? \"asc\" };\n if (!columns.some((c) => c.field === sort.field)) columns.push({ field: sort.field, order: sort.order ?? \"asc\" });\n }\n return { columns, keyOrder: \"asc\" };\n}\n\n/**\n * The PostgREST `or` clauses selecting the rows after `state` (before it, for\n * a cursor going back), for a list ordered by each sort column (nulls last\n * when ascending and first when descending, as Postgres orders them by\n * default) and then by the key. Spelled out one column at a time: Postgres's\n * row comparison `(a, b) > (x, y)` doesn't follow that null placement, and\n * PostgREST's filters can't express it anyway.\n * @internal Exported for tests.\n */\nexport function keysetClauses(state: CursorState): string {\n const back = state.d === \"b\";\n const k = state.k;\n const K = quoteFilterValue(state.id);\n const { cols, keyOrder } = cursorColumns(state);\n // The key is unique: within ties on every column, the rows after (or before) by the key.\n const keyAhead = `${k}.${(keyOrder === \"asc\") !== back ? \"gt\" : \"lt\"}.${K}`;\n if (cols.length === 0) return keyAhead;\n // Rows that come later on one column, given equal values on the columns before it. The\n // `is.null` pieces go last, so a one-column cursor reads as it always has.\n const main: string[] = [];\n const tail: string[] = [];\n const equal: string[] = [];\n const within = (piece: string) => (equal.length ? `and(${equal.join(\",\")},${piece})` : piece);\n for (const { s, o, v } of cols) {\n // Ascending puts nulls last; going back mirrors which side is \"ahead\".\n const nullsAhead = (o === \"asc\") !== back;\n if (v === null) {\n if (!nullsAhead) main.push(within(`${s}.not.is.null`));\n equal.push(`${s}.is.null`);\n } else {\n const V = quoteFilterValue(v);\n main.push(within(`${s}.${(o === \"asc\") !== back ? \"gt\" : \"lt\"}.${V}`));\n if (nullsAhead) tail.push(within(`${s}.is.null`));\n equal.push(`${s}.eq.${V}`);\n }\n }\n return [...main, `and(${equal.join(\",\")},${keyAhead})`, ...tail].join(\",\");\n}\n\n/** `\"schema.table\"` or `\"table\"` (schema `public`), as Realtime names them. */\nfunction realtimeTable(resource: string): { schema: string; table: string } {\n const dot = resource.indexOf(\".\");\n const strip = (name: string) => name.replace(/\"/g, \"\");\n return dot < 0\n ? { schema: \"public\", table: strip(resource) }\n : { schema: strip(resource.slice(0, dot)), table: strip(resource.slice(dot + 1)) };\n}\n\nlet realtimeChannelSeq = 0;\n\n/** How long after this client's own write a realtime event for that row is taken as its echo. */\nexport const REALTIME_ECHO_MS = 2000;\n\n/** The realtime filter for a list's first equality filter on a plain column, or undefined. */\nfunction realtimeFilter(filters: FilterParam[] | undefined): string | undefined {\n for (const f of filters ?? []) {\n if (f.operator !== \"eq\" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f.field)) continue;\n const v = f.value;\n if (typeof v !== \"string\" && typeof v !== \"number\" && typeof v !== \"boolean\") continue;\n // Realtime's filter grammar has no quoting: skip a value it would misread, or an empty one.\n if (typeof v === \"string\" && (v === \"\" || /[,()]/.test(v))) continue;\n return `${f.field}=eq.${String(v)}`;\n }\n return undefined;\n}\nconst warnedRealtime = new Set<string>();\n\n/**\n * The Supabase data provider. Reads and writes go through the client you\n * pass, under that client's session and RLS.\n *\n * Writes never report a save that did not happen:\n * - `update` and `deleteOne` ask for the affected rows. Zero rows is a\n * `DataWriteError`: the row is read back, and still visible means\n * `forbidden` (RLS or a trigger refused the change), no longer visible\n * means `gone`.\n * - Database errors on writes are thrown as `DataWriteError` with the\n * outcome their code means (`writeOutcomeFromCode`) and the code kept on\n * `error.code`.\n * - Recycle-bin tables (`binTables`) succeed when the row leaves the\n * caller's view.\n *\n * Reads are unchanged: errors are thrown as an `Error` carrying `code`.\n */\nexport function createSupabaseProvider(\n client: SupabaseClientInput,\n options: SupabaseProviderOptions = {},\n): DataProvider {\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n function applyFilters(\n query: SupabaseQueryBuilder,\n filters: FilterParam[] | undefined,\n ): SupabaseQueryBuilder {\n if (!filters) return query;\n for (const f of filters) {\n switch (f.operator) {\n case \"eq\":\n query = query.eq(f.field, f.value);\n break;\n case \"neq\":\n query = query.neq(f.field, f.value);\n break;\n case \"gt\":\n query = query.gt(f.field, f.value);\n break;\n case \"lt\":\n query = query.lt(f.field, f.value);\n break;\n case \"gte\":\n query = query.gte(f.field, f.value);\n break;\n case \"lte\":\n query = query.lte(f.field, f.value);\n break;\n case \"contains\":\n query = query.ilike(f.field, `%${escapeIlike(String(f.value))}%`);\n break;\n case \"in\":\n query = query.in(f.field, f.value);\n break;\n case \"is_null\":\n query = query.is(f.field, null);\n break;\n case \"is_not_null\":\n query = query.not(f.field, \"is\", null);\n break;\n case \"between\": {\n const [lo, hi] = f.value;\n query = query.gte(f.field, lo).lte(f.field, hi);\n break;\n }\n default:\n throw new Error(`[SupabaseProvider] Unknown filter operator \"${(f as FilterParam).operator}\"`);\n break;\n }\n }\n return query;\n }\n\n const maxPerPage = options.maxPerPage ?? 1000;\n // Resources found to have no \"id\" column for the default orderKey.\n const keylessResources = new Set<string>();\n\n /** Tell `onReadError` (sync or async; its failure is swallowed), then throw. */\n async function reportReadError(\n error: DataReadError,\n resource: string,\n operation: \"getList\" | \"getOne\" | \"getMany\",\n ): Promise<never> {\n try {\n await Promise.resolve(options.onReadError?.(error, { resource, operation }));\n } catch {\n // A logging hook never changes what the caller is told.\n }\n throw error;\n }\n\n /** A failed read, as a `DataReadError` with a message users can be shown. */\n async function throwIfReadError(\n result: { error: unknown },\n resource: string,\n operation: \"getList\" | \"getOne\" | \"getMany\",\n ): Promise<void> {\n if (!result.error) return;\n const raw = result.error as { message?: string; code?: string };\n const code = typeof raw.code === \"string\" ? raw.code : undefined;\n const outcome = readOutcomeFromCode(code);\n const error = new DataReadError(\n outcome,\n readFailureMessage(outcome, nounFor(resource), operation === \"getOne\", configFor(resource).nounPlural),\n { code, cause: result.error },\n );\n await reportReadError(error, resource, operation);\n }\n\n // ---------------------------------------------------------------------------\n // Write helpers\n // ---------------------------------------------------------------------------\n\n const from = (resource: string) => client.from(resource) as SupabaseQueryBuilder;\n\n /** How a list of `resource` counts its total: the caller's, else the resource's, else exact. */\n function countMode(resource: string, params: ListParams): CountMode {\n return params.count ?? configFor(resource).count ?? \"exact\";\n }\n\n /** The relation PostgREST names in errors about a read of `resource`: its view, function or table. */\n function readName(resource: string): string {\n const source = configFor(resource).source;\n return typeof source === \"string\" ? source : source ? source.rpc : resource;\n }\n\n /**\n * The values a create or update sends to the table: with `writeColumns`,\n * only those; for an update of a sourced resource without them, only the\n * columns the table's row has, so read-only columns from a view never go out.\n */\n async function tableValues(\n resource: string,\n values: Record<string, unknown>,\n id?: Identifier,\n ): Promise<Record<string, unknown>> {\n const config = configFor(resource);\n if (config.writeColumns) {\n const allowed = new Set(config.writeColumns);\n return Object.fromEntries(Object.entries(values).filter(([key]) => allowed.has(key)));\n }\n if (!config.source || id === undefined) return values;\n const row = await readBack(resource, id);\n if (!row) return values;\n return Object.fromEntries(Object.entries(values).filter(([key]) => key in row));\n }\n\n /** A read of `resource` from its configured source (table, view or function), with its default columns. */\n function read(\n resource: string,\n columns: string | undefined,\n count?: \"exact\" | \"estimated\" | \"planned\",\n ): SupabaseQueryBuilder {\n const config = configFor(resource);\n const cols = columns ?? config.select ?? \"*\";\n const source = config.source;\n if (source && typeof source === \"object\") {\n if (!client.rpc) {\n throw new DataReadError(\"error\", `[SupabaseProvider] \"${resource}\" reads from ${source.rpc}(), but the client has no rpc.`);\n }\n const builder = client.rpc(source.rpc, source.args?.() ?? {}, count ? { count } : undefined) as SupabaseQueryBuilder;\n return builder.select(cols);\n }\n const table = client.from(source ?? resource) as SupabaseQueryBuilder;\n return count ? table.select(cols, { count }) : table.select(cols);\n }\n const configFor = (resource: string): SupabaseResourceConfig =>\n options.resources?.[resource] ?? {};\n const nounFor = (resource: string) => configFor(resource).noun ?? \"record\";\n\n /**\n * Rows this client wrote just now, `${resource}\\0${id}` → the realtime event their write sends\n * and when. Each channel (one per filter) skips the first matching event once, so a later change\n * to the same row (a trigger, a job, another person) is still heard.\n */\n const recentWrites = new Map<\n string,\n { eventType: \"INSERT\" | \"UPDATE\" | \"DELETE\"; at: number; heardOn: Set<string>; openChannels: Set<object> }\n >();\n\n function noteWrite(event: WriteEvent): void {\n const now = Date.now();\n for (const [key, mark] of recentWrites) if (now - mark.at > REALTIME_ECHO_MS) recentWrites.delete(key);\n const eventType = event.kind === \"create\" ? \"INSERT\" : event.kind === \"delete\" ? \"DELETE\" : \"UPDATE\";\n // Only the channels open now carry this write's echo; one opened later never saw the write.\n const openChannels = new Set(\n [...sharedChannels.entries()].filter(([t]) => t.startsWith(`${event.resource}\\u0000`)).map(([, c]) => c as object),\n );\n recentWrites.set(`${event.resource}\\u0000${String(event.id)}`, { eventType, at: now, heardOn: new Set(), openChannels });\n }\n /** One realtime channel per resource and server filter, shared by every subscriber to it. */\n const sharedChannels = new Map<\n string,\n { listeners: Set<{ emit: (event: ResourceChangeEvent) => void; id?: Identifier }>; close: () => void }\n >();\n\n function isEcho(\n resource: string,\n id: unknown,\n eventType: SupabaseRealtimePayload[\"eventType\"],\n topic: string,\n channelObject: object | undefined,\n ): boolean {\n if (!isIdentifier(id)) return false;\n const key = `${resource}\\u0000${String(id)}`;\n const mark = recentWrites.get(key);\n // Only a channel that was open at the write carries its echo: one reopened on the same topic\n // since then is a different object and never saw it.\n if (!mark || mark.eventType !== eventType || mark.heardOn.has(topic) || !channelObject || !mark.openChannels.has(channelObject)) return false;\n if (Date.now() - mark.at > REALTIME_ECHO_MS) {\n recentWrites.delete(key);\n return false;\n }\n mark.heardOn.add(topic);\n return true;\n }\n\n function realtimeEnabled(resource: string): boolean {\n if (typeof client.channel !== \"function\") return false;\n const own = configFor(resource).realtime;\n if (own !== undefined) return own;\n const all = options.realtime;\n if (!all) return false;\n if (all === true) return true;\n return typeof all === \"function\" ? all(resource) : all.includes(resource);\n }\n\n function isBinTable(resource: string): boolean {\n const mode = configFor(resource).deleteMode;\n if (mode) return mode === \"bin\";\n const bin = options.binTables;\n if (!bin) return false;\n return typeof bin === \"function\" ? bin(resource) : bin.includes(resource);\n }\n\n /** Awaits a write-path query: its rows, or a `DataWriteError`. */\n async function run(query: SupabaseQueryBuilder): Promise<unknown[]> {\n let result: { data: unknown; error: unknown };\n try {\n result = (await query) as { data: unknown; error: unknown };\n } catch (error) {\n throw toDataWriteError(error);\n }\n if (result.error) throw toDataWriteError(result.error);\n if (Array.isArray(result.data)) return result.data;\n return result.data == null ? [] : [result.data];\n }\n\n async function isVisible(resource: string, id: Identifier): Promise<boolean> {\n return (await run(from(resource).select(\"id\").eq(\"id\", id))).length > 0;\n }\n\n async function readBack(resource: string, id: Identifier): Promise<BaseRecord | undefined> {\n return (await run(from(resource).select(\"*\").eq(\"id\", id)))[0] as BaseRecord | undefined;\n }\n\n function goneError(resource: string): DataWriteError {\n return new DataWriteError(\n \"gone\",\n `This ${nounFor(resource)} no longer exists, or you can no longer see it.`,\n );\n }\n\n /**\n * A write matched no rows: read the row back to say why. Still visible\n * means the change was refused; not visible means it is gone (deleted, or\n * hidden from this user — the two can't be told apart under RLS).\n */\n async function noRowsError(\n resource: string,\n id: Identifier,\n verb: \"change\" | \"delete\",\n ): Promise<DataWriteError> {\n let visible: boolean;\n try {\n visible = await isVisible(resource, id);\n } catch (error) {\n const cause = toDataWriteError(error);\n return new DataWriteError(\n cause.outcome === \"unauthenticated\" ? \"unauthenticated\" : \"error\",\n `This ${nounFor(resource)} was not ${verb === \"change\" ? \"changed\" : \"deleted\"}, and reading it back failed (${cause.message}).`,\n { code: cause.code, cause: error },\n );\n }\n if (visible) {\n return new DataWriteError(\"forbidden\", `You can't ${verb} this ${nounFor(resource)}.`);\n }\n return goneError(resource);\n }\n\n async function prepare(\n resource: string,\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ): Promise<Record<string, unknown>> {\n const rule = configFor(resource).prepare;\n if (!rule) return values;\n try {\n return await rule({ ...values }, context);\n } catch (error) {\n throw toDataWriteError(error);\n }\n }\n\n /** After a committed write. Never turns it into a failure. */\n async function committed(event: WriteEvent): Promise<void> {\n // Its realtime echo is this client's own write: it already refreshes through the write path.\n if (event.id != null) noteWrite(event);\n if (!options.onWrite) return;\n try {\n await options.onWrite(event);\n } catch (error) {\n console.error(`[SupabaseProvider] onWrite failed for \"${event.resource}\":`, error);\n }\n }\n\n // ---------------------------------------------------------------------------\n // DataProvider implementation\n // ---------------------------------------------------------------------------\n\n /** The search as PostgREST `or` clauses, or \"\" for none. */\n function searchClauses(resource: string, params: ListParams): string {\n const searchFields = configFor(resource).searchFields ?? params.search?.fields ?? [];\n if (!params.search || !params.search.query || searchFields.length === 0) return \"\";\n const escaped = escapeIlike(params.search.query);\n const safeFieldPattern = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;\n return searchFields\n .filter((f) => safeFieldPattern.test(f))\n // Quoted, so commas, dots and parens in the query stay literal (also\n // when nested inside the keyset's `and(or(…))`).\n .map((f) => `${f}.ilike.${quoteFilterValue(`%${escaped}%`)}`)\n .join(\",\");\n }\n\n /** A cursor request this provider can't serve: `invalid`, with why as the cause. */\n function refuseCursor(resource: string, why: string): Promise<never> {\n return reportReadError(\n new DataReadError(\n \"invalid\",\n readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural),\n { cause: new Error(`[SupabaseProvider] \"${resource}\": ${why}`) },\n ),\n resource,\n \"getList\",\n );\n }\n\n /**\n * One page by keyset: ordered by the sort column and then the key, the\n * rows after the cursor's row, plus one more to tell whether a next page\n * exists. Counted only on the first page.\n */\n async function getCursorPage(\n resource: string,\n params: ListParams,\n key: string | false,\n ): Promise<{ data: unknown[]; total: number; nextCursor: string | null; prevCursor: string | null }> {\n const { cursor } = params.pagination!;\n // The look-ahead row must fit under PostgREST's max-rows (maxPerPage), or\n // it is dropped and the list would end after one page. A keyset page can\n // be shorter than asked without skipping or repeating rows.\n const perPage = Math.max(1, Math.min(params.pagination!.perPage, maxPerPage - 1));\n if (!key) {\n return refuseCursor(resource, \"cursor paging needs a unique key column to order by; its orderKey is false. Set orderKey to a unique, non-null column, or page by offset.\");\n }\n if (!PLAIN_COLUMN.test(key)) return refuseCursor(resource, `the key column \"${key}\" can't be used in a cursor.`);\n const { columns, keyOrder } = sortColumns(params, key);\n const unplain = columns.find((c) => !PLAIN_COLUMN.test(c.field));\n if (unplain) return refuseCursor(resource, `cursor paging can sort only by a plain column, not \"${unplain.field}\".`);\n const sortFields = columns.map((c) => c.field);\n // One column keeps the cursor's original shape; several use `c`/`vs`.\n const shape = (values: CursorValue[]): Pick<CursorState, \"s\" | \"o\" | \"v\" | \"c\" | \"vs\"> =>\n columns.length === 0\n ? { s: null, o: keyOrder }\n : columns.length === 1\n ? { s: columns[0]!.field, o: columns[0]!.order, v: values[0] ?? null }\n : { s: null, o: \"asc\", c: columns.map((c) => ({ s: c.field, o: c.order })), vs: values };\n const sortId = JSON.stringify([columns.map((c) => [c.field, c.order]), keyOrder]);\n\n let after: CursorState | undefined;\n if (cursor) {\n after = decodeCursor(cursor);\n if (!after) return refuseCursor(resource, \"the cursor is not one this provider made.\");\n const made = cursorColumns(after);\n if (JSON.stringify([made.cols.map((c) => [c.s, c.o]), made.keyOrder]) !== sortId || after.k !== key) {\n return refuseCursor(resource, \"the cursor was made for a different sort; start again from the first page (cursor: null).\");\n }\n }\n\n const mode = countMode(resource, params);\n let query = read(resource, params.select, cursor || mode === \"none\" ? undefined : mode);\n query = applyFilters(query, params.filters);\n const search = searchClauses(resource, params);\n const keyset = after ? keysetClauses(after) : \"\";\n // Both are OR groups that must hold together: nest them in one `or`.\n if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);\n else if (search || keyset) query = query.or(search || keyset);\n\n // Going back reads the rows before the cursor in the reverse order (nearest first), then\n // turns them around.\n const back = after?.d === \"b\";\n for (const { field, order } of columns) {\n // Pinned to Postgres's default null placement, which the keyset assumes.\n const ascending = (order === \"asc\") !== back;\n query = query.order(field, { ascending, nullsFirst: !ascending });\n }\n query = query.order(key, { ascending: (keyOrder === \"asc\") !== back });\n query = query.range(0, perPage);\n\n const result = (await query) as unknown as { data: unknown[] | null; error: unknown; count?: number | null };\n await throwIfReadError(result, resource, \"getList\");\n const rows = (result.data ?? []) as Record<string, unknown>[];\n const more = rows.length > perPage;\n const page = rows.slice(0, perPage);\n if (back) page.reverse();\n // A cursor for the rows after or before `row`.\n const cursorAt = (row: Record<string, unknown> | undefined, direction?: \"b\"): string | null | false => {\n if (!row) return null;\n const id = row[key];\n if (!isIdentifier(id) || sortFields.some((f) => !(f in row))) return false;\n const values = sortFields.map((f) => row[f] ?? null);\n if (values.some((v) => v !== null && typeof v === \"object\")) return false;\n return encodeCursor({ ...shape(values as CursorValue[]), k: key, id, ...(direction ? { d: direction } : {}) });\n };\n // Forward: more after the last row when the look-ahead found one; rows before the first\n // whenever this wasn't the first page. Back: the mirror.\n const next = back ? cursorAt(page[page.length - 1]) : more ? cursorAt(page[page.length - 1]) : null;\n const prev = back ? (more ? cursorAt(page[0], \"b\") : null) : cursor ? cursorAt(page[0], \"b\") : null;\n if (next === false || prev === false) {\n const objectValued = sortFields.find((f) =>\n page.some((row) => f in row && row[f] !== null && typeof row[f] === \"object\"),\n );\n if (objectValued) {\n return refuseCursor(resource, `cursor paging can't sort by \"${objectValued}\": its values aren't plain (text, number, date, boolean).`);\n }\n const needed = [key, ...sortFields].map((f) => `\"${f}\"`);\n const list = needed.length === 1 ? needed[0] : `${needed.slice(0, -1).join(\", \")} and ${needed[needed.length - 1]}`;\n return refuseCursor(resource, `the selected columns must include ${list} to page by cursor.`);\n }\n return {\n data: page,\n total: cursor || mode === \"none\" ? -1 : (result.count ?? 0),\n ...(!cursor && (mode === \"estimated\" || mode === \"planned\") ? { totalIsEstimate: true } : {}),\n nextCursor: next,\n prevCursor: prev,\n };\n }\n\n const provider: DataProvider = {\n async getList(resource, params) {\n // Refused, not cut short: a shorter page than the caller asked for\n // would shift every later page's boundary and skip or repeat rows.\n if (params.pagination && params.pagination.perPage > maxPerPage) {\n const { perPage } = params.pagination;\n await reportReadError(\n new DataReadError(\n \"invalid\",\n readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural),\n {\n cause: new Error(\n `[SupabaseProvider] \"${resource}\" asked for ${perPage} rows per page; the most is ${maxPerPage} (maxPerPage). Ask for at most ${maxPerPage} and page through the rest.`,\n ),\n },\n ),\n resource,\n \"getList\",\n );\n }\n\n const configuredKey = configFor(resource).orderKey;\n if (params.pagination && params.pagination.cursor !== undefined) {\n return getCursorPage(resource, params, configuredKey === undefined ? \"id\" : configuredKey) as never;\n }\n const mode = countMode(resource, params);\n const run = (key: string | false) => {\n let query = read(resource, params.select, mode === \"none\" ? undefined : mode);\n\n query = applyFilters(query, params.filters);\n\n // Search — convert to OR of ilike. A resource's configured\n // `searchFields` win over the caller's.\n const clauses = searchClauses(resource, params);\n if (clauses) {\n query = query.or(clauses);\n }\n\n // Each sort column, then the key column, so equal sort values keep\n // one order across pages (otherwise a row can repeat on page 2 or be\n // skipped). An unsorted page is ordered by the key alone: without an\n // ORDER BY the database may return pages in any order.\n const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (requested.length > 0 && key) {\n const { columns, keyOrder } = sortColumns(params, key);\n for (const { field, order } of columns) query = query.order(field, { ascending: order === \"asc\" });\n query = query.order(key, { ascending: keyOrder === \"asc\" });\n } else if (requested.length > 0) {\n for (const { field, order } of requested) query = query.order(field, { ascending: order === \"asc\" });\n } else if (params.pagination && key) {\n query = query.order(key, { ascending: true });\n }\n\n if (params.pagination) {\n const { page, perPage } = params.pagination;\n const from = (page - 1) * perPage;\n const to = from + perPage - 1;\n query = query.range(from, to);\n }\n\n return query as unknown as Promise<{\n data: unknown[];\n error: unknown;\n count?: number | null;\n }>;\n };\n\n // The default key (\"id\") is a guess: a view without that column reads\n // as before, without the key order, and is not ordered by it again.\n const guessKey = configuredKey === undefined && !keylessResources.has(resource);\n let result = await run(configuredKey ?? (keylessResources.has(resource) ? false : \"id\"));\n if (guessKey && isMissingColumn(result.error, readName(resource), \"id\")) {\n keylessResources.add(resource);\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[SupabaseProvider] \"${resource}\" has no \"id\" column, so its pages have no stable order. Set resources.${resource}.orderKey to a unique column (or false to silence this).`,\n );\n }\n result = await run(false);\n }\n await throwIfReadError(result, resource, \"getList\");\n\n return {\n data: result.data ?? [],\n total: mode === \"none\" ? -1 : (result.count ?? 0),\n ...(mode === \"estimated\" || mode === \"planned\" ? { totalIsEstimate: true } : {}),\n } as never;\n },\n\n async getOne(resource, params) {\n const result = (await read(resource, params.select)\n .eq(\"id\", params.id)\n .single()) as { data: unknown; error: unknown };\n await throwIfReadError(result, resource, \"getOne\");\n return { data: result.data } as never;\n },\n\n async getMany(resource, params) {\n if (params.ids.length === 0) return { data: [] } as never;\n const result = (await read(resource, undefined)\n .in(\"id\", params.ids)) as { data: unknown[]; error: unknown };\n await throwIfReadError(result, resource, \"getMany\");\n return { data: result.data ?? [] } as never;\n },\n\n async capabilities(resource?: string): Promise<ProviderCapabilities> {\n return {\n search: resource ? configFor(resource).searchFields?.length !== 0 : true,\n sort: true,\n filterOperators: SERVED_OPERATORS,\n bulkWrites: false,\n versionedWrites: false,\n compositeKeys: false,\n multiSort: true,\n create: true,\n delete: true,\n maxPerPage,\n softDelete: resource ? isBinTable(resource) : false,\n cursorPagination: resource ? configFor(resource).orderKey !== false : true,\n realtime: resource\n ? realtimeEnabled(resource)\n : typeof client.channel === \"function\" &&\n (!!options.realtime ||\n Object.values(options.resources ?? {}).some((r) => r.realtime === true)),\n };\n },\n\n subscribe(resource, params, callback) {\n if (!realtimeEnabled(resource)) {\n if (process.env.NODE_ENV !== \"production\" && !warnedRealtime.has(resource)) {\n warnedRealtime.add(resource);\n console.warn(\n typeof client.channel !== \"function\"\n ? `[SupabaseProvider] \"${resource}\" was subscribed to, but the client has no channel() (Supabase Realtime), so nothing will be reported.`\n : `[SupabaseProvider] \"${resource}\" was subscribed to, but realtime is off for it. Set resources.${resource}.realtime (or the realtime option) to true.`,\n );\n }\n return () => {};\n }\n const { schema, table } = realtimeTable(resource);\n // One record is matched below, not with a server-side `id=eq.` filter, so it can share the\n // resource's channel. A list's first equality filter narrows the channel on the server.\n // Not for a resource read from a view or function: the filter may name a column only the view\n // has, and the channel watches the table.\n const serverFilter =\n params.id != null || configFor(resource).source !== undefined ? undefined : realtimeFilter(params.filters);\n const topic = `${resource}\\u0000${serverFilter ?? \"\"}`;\n // The row is passed on only where it is the resource's own row: a resource read from a view\n // or function shows other columns, so its listeners refetch instead.\n const sendRecord = configFor(resource).source === undefined;\n let shared = sharedChannels.get(topic);\n if (!shared) {\n const listeners = new Set<{ emit: (event: ResourceChangeEvent) => void; id?: Identifier }>();\n // A unique topic: supabase-js hands back an existing channel for a topic already open.\n const channel = client.channel!(`genesis:${resource}:${++realtimeChannelSeq}`) as SupabaseRealtimeChannel;\n let subscribedOnce = false;\n let interrupted = false;\n const broadcast = (event: ResourceChangeEvent, rowId?: unknown) => {\n for (const l of listeners) {\n if (l.id != null && isIdentifier(rowId) && String(rowId) !== String(l.id)) continue;\n l.emit(event);\n }\n };\n const onChange = (payload: SupabaseRealtimePayload) => {\n // Realtime applies RLS to inserts and updates; a delete's old key goes to every\n // subscriber, so a delete passes on only its id.\n const row = payload.eventType === \"DELETE\" ? payload.old : payload.new;\n const id = row?.[\"id\"];\n if (isEcho(resource, id, payload.eventType, topic, sharedChannels.get(topic))) return;\n const type =\n payload.eventType === \"INSERT\" ? \"created\" : payload.eventType === \"UPDATE\" ? \"updated\" : \"deleted\";\n const event: ResourceChangeEvent = isIdentifier(id)\n ? sendRecord && type !== \"deleted\" && row\n ? { type, id, record: row as BaseRecord }\n : { type, id }\n : { type };\n broadcast(event, id);\n };\n if (serverFilter) {\n // Only inserts are filtered. Realtime filters on the new row, so a filtered update would\n // never report a row leaving the list (status open → closed); and it never delivers\n // deletes through a filter. Both come unfiltered.\n channel.on(\"postgres_changes\", { event: \"INSERT\", schema, table, filter: serverFilter }, onChange);\n channel.on(\"postgres_changes\", { event: \"UPDATE\", schema, table }, onChange);\n channel.on(\"postgres_changes\", { event: \"DELETE\", schema, table }, onChange);\n } else {\n channel.on(\"postgres_changes\", { event: \"*\", schema, table }, onChange);\n }\n channel.subscribe((status) => {\n if (status === \"SUBSCRIBED\") {\n // Back after a drop: changes made meanwhile were not sent.\n if (subscribedOnce && interrupted) broadcast({ type: \"changed\" });\n subscribedOnce = true;\n interrupted = false;\n } else if (status === \"CHANNEL_ERROR\" || status === \"TIMED_OUT\" || status === \"CLOSED\") {\n interrupted = true;\n }\n });\n shared = {\n listeners,\n close: () => {\n try {\n const done =\n typeof client.removeChannel === \"function\" ? client.removeChannel(channel) : channel.unsubscribe?.();\n // A failed removal (socket already gone) is nothing to report.\n if (done && typeof (done as Promise<unknown>).catch === \"function\") {\n (done as Promise<unknown>).catch(() => {});\n }\n } catch {\n // As above.\n }\n },\n };\n sharedChannels.set(topic, shared);\n }\n let closed = false;\n const listener = {\n id: params.id,\n emit: (event: ResourceChangeEvent) => {\n if (closed) return;\n try {\n callback(event);\n } catch (error) {\n console.error(`[SupabaseProvider] a realtime callback for \"${resource}\" threw:`, error);\n }\n },\n };\n shared.listeners.add(listener);\n const mine = shared;\n return () => {\n if (closed) return;\n closed = true;\n mine.listeners.delete(listener);\n if (mine.listeners.size === 0 && sharedChannels.get(topic) === mine) {\n sharedChannels.delete(topic);\n mine.close();\n }\n };\n },\n\n async create(resource, params) {\n const row = await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"create\" }),\n );\n const override = configFor(resource).create;\n let record: BaseRecord;\n if (override) {\n let returned: BaseRecord | Identifier;\n try {\n returned = await override(row);\n } catch (error) {\n throw toDataWriteError(error);\n }\n if (isIdentifier(returned)) {\n // The row exists from here on. A failed read-back must not report\n // the create as failed: the user would retry and make a second one.\n record = (await readBack(resource, returned).catch(() => undefined)) ?? { id: returned };\n } else if (returned && typeof returned === \"object\" && isIdentifier(returned.id)) {\n record = returned;\n } else {\n throw new DataWriteError(\n \"error\",\n `[SupabaseProvider] The create rule for \"${resource}\" returned neither the new row nor its id.`,\n );\n }\n } else {\n const rows = await run(from(resource).insert(row).select(\"*\").single());\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"create\", id: record.id, record });\n return { data: record } as never;\n },\n\n async update(resource, params) {\n const { id } = params;\n const row = await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"update\", id }),\n id,\n );\n const override = configFor(resource).update;\n let record: BaseRecord;\n if (override) {\n let returned: BaseRecord | Identifier | boolean | null | undefined | void;\n try {\n returned = await override(id, row);\n } catch (error) {\n throw toDataWriteError(error);\n }\n const result: unknown = returned;\n if (result == null || result === false) throw await noRowsError(resource, id, \"change\");\n if (isIdentifier(result) || result === true) {\n // The change committed; a failed read-back still reports it saved.\n const readId = result === true ? id : result;\n record = (await readBack(resource, readId).catch(() => undefined)) ?? { ...row, id: readId };\n } else if (typeof result === \"object\") {\n record = { id, ...(result as Record<string, unknown>) } as BaseRecord;\n } else {\n throw new DataWriteError(\n \"error\",\n `[SupabaseProvider] The update rule for \"${resource}\" returned neither the row, its id, nor nothing.`,\n );\n }\n } else {\n const rows = await run(from(resource).update(row).eq(\"id\", id).select(\"*\"));\n if (rows.length === 0) throw await noRowsError(resource, id, \"change\");\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"update\", id, record });\n return { data: record } as never;\n },\n\n async deleteOne(resource, params) {\n const { id } = params;\n let deletedId: Identifier = id;\n if (isBinTable(resource)) {\n // A binned delete reports zero rows whether or not it worked, so the\n // answer comes from visibility before and after.\n if (!(await isVisible(resource, id))) throw goneError(resource);\n await run(from(resource).delete().eq(\"id\", id));\n let stillVisible: boolean;\n try {\n stillVisible = await isVisible(resource, id);\n } catch (error) {\n const cause = toDataWriteError(error);\n throw new DataWriteError(\n \"error\",\n `The ${nounFor(resource)} may not have been deleted: checking it failed (${cause.message}).`,\n { code: cause.code, cause: error },\n );\n }\n if (stillVisible) {\n throw new DataWriteError(\"forbidden\", `You can't delete this ${nounFor(resource)}.`);\n }\n } else {\n const rows = await run(from(resource).delete().eq(\"id\", id).select(\"id\"));\n if (rows.length === 0) throw await noRowsError(resource, id, \"delete\");\n const returnedId = (rows[0] as { id?: unknown }).id;\n if (isIdentifier(returnedId)) deletedId = returnedId;\n }\n await committed({ resource, kind: \"delete\", id: deletedId });\n return { data: { id: deletedId } };\n },\n\n toFormValues(resource, record) {\n const map = configFor(resource).toFormValues;\n return map ? map(record) : record;\n },\n\n invalidates(event) {\n const keys = configFor(event.resource).invalidates;\n if (!keys) return [];\n return typeof keys === \"function\" ? keys(event) : keys;\n },\n };\n\n // How many write marks are held, for tests of the pruning. Not part of the provider contract.\n Object.defineProperty(provider, \"__recentWriteCount\", { value: () => recentWrites.size, enumerable: false });\n return provider;\n}\n","// ---------------------------------------------------------------------------\n// Write helpers (README \"One-off writes\")\n//\n// The writes a resource page doesn't cover: a database function (RPC) with\n// plain error words, and \"one live row per key\" (create, or adopt the row\n// that's already there). Both fail with a DataWriteError, like the provider.\n// ---------------------------------------------------------------------------\n\nimport { DataWriteError, isDataWriteError } from \"../schema/write-outcome\";\nimport { toDataWriteError } from \"./postgrest-errors\";\nimport type { BaseRecord, DataProvider, FilterParam } from \"./types\";\n\n/** Anything with Supabase's `rpc`. */\nexport interface RpcClient {\n rpc(fn: string, args?: Record<string, unknown>): PromiseLike<{ data: unknown; error: unknown }>;\n}\n\n/** The words shown for a code when the caller gives none. A guard's own `raise exception` (P0001) keeps its words. */\nexport const DEFAULT_RPC_MESSAGES: Readonly<Record<string, string>> = {\n \"42501\": \"You can't do that.\",\n \"22023\": \"That request isn't valid.\",\n \"23505\": \"That already exists.\",\n \"28000\": \"Sign in to continue.\",\n PGRST202: \"That action isn't available.\",\n PGRST301: \"Sign in to continue.\",\n};\n\nexport const RPC_FAILED = \"That didn't work. Try again.\";\n\nexport interface CallRpcOptions {\n /** Words per error code, e.g. `{ \"55000\": \"This course has already started.\" }`; these win over the defaults. */\n messages?: Record<string, string>;\n}\n\n/**\n * Calls a database function and returns its result. A failure throws a\n * DataWriteError with the usual outcome and code, and words a person can\n * read: yours for the code, a guard's own message (P0001), the defaults\n * above, or a generic sentence. The raw error stays on `cause`.\n */\nexport async function callRpc<T = unknown>(\n client: RpcClient,\n fn: string,\n args: Record<string, unknown> = {},\n options: CallRpcOptions = {},\n): Promise<T> {\n let result: { data: unknown; error: unknown };\n try {\n result = await client.rpc(fn, args);\n } catch (error) {\n // A client that already speaks DataWriteError (signed out, a refusal) keeps its outcome and code.\n if (isDataWriteError(error)) throw error;\n throw new DataWriteError(\"error\", RPC_FAILED, { cause: error });\n }\n if (!result || typeof result !== \"object\") {\n throw new DataWriteError(\"error\", RPC_FAILED, { cause: new Error(`rpc ${fn} returned ${String(result)}`) });\n }\n if (!result.error) return result.data as T;\n const mapped = toDataWriteError(result.error);\n const code = mapped.code;\n const custom = code !== undefined ? options.messages?.[code] : undefined;\n const raw = (result.error as { message?: unknown }).message;\n const guardWords = typeof raw === \"string\" && raw.trim() ? raw : undefined;\n const message =\n custom ??\n (code === \"P0001\" ? guardWords : undefined) ??\n (mapped.fields ? mapped.message : undefined) ??\n (code !== undefined ? DEFAULT_RPC_MESSAGES[code] : undefined) ??\n RPC_FAILED;\n throw new DataWriteError(mapped.outcome, message, { code, fields: mapped.fields, cause: result.error });\n}\n\nexport interface CreateOrAdoptOptions<T extends BaseRecord> {\n /** The fields that make a row unique (its unique index), read from `data`. */\n key: readonly (keyof T & string)[];\n /**\n * Changes to write over a row that was already there; return null to keep it\n * as it is. It runs on the row as read just now, and the update isn't\n * conditional: two callers merging into one row at once can each overwrite\n * the other. Where that matters, merge in a database function instead.\n */\n merge?: (existing: T) => Partial<T> | null;\n /**\n * Whether the row already there is finished and can't take changes (a sent answer): it's handed\n * back with `final: true` and `merge` isn't called, so the caller stops instead of writing over it.\n */\n final?: (existing: T) => boolean;\n /**\n * Extra filters on the lookup, for a partial unique index: the rows the index covers, e.g.\n * `[{ field: \"deleted_at\", operator: \"is_null\" }, { field: \"kind\", operator: \"eq\", value: \"worksheet\" }]`.\n * A clash on an index whose key is an expression reports no fields, so it's adopted by key and scope.\n */\n scope?: readonly FilterParam[];\n}\n\nexport type CreateOrAdoptResult<T> = {\n row: T;\n /** The row was already there. */\n adopted: boolean;\n /** The row already there is finished (see `final`): nothing was written. */\n final: boolean;\n};\n\n/**\n * \"One live row per key\": creates the row, or, when one with the same key is\n * already there (a `duplicate`), adopts it, optionally merging changes in.\n * `adopted` says which, and `final` that the row already there is finished. Key\n * fields that are null or undefined match rows where they're null. A duplicate\n * you can't see is still an error.\n */\nexport async function createOrAdopt<T extends BaseRecord>(\n provider: DataProvider,\n resource: string,\n data: Partial<T>,\n options: CreateOrAdoptOptions<T>,\n): Promise<CreateOrAdoptResult<T>> {\n if (options.key.length === 0) throw new Error(`[genesis-core] createOrAdopt(\"${resource}\") needs a key`);\n try {\n return { row: (await provider.create<T>(resource, { data })).data, adopted: false, final: false };\n } catch (error) {\n if (!isDataWriteError(error) || error.outcome !== \"duplicate\") throw error;\n // A clash on some other unique index isn't this key's row.\n if (error.fields && Object.keys(error.fields).some((field) => !options.key.includes(field as keyof T & string))) throw error;\n const filters: FilterParam[] = options.key.map((field) => {\n const value = (data as Record<string, unknown>)[field];\n if (value === null || value === undefined) return { field, operator: \"is_null\" };\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n throw new Error(`[genesis-core] createOrAdopt(\"${resource}\") key field ${field} must be a string, number or boolean`);\n }\n return { field, operator: \"eq\", value };\n });\n const { data: rows } = await provider.getList<T>(resource, {\n filters: [...filters, ...(options.scope ?? [])],\n pagination: { page: 1, perPage: 2 },\n });\n if (rows.length !== 1) throw error;\n const existing = rows[0]!;\n if (options.final?.(existing)) return { row: existing, adopted: true, final: true };\n const changes = options.merge?.(existing);\n if (!changes || Object.keys(changes).length === 0) return { row: existing, adopted: true, final: false };\n return {\n row: (await provider.update<T>(resource, { id: existing.id, data: changes })).data,\n adopted: true,\n final: false,\n };\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { patchCachedRow, listCouldChange } from './chunk-AUVKRXRC.js';
|
|
2
|
-
import { useDataProvider } from './chunk-
|
|
2
|
+
import { useDataProvider } from './chunk-VDEW4AOS.js';
|
|
3
3
|
import { useRef, useEffect } from 'react';
|
|
4
4
|
import { useQueryClient } from '@tanstack/react-query';
|
|
5
5
|
|
|
@@ -89,5 +89,5 @@ function useLiveInvalidation(resource, live, enabled, params, queryKey, accept)
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
export { DEFAULT_LIVE_DEBOUNCE_MS, DEFAULT_LIVE_RESYNC_MS, useLiveInvalidation };
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
93
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-K4ZNAF3G.js.map
|
|
93
|
+
//# sourceMappingURL=chunk-K4ZNAF3G.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-live.ts"],"names":[],"mappings":";;;;;AA0BO,IAAM,wBAAA,GAA2B;AAOjC,IAAM,sBAAA,GAAyB;AAkBtC,IAAM,iBAAA,uBAAwB,OAAA,EAAgB;AAUvC,SAAS,oBACd,QAAA,EACA,IAAA,EACA,OAAA,EACA,MAAA,EACA,UACA,MAAA,EACM;AACN,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,cAAc,cAAA,EAAe;AACnC,EAAA,MAAM,EAAA,GAAK,CAAC,CAAC,IAAA,IAAQ,OAAA;AACrB,EAAA,MAAM,aAAa,IAAA,CAAK,GAAA;AAAA,IACtB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,aAAa,MAAA,KAAc;AAAA,GAC9D;AACA,EAAA,MAAM,WAAW,IAAA,CAAK,GAAA;AAAA,IACpB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,WAAW,MAAA,KAAc;AAAA,GAC5D;AACA,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA;AACvC,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAItC,EAAA,MAAM,SAAS,MAAA,CAAO,EAAE,QAAA,EAAU,MAAA,EAAQ,QAAQ,CAAA;AAClD,EAAA,MAAA,CAAO,OAAA,GAAU,EAAE,QAAA,EAAU,MAAA,EAAQ,MAAA,EAAO;AAE5C,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,IAAI,CAAC,EAAA,EAAI;AACT,IAAA,I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AU,CAAA;AAAA,IACtG,CAAA,EAAG,QAAQ,CAAA,GACX,MAAA;AACN,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,IAAI,MAAA,KAAW,MAAA,EAAW,aAAA,CAAc,MAAM,CAAA;AAC9C,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,KAAK,CAAA;AAC3C,MAAA,IAAI;AACF,QAAA,WAAA,IAAc;AAAA,MAChB,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,8BAAA,EAAiC,QAAQ,CAAA,SAAA,CAAA,EAAa,KAAK,CAAA;AAAA,MAC3E;AAAA,IACF,CAAA;AAAA,EAEF,CAAA,EAAG,CAAC,EAAA,EAAI,QAAA,EAAU,WAAA,EAAa,UAAU,UAAA,EAAY,QAAA,EAAU,SAAA,EAAW,MAAM,CAAC,CAAA;AACnF","file":"chunk-UV3ROHQA.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Live reads — refetch a resource's cached reads when the provider reports a\n// change (`DataProvider.subscribe`).\n//\n// Events are invalidation hints. When an update carries the row (the provider\n// sends one only for a resource read from its own table, under realtime's RLS),\n// the fields cached rows already have are patched at once; the refetch that\n// follows still goes through the provider's normal read, so what a user ends\n// up seeing is what that read (and its RLS) returns. Lists the change can't\n// have touched (its row matches none of their filters and isn't in them) are\n// left alone.\n//\n// Pending optimistic and undoable writes are safe: their patches are\n// re-applied to whatever a refetch brings (see mutation-mode.ts), so a row\n// deleted with undo stays hidden and an edit stays shown until the write\n// settles. The provider drops the echo of this client's own writes, which\n// already refresh through the write path.\n// ---------------------------------------------------------------------------\n\nimport { useEffect, useRef } from \"react\";\nimport { useQueryClient, type QueryKey } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { ResourceChangeEvent, SubscribeParams } from \"../provider/types\";\nimport { listCouldChange, patchCachedRow } from \"./live-cache\";\n\n/** How long a burst of change events is gathered into one refetch. */\nexport const DEFAULT_LIVE_DEBOUNCE_MS = 250;\n\n/**\n * How often a live read refetches anyway while the page is visible. Realtime checks each change\n * against the row's new state, so a row the viewer stops being allowed to see (binned, made a\n * draft, moved to another practice) sends them nothing and would stay on screen.\n */\nexport const DEFAULT_LIVE_RESYNC_MS = 60_000;\n\n/** `live` as an object, to tune it. `live: true` takes the defaults. */\nexport interface LiveOptions {\n /**\n * Events arriving within this many milliseconds of each other cause one\n * refetch, not one each. Default {@link DEFAULT_LIVE_DEBOUNCE_MS}. A\n * steady stream still refetches at least every `4 × debounceMs`.\n */\n debounceMs?: number;\n /**\n * Refetch at least this often while the page is visible, for the changes realtime can't\n * deliver (a row the viewer may no longer read). Default {@link DEFAULT_LIVE_RESYNC_MS}; 0 turns\n * it off.\n */\n resyncMs?: number;\n}\n\nconst warnedNoSubscribe = new WeakSet<object>();\n\n/**\n * Subscribes while mounted and `enabled`, and invalidates `queryKey` (a\n * prefix) once per burst of events that `accept` lets through. While the\n * page is hidden the queries are only marked stale; they refetch when it is\n * shown again (TanStack Query's `refetchOnWindowFocus`) or next used.\n *\n * @internal Used by `useResource` and `useOne`'s `live` option.\n */\nexport function useLiveInvalidation(\n resource: string,\n live: boolean | LiveOptions | undefined,\n enabled: boolean,\n params: SubscribeParams,\n queryKey: QueryKey,\n accept?: (event: ResourceChangeEvent) => boolean,\n): void {\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n const on = !!live && enabled;\n const debounceMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.debounceMs : undefined) ?? DEFAULT_LIVE_DEBOUNCE_MS,\n );\n const resyncMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.resyncMs : undefined) ?? DEFAULT_LIVE_RESYNC_MS,\n );\n const paramsKey = JSON.stringify(params);\n const keyKey = JSON.stringify(queryKey);\n\n // The latest values, read when an event arrives, so a new array or\n // callback each render doesn't resubscribe.\n const latest = useRef({ queryKey, accept, params });\n latest.current = { queryKey, accept, params };\n\n useEffect(() => {\n if (!on) return;\n if (typeof provider.subscribe !== \"function\") {\n if (process.env.NODE_ENV !== \"production\" && !warnedNoSubscribe.has(provider)) {\n warnedNoSubscribe.add(provider);\n console.warn(\n `[genesis] \"${resource}\" asked for live updates, but the data provider has no subscribe(); the list will only refresh on its own reads.`,\n );\n }\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n let burstStart = 0;\n // The rows of this burst's updates; null once an event without one (a delete, an insert,\n // `changed`) means every read must refetch.\n let burst: Record<string, unknown>[] | null = [];\n let active = true;\n // A busy table must not postpone the refetch forever.\n const maxWaitMs = debounceMs * 4;\n const fire = () => {\n timer = undefined;\n if (!active) return;\n const hidden = typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n const rows = burst;\n burst = [];\n void queryClient.invalidateQueries({\n queryKey: [...latest.current.queryKey],\n refetchType: hidden ? \"none\" : \"active\",\n ...(rows && rows.length ? { predicate: (query) => listCouldChange(query, rows) } : {}),\n });\n };\n let unsubscribe: (() => void) | undefined;\n try {\n unsubscribe = provider.subscribe(resource, latest.current.params, (event) => {\n if (!active) return;\n const test = latest.current.accept;\n if (test && event.type !== \"changed\" && !test(event)) return;\n if (event.type === \"updated\" && event.record) {\n patchCachedRow(queryClient, resource, event.record);\n burst?.push(event.record);\n } else {\n burst = null;\n }\n // Coalesce: one refetch per burst, after it goes quiet (or has\n // lasted `maxWaitMs`).\n const now = Date.now();\n if (timer === undefined) burstStart = now;\n else clearTimeout(timer);\n timer = setTimeout(fire, Math.min(debounceMs, Math.max(0, burstStart + maxWaitMs - now)));\n });\n } catch (error) {\n console.error(`[genesis] subscribing to \"${resource}\" failed:`, error);\n }\n // The safety net for changes realtime can't deliver; skipped while the page is hidden (a\n // hidden page refetches when it's shown again).\n const resync =\n resyncMs > 0\n ? setInterval(() => {\n if (!active) return;\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n void queryClient.invalidateQueries({ queryKey: [...latest.current.queryKey], refetchType: \"active\" });\n }, resyncMs)\n : undefined;\n return () => {\n active = false;\n if (resync !== undefined) clearInterval(resync);\n if (timer !== undefined) clearTimeout(timer);\n try {\n unsubscribe?.();\n } catch (error) {\n console.error(`[genesis] unsubscribing from \"${resource}\" failed:`, error);\n }\n };\n // `paramsKey` / `keyKey` stand for `params` / `queryKey` by value.\n }, [on, provider, queryClient, resource, debounceMs, resyncMs, paramsKey, keyKey]);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-live.ts"],"names":[],"mappings":";;;;;AA0BO,IAAM,wBAAA,GAA2B;AAOjC,IAAM,sBAAA,GAAyB;AAkBtC,IAAM,iBAAA,uBAAwB,OAAA,EAAgB;AAUvC,SAAS,oBACd,QAAA,EACA,IAAA,EACA,OAAA,EACA,MAAA,EACA,UACA,MAAA,EACM;AACN,EAAA,MAAM,WAAW,eAAA,EAAgB;AACjC,EAAA,MAAM,cAAc,cAAA,EAAe;AACnC,EAAA,MAAM,EAAA,GAAK,CAAC,CAAC,IAAA,IAAQ,OAAA;AACrB,EAAA,MAAM,aAAa,IAAA,CAAK,GAAA;AAAA,IACtB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,aAAa,MAAA,KAAc;AAAA,GAC9D;AACA,EAAA,MAAM,WAAW,IAAA,CAAK,GAAA;AAAA,IACpB,CAAA;AAAA,IAAA,CACC,OAAO,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,WAAW,MAAA,KAAc;AAAA,GAC5D;AACA,EAAA,MAAM,SAAA,GAAY,IAAA,CAAK,SAAA,CAAU,MAAM,CAAA;AACvC,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAItC,EAAA,MAAM,SAAS,MAAA,CAAO,EAAE,QAAA,EAAU,MAAA,EAAQ,QAAQ,CAAA;AAClD,EAAA,MAAA,CAAO,OAAA,GAAU,EAAE,QAAA,EAAU,MAAA,EAAQ,MAAA,EAAO;AAE5C,EAAA,SAAA,C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AAO,OAAA,CAAQ,QAAQ,CAAA,EAAG,WAAA,EAAa,QAAA,EAAU,CAAA;AAAA,IACtG,CAAA,EAAG,QAAQ,CAAA,GACX,MAAA;AACN,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,IAAI,MAAA,KAAW,MAAA,EAAW,aAAA,CAAc,MAAM,CAAA;AAC9C,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,KAAK,CAAA;AAC3C,MAAA,IAAI;AACF,QAAA,WAAA,IAAc;AAAA,MAChB,SAAS,KAAA,EAAO;AACd,QAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,8BAAA,EAAiC,QAAQ,CAAA,SAAA,CAAA,EAAa,KAAK,CAAA;AAAA,MAC3E;AAAA,IACF,CAAA;AAAA,EAEF,CAAA,EAAG,CAAC,EAAA,EAAI,QAAA,EAAU,WAAA,EAAa,UAAU,UAAA,EAAY,QAAA,EAAU,SAAA,EAAW,MAAM,CAAC,CAAA;AACnF","file":"chunk-K4ZNAF3G.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Live reads — refetch a resource's cached reads when the provider reports a\n// change (`DataProvider.subscribe`).\n//\n// Events are invalidation hints. When an update carries the row (the provider\n// sends one only for a resource read from its own table, under realtime's RLS),\n// the fields cached rows already have are patched at once; the refetch that\n// follows still goes through the provider's normal read, so what a user ends\n// up seeing is what that read (and its RLS) returns. Lists the change can't\n// have touched (its row matches none of their filters and isn't in them) are\n// left alone.\n//\n// Pending optimistic and undoable writes are safe: their patches are\n// re-applied to whatever a refetch brings (see mutation-mode.ts), so a row\n// deleted with undo stays hidden and an edit stays shown until the write\n// settles. The provider drops the echo of this client's own writes, which\n// already refresh through the write path.\n// ---------------------------------------------------------------------------\n\nimport { useEffect, useRef } from \"react\";\nimport { useQueryClient, type QueryKey } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { ResourceChangeEvent, SubscribeParams } from \"../provider/types\";\nimport { listCouldChange, patchCachedRow } from \"./live-cache\";\n\n/** How long a burst of change events is gathered into one refetch. */\nexport const DEFAULT_LIVE_DEBOUNCE_MS = 250;\n\n/**\n * How often a live read refetches anyway while the page is visible. Realtime checks each change\n * against the row's new state, so a row the viewer stops being allowed to see (binned, made a\n * draft, moved to another practice) sends them nothing and would stay on screen.\n */\nexport const DEFAULT_LIVE_RESYNC_MS = 60_000;\n\n/** `live` as an object, to tune it. `live: true` takes the defaults. */\nexport interface LiveOptions {\n /**\n * Events arriving within this many milliseconds of each other cause one\n * refetch, not one each. Default {@link DEFAULT_LIVE_DEBOUNCE_MS}. A\n * steady stream still refetches at least every `4 × debounceMs`.\n */\n debounceMs?: number;\n /**\n * Refetch at least this often while the page is visible, for the changes realtime can't\n * deliver (a row the viewer may no longer read). Default {@link DEFAULT_LIVE_RESYNC_MS}; 0 turns\n * it off.\n */\n resyncMs?: number;\n}\n\nconst warnedNoSubscribe = new WeakSet<object>();\n\n/**\n * Subscribes while mounted and `enabled`, and invalidates `queryKey` (a\n * prefix) once per burst of events that `accept` lets through. While the\n * page is hidden the queries are only marked stale; they refetch when it is\n * shown again (TanStack Query's `refetchOnWindowFocus`) or next used.\n *\n * @internal Used by `useResource` and `useOne`'s `live` option.\n */\nexport function useLiveInvalidation(\n resource: string,\n live: boolean | LiveOptions | undefined,\n enabled: boolean,\n params: SubscribeParams,\n queryKey: QueryKey,\n accept?: (event: ResourceChangeEvent) => boolean,\n): void {\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n const on = !!live && enabled;\n const debounceMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.debounceMs : undefined) ?? DEFAULT_LIVE_DEBOUNCE_MS,\n );\n const resyncMs = Math.max(\n 0,\n (typeof live === \"object\" ? live.resyncMs : undefined) ?? DEFAULT_LIVE_RESYNC_MS,\n );\n const paramsKey = JSON.stringify(params);\n const keyKey = JSON.stringify(queryKey);\n\n // The latest values, read when an event arrives, so a new array or\n // callback each render doesn't resubscribe.\n const latest = useRef({ queryKey, accept, params });\n latest.current = { queryKey, accept, params };\n\n useEffect(() => {\n if (!on) return;\n if (typeof provider.subscribe !== \"function\") {\n if (process.env.NODE_ENV !== \"production\" && !warnedNoSubscribe.has(provider)) {\n warnedNoSubscribe.add(provider);\n console.warn(\n `[genesis] \"${resource}\" asked for live updates, but the data provider has no subscribe(); the list will only refresh on its own reads.`,\n );\n }\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n let burstStart = 0;\n // The rows of this burst's updates; null once an event without one (a delete, an insert,\n // `changed`) means every read must refetch.\n let burst: Record<string, unknown>[] | null = [];\n let active = true;\n // A busy table must not postpone the refetch forever.\n const maxWaitMs = debounceMs * 4;\n const fire = () => {\n timer = undefined;\n if (!active) return;\n const hidden = typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n const rows = burst;\n burst = [];\n void queryClient.invalidateQueries({\n queryKey: [...latest.current.queryKey],\n refetchType: hidden ? \"none\" : \"active\",\n ...(rows && rows.length ? { predicate: (query) => listCouldChange(query, rows) } : {}),\n });\n };\n let unsubscribe: (() => void) | undefined;\n try {\n unsubscribe = provider.subscribe(resource, latest.current.params, (event) => {\n if (!active) return;\n const test = latest.current.accept;\n if (test && event.type !== \"changed\" && !test(event)) return;\n if (event.type === \"updated\" && event.record) {\n patchCachedRow(queryClient, resource, event.record);\n burst?.push(event.record);\n } else {\n burst = null;\n }\n // Coalesce: one refetch per burst, after it goes quiet (or has\n // lasted `maxWaitMs`).\n const now = Date.now();\n if (timer === undefined) burstStart = now;\n else clearTimeout(timer);\n timer = setTimeout(fire, Math.min(debounceMs, Math.max(0, burstStart + maxWaitMs - now)));\n });\n } catch (error) {\n console.error(`[genesis] subscribing to \"${resource}\" failed:`, error);\n }\n // The safety net for changes realtime can't deliver; skipped while the page is hidden (a\n // hidden page refetches when it's shown again).\n const resync =\n resyncMs > 0\n ? setInterval(() => {\n if (!active) return;\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") return;\n void queryClient.invalidateQueries({ queryKey: [...latest.current.queryKey], refetchType: \"active\" });\n }, resyncMs)\n : undefined;\n return () => {\n active = false;\n if (resync !== undefined) clearInterval(resync);\n if (timer !== undefined) clearTimeout(timer);\n try {\n unsubscribe?.();\n } catch (error) {\n console.error(`[genesis] unsubscribing from \"${resource}\" failed:`, error);\n }\n };\n // `paramsKey` / `keyKey` stand for `params` / `queryKey` by value.\n }, [on, provider, queryClient, resource, debounceMs, resyncMs, paramsKey, keyKey]);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resourceKeys } from './chunk-OYIUIW7C.js';
|
|
2
|
-
import { capabilitiesQueryKey } from './chunk-
|
|
2
|
+
import { capabilitiesQueryKey } from './chunk-LGTXQTHA.js';
|
|
3
3
|
|
|
4
4
|
// src/hooks/mutation-mode.ts
|
|
5
5
|
var DEFAULT_UNDO_DELAY_MS = 5e3;
|
|
@@ -576,5 +576,5 @@ async function executeWrite(args) {
|
|
|
576
576
|
}
|
|
577
577
|
|
|
578
578
|
export { DEFAULT_UNDO_DELAY_MS, DROPPED_WRITE_MESSAGE, cachedRecord, dropPendingWrites, executeWrite, flushPendingWrites, invalidateResource, pendingWriteCount, providerServesUndo, sameValue };
|
|
579
|
-
//# sourceMappingURL=chunk-
|
|
580
|
-
//# sourceMappingURL=chunk-
|
|
579
|
+
//# sourceMappingURL=chunk-K7WEY5WR.js.map
|
|
580
|
+
//# sourceMappingURL=chunk-K7WEY5WR.js.map
|