@marktiderman/genesis-core 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +3 -2
  2. package/dist/{aggregate-Y5IJ5aPn.d.ts → aggregate-v_r-nZbH.d.ts} +1 -1
  3. package/dist/{chunk-M5IX7C6U.js → chunk-24X4HWL5.js} +4 -4
  4. package/dist/{chunk-M5IX7C6U.js.map → chunk-24X4HWL5.js.map} +1 -1
  5. package/dist/chunk-2ORQLYVW.js +115 -0
  6. package/dist/chunk-2ORQLYVW.js.map +1 -0
  7. package/dist/{chunk-XPBS5YE4.js → chunk-4POVYF6P.js} +4 -4
  8. package/dist/{chunk-XPBS5YE4.js.map → chunk-4POVYF6P.js.map} +1 -1
  9. package/dist/{chunk-IYGVJFCV.js → chunk-5KLIFJYG.js} +3 -3
  10. package/dist/{chunk-IYGVJFCV.js.map → chunk-5KLIFJYG.js.map} +1 -1
  11. package/dist/{chunk-ALLWIK62.js → chunk-6B4CN2TC.js} +8 -6
  12. package/dist/chunk-6B4CN2TC.js.map +1 -0
  13. package/dist/chunk-6JOWGO2X.js +266 -0
  14. package/dist/chunk-6JOWGO2X.js.map +1 -0
  15. package/dist/{chunk-E3K2A3PK.js → chunk-6SHGMEA6.js} +3 -3
  16. package/dist/{chunk-E3K2A3PK.js.map → chunk-6SHGMEA6.js.map} +1 -1
  17. package/dist/chunk-6VNM6KAX.js +59 -0
  18. package/dist/chunk-6VNM6KAX.js.map +1 -0
  19. package/dist/{chunk-SOO54YYY.js → chunk-AQX5HQD6.js} +3 -3
  20. package/dist/{chunk-SOO54YYY.js.map → chunk-AQX5HQD6.js.map} +1 -1
  21. package/dist/chunk-BNKP2H7J.js +11 -0
  22. package/dist/chunk-BNKP2H7J.js.map +1 -0
  23. package/dist/{chunk-FXPODKCK.js → chunk-FBMKI22S.js} +6 -6
  24. package/dist/{chunk-FXPODKCK.js.map → chunk-FBMKI22S.js.map} +1 -1
  25. package/dist/{chunk-POUI7GAI.js → chunk-JF7FXSQB.js} +5 -5
  26. package/dist/{chunk-POUI7GAI.js.map → chunk-JF7FXSQB.js.map} +1 -1
  27. package/dist/chunk-JNWTHDGF.js +892 -0
  28. package/dist/chunk-JNWTHDGF.js.map +1 -0
  29. package/dist/chunk-K33LWVUF.js +31 -0
  30. package/dist/chunk-K33LWVUF.js.map +1 -0
  31. package/dist/chunk-KRRESUXT.js +192 -0
  32. package/dist/chunk-KRRESUXT.js.map +1 -0
  33. package/dist/{chunk-LB6FMQQM.js → chunk-KV2HW4G4.js} +3 -11
  34. package/dist/chunk-KV2HW4G4.js.map +1 -0
  35. package/dist/{chunk-42NVJJTT.js → chunk-MMMC37AP.js} +3 -3
  36. package/dist/{chunk-42NVJJTT.js.map → chunk-MMMC37AP.js.map} +1 -1
  37. package/dist/chunk-MZVFOTAE.js +96 -0
  38. package/dist/chunk-MZVFOTAE.js.map +1 -0
  39. package/dist/{chunk-R3YXYVWF.js → chunk-OIZNABG4.js} +5 -4
  40. package/dist/chunk-OIZNABG4.js.map +1 -0
  41. package/dist/{chunk-QGWQ6LK3.js → chunk-QJOKZZKY.js} +9 -6
  42. package/dist/chunk-QJOKZZKY.js.map +1 -0
  43. package/dist/chunk-TWLPC4S3.js +53 -0
  44. package/dist/chunk-TWLPC4S3.js.map +1 -0
  45. package/dist/{chunk-7EFTWOMA.js → chunk-UNEZF3ZP.js} +73 -15
  46. package/dist/chunk-UNEZF3ZP.js.map +1 -0
  47. package/dist/chunk-WNOCPV4A.js +220 -0
  48. package/dist/chunk-WNOCPV4A.js.map +1 -0
  49. package/dist/{chunk-ZYOJWU62.js → chunk-XIBQ5BTZ.js} +12 -53
  50. package/dist/chunk-XIBQ5BTZ.js.map +1 -0
  51. package/dist/chunk-YMFJLBIZ.js +159 -0
  52. package/dist/chunk-YMFJLBIZ.js.map +1 -0
  53. package/dist/{chunk-UDSTWXXZ.js → chunk-ZKLB2HB5.js} +3 -3
  54. package/dist/{chunk-UDSTWXXZ.js.map → chunk-ZKLB2HB5.js.map} +1 -1
  55. package/dist/csv.d.ts +12 -3
  56. package/dist/csv.js +4 -4
  57. package/dist/csv.js.map +1 -1
  58. package/dist/form-types.d.ts +1 -1
  59. package/dist/headless/index.d.ts +1 -1
  60. package/dist/hooks/index.d.ts +16 -6
  61. package/dist/hooks/index.js +27 -15
  62. package/dist/hooks/mutation-mode.d.ts +1 -1
  63. package/dist/hooks/mutation-mode.js +3 -3
  64. package/dist/hooks/related-keys.d.ts +1 -1
  65. package/dist/hooks/use-aggregate.d.ts +2 -2
  66. package/dist/hooks/use-aggregate.js +3 -3
  67. package/dist/hooks/use-board-columns.d.ts +79 -0
  68. package/dist/hooks/use-board-columns.js +4 -0
  69. package/dist/hooks/use-board-columns.js.map +1 -0
  70. package/dist/hooks/use-capabilities.d.ts +1 -1
  71. package/dist/hooks/use-capabilities.js +2 -2
  72. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  73. package/dist/hooks/use-infinite-resource.js +3 -3
  74. package/dist/hooks/use-link-options.d.ts +1 -1
  75. package/dist/hooks/use-link-options.js +5 -5
  76. package/dist/hooks/use-list-state.d.ts +103 -0
  77. package/dist/hooks/use-list-state.js +21 -0
  78. package/dist/hooks/use-list-state.js.map +1 -0
  79. package/dist/hooks/use-live.d.ts +1 -1
  80. package/dist/hooks/use-live.js +2 -2
  81. package/dist/hooks/use-one.d.ts +7 -1
  82. package/dist/hooks/use-one.js +3 -3
  83. package/dist/hooks/use-persisted-ui-state.js +2 -2
  84. package/dist/hooks/use-relation-label.d.ts +1 -1
  85. package/dist/hooks/use-relation-label.js +2 -2
  86. package/dist/hooks/use-resource-form.d.ts +1 -1
  87. package/dist/hooks/use-resource-form.js +7 -7
  88. package/dist/hooks/use-resource.d.ts +7 -1
  89. package/dist/hooks/use-resource.js +5 -5
  90. package/dist/hooks/use-segment-counts.d.ts +23 -0
  91. package/dist/hooks/use-segment-counts.js +19 -0
  92. package/dist/hooks/use-segment-counts.js.map +1 -0
  93. package/dist/hooks/use-view-board.d.ts +120 -0
  94. package/dist/hooks/use-view-board.js +29 -0
  95. package/dist/hooks/use-view-board.js.map +1 -0
  96. package/dist/hooks/use-view-calendar-range.d.ts +91 -0
  97. package/dist/hooks/use-view-calendar-range.js +22 -0
  98. package/dist/hooks/use-view-calendar-range.js.map +1 -0
  99. package/dist/hooks/use-write.d.ts +1 -1
  100. package/dist/index.d.ts +41 -11
  101. package/dist/index.js +119 -26
  102. package/dist/index.js.map +1 -1
  103. package/dist/provider/index.d.ts +61 -8
  104. package/dist/provider/index.js +2 -2
  105. package/dist/resource-view/index.d.ts +162 -757
  106. package/dist/resource-view/index.js +31 -686
  107. package/dist/resource-view/index.js.map +1 -1
  108. package/dist/saved-views-C45lRm7i.d.ts +155 -0
  109. package/dist/schema/index.d.ts +3 -3
  110. package/dist/schema/index.js +2 -1
  111. package/dist/testing/index.d.ts +2 -2
  112. package/dist/types-BAhcze_-.d.ts +1063 -0
  113. package/dist/{types-BriIV4e_.d.ts → types-CiQY6hUy.d.ts} +11 -1
  114. package/dist/{viewer-scope-Dx0N9AYk.d.ts → viewer-oOk0ZZk9.d.ts} +36 -34
  115. package/dist/{workspaces-CxpiFu2-.d.ts → workspaces-DeaFix5Z.d.ts} +1 -1
  116. package/dist/workspaces.d.ts +2 -2
  117. package/dist/{write-outcome-CkQXgtJq.d.ts → write-outcome-DuwfsnyO.d.ts} +1 -1
  118. package/package.json +11 -1
  119. package/dist/chunk-7EFTWOMA.js.map +0 -1
  120. package/dist/chunk-ALLWIK62.js.map +0 -1
  121. package/dist/chunk-LB6FMQQM.js.map +0 -1
  122. package/dist/chunk-QGWQ6LK3.js.map +0 -1
  123. package/dist/chunk-R3YXYVWF.js.map +0 -1
  124. package/dist/chunk-ZYOJWU62.js.map +0 -1
@@ -0,0 +1,53 @@
1
+ import { ViewerScope } from './chunk-XIBQ5BTZ.js';
2
+ import { workspaceAt, workspaceHref } from './chunk-APFXV6FZ.js';
3
+ import { createContext, useContext, useMemo, useEffect } from 'react';
4
+ import { jsx } from 'react/jsx-runtime';
5
+
6
+ var WorkspaceContextValue = createContext(null);
7
+ function useWorkspace() {
8
+ return useContext(WorkspaceContextValue);
9
+ }
10
+ var STORAGE_PREFIX = "genesis:workspace:";
11
+ function rememberedWorkspaceId(viewer) {
12
+ if (!viewer || typeof window === "undefined") return null;
13
+ try {
14
+ return window.localStorage.getItem(STORAGE_PREFIX + viewer);
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ function remember(viewer, id) {
20
+ try {
21
+ window.localStorage.setItem(STORAGE_PREFIX + viewer, id);
22
+ } catch {
23
+ }
24
+ }
25
+ function WorkspaceScope({ workspaces, pathname, scope, keep, children, ...viewerProps }) {
26
+ const current = workspaceAt(workspaces, pathname);
27
+ const value = useMemo(
28
+ () => ({
29
+ current,
30
+ workspaces,
31
+ hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {})
32
+ }),
33
+ [current, workspaces, pathname, keep]
34
+ );
35
+ const viewer = viewerProps.viewer;
36
+ useEffect(() => {
37
+ if (viewer && current) remember(viewer, current.id);
38
+ }, [viewer, current]);
39
+ return /* @__PURE__ */ jsx(WorkspaceContextValue.Provider, { value, children: /* @__PURE__ */ jsx(
40
+ ViewerScope,
41
+ {
42
+ ...viewerProps,
43
+ scope: { ...scope, ...current?.scope },
44
+ ...current?.roles !== void 0 ? { roles: current.roles } : {},
45
+ ...current?.timeZone !== void 0 ? { scopeTimeZone: current.timeZone } : {},
46
+ children
47
+ }
48
+ ) });
49
+ }
50
+
51
+ export { WorkspaceScope, rememberedWorkspaceId, useWorkspace };
52
+ //# sourceMappingURL=chunk-TWLPC4S3.js.map
53
+ //# sourceMappingURL=chunk-TWLPC4S3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/workspace-scope.tsx"],"names":[],"mappings":";;;;;AAiBA,IAAM,qBAAA,GAAwB,cAAuC,IAAI,CAAA;AAOlE,S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A,EAAG,CAAC,MAAA,EAAQ,OAAO,CAAC,CAAA;AACpB,EAAA,uBACE,GAAA,CAAC,qBAAA,CAAsB,QAAA,EAAtB,EAA+B,KAAA,EAC9B,QAAA,kBAAA,GAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-TWLPC4S3.js","sourcesContent":["import { createContext, useContext, useEffect, useMemo } from \"react\";\nimport { ViewerScope, type ViewerScopeProps } from \"./viewer-scope\";\nimport { workspaceAt, workspaceHref, type Workspace, type WorkspaceHrefOptions } from \"../workspaces\";\n\n/**\n * The workspace the viewer is in, and where each of their others is from here.\n *\n * @stability Beta\n */\nexport interface WorkspaceContext<W extends Workspace = Workspace> {\n /** Undefined when the URL is in no workspace (the app's front door, a sign-in page). */\n current: W | undefined;\n workspaces: readonly W[];\n /** Where switching to `to` goes from the current URL, keeping the viewer's place when it can. */\n hrefFor: (to: W) => string;\n}\n\nconst WorkspaceContextValue = createContext<WorkspaceContext | null>(null);\n\n/**\n * The nearest `WorkspaceScope`'s workspaces, or null outside one.\n *\n * @stability Beta\n */\nexport function useWorkspace<W extends Workspace = Workspace>(): WorkspaceContext<W> | null {\n return useContext(WorkspaceContextValue) as WorkspaceContext<W> | null;\n}\n\nconst STORAGE_PREFIX = \"genesis:workspace:\";\n\n/**\n * The workspace this viewer was last in on this device, for the app's front door\n * (`defaultWorkspace(workspaces, rememberedWorkspaceId(viewer))`). Null when unknown.\n *\n * @stability Beta\n */\nexport function rememberedWorkspaceId(viewer: string | null | undefined): string | null {\n if (!viewer || typeof window === \"undefined\") return null;\n try {\n return window.localStorage.getItem(STORAGE_PREFIX + viewer);\n } catch {\n return null;\n }\n}\n\nfunction remember(viewer: string, id: string) {\n try {\n window.localStorage.setItem(STORAGE_PREFIX + viewer, id);\n } catch {\n // private mode or full: the front door falls back to the first tenant.\n }\n}\n\n/** @stability Beta */\nexport interface WorkspaceScopeProps<W extends Workspace = Workspace> extends Omit<ViewerScopeProps, \"scope\" | \"roles\" | \"scopeTimeZone\"> {\n /** Every workspace this viewer has. */\n workspaces: readonly W[];\n /** The current URL's path (`useLocation().pathname`): the workspace is read from it. */\n pathname: string;\n /** Scope keys every workspace adds to its own (rarely needed). */\n scope?: ViewerScopeProps[\"scope\"];\n /** How switching keeps the viewer's place (see `workspaceHref`). */\n keep?: WorkspaceHrefOptions[\"keep\"];\n}\n\n/**\n * `ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current\n * workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and\n * `timeZone`), so every view with `scope: [\"org_id\"]` follows the switcher with no screen code. It\n * remembers the workspace per viewer on this device, and gives `WorkspaceSwitcher` its list.\n *\n * ```tsx\n * <WorkspaceScope viewer={userId} workspaces={workspaces} pathname={location.pathname}>\n * <AppShell headerSlot={<WorkspaceSwitcher linkComponent={Link} />} …>\n * </WorkspaceScope>\n * ```\n *\n * @stability Beta\n */\nexport function WorkspaceScope<W extends Workspace>({ workspaces, pathname, scope, keep, children, ...viewerProps }: WorkspaceScopeProps<W>) {\n const current = workspaceAt(workspaces, pathname);\n const value = useMemo<WorkspaceContext<W>>(\n () => ({\n current,\n workspaces,\n hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {}),\n }),\n [current, workspaces, pathname, keep],\n );\n const viewer = viewerProps.viewer;\n useEffect(() => {\n if (viewer && current) remember(viewer, current.id);\n }, [viewer, current]);\n return (\n <WorkspaceContextValue.Provider value={value as unknown as WorkspaceContext}>\n <ViewerScope\n {...viewerProps}\n scope={{ ...scope, ...current?.scope }}\n {...(current?.roles !== undefined ? { roles: current.roles } : {})}\n {...(current?.timeZone !== undefined ? { scopeTimeZone: current.timeZone } : {})}\n >\n {children}\n </ViewerScope>\n </WorkspaceContextValue.Provider>\n );\n}\n\n"]}
@@ -252,7 +252,7 @@ function createSupabaseProvider(client, options = {}) {
252
252
  if (!row) return values;
253
253
  return Object.fromEntries(Object.entries(values).filter(([key]) => key in row));
254
254
  }
255
- function read(resource, columns, count) {
255
+ function read(resource, columns, count, filters, used = /* @__PURE__ */ new Set()) {
256
256
  const config = configFor(resource);
257
257
  const cols = columns ?? config.select ?? "*";
258
258
  const source = config.source;
@@ -260,12 +260,64 @@ function createSupabaseProvider(client, options = {}) {
260
260
  if (!client.rpc) {
261
261
  throw new DataReadError("error", `[SupabaseProvider] "${resource}" reads from ${source.rpc}(), but the client has no rpc.`);
262
262
  }
263
- const builder = client.rpc(source.rpc, source.args?.() ?? {}, count ? { count } : void 0);
263
+ const builder = client.rpc(source.rpc, source.args?.(sourceArgs(resource, filters, used)) ?? {}, count ? { count } : void 0);
264
264
  return builder.select(cols);
265
265
  }
266
266
  const table = relation(source ?? resource);
267
267
  return count ? table.select(cols, { count }) : table.select(cols);
268
268
  }
269
+ function sourceArgs(resource, filters, used) {
270
+ const list = filters ?? [];
271
+ return {
272
+ resource,
273
+ filters: list,
274
+ take: (field) => {
275
+ const f = list.find((x) => x.field === field && (x.operator === "eq" || x.operator === "is_null"));
276
+ if (!f) return void 0;
277
+ used.add(f);
278
+ return f.operator === "eq" ? f.value : null;
279
+ },
280
+ takeIn: (field) => {
281
+ const f = list.find((x) => x.field === field && (x.operator === "in" || x.operator === "eq") && !used.has(x));
282
+ if (!f) return void 0;
283
+ used.add(f);
284
+ const value = f.value;
285
+ return f.operator === "in" ? [...value] : [value];
286
+ }
287
+ };
288
+ }
289
+ function readFiltered(resource, columns, count, filters) {
290
+ const used = /* @__PURE__ */ new Set();
291
+ const query = read(resource, columns, count, filters, used);
292
+ return applyFilters(query, used.size ? filters.filter((f) => !used.has(f)) : filters);
293
+ }
294
+ async function readSourcePage(resource, params, offset, limit) {
295
+ const source = configFor(resource).source;
296
+ if (!source || typeof source !== "object" || !source.pages || !client.rpc) return void 0;
297
+ if (searchClauses(resource, params)) return void 0;
298
+ const order = source.pages.order ?? [];
299
+ const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];
300
+ if (requested.length > 0 && (requested.length > order.length || requested.some((r, k) => r.field !== order[k].field || r.order !== order[k].order))) {
301
+ return void 0;
302
+ }
303
+ const used = /* @__PURE__ */ new Set();
304
+ const args = source.args?.(sourceArgs(resource, params.filters, used)) ?? {};
305
+ if ((params.filters ?? []).some((f) => !used.has(f))) return void 0;
306
+ const totalColumn = source.pages.total ?? "total_count";
307
+ const cols = params.select ?? configFor(resource).select ?? "*";
308
+ const select = cols.trim() === "*" ? cols : `${cols},${totalColumn}`;
309
+ const call = async (from2, take) => {
310
+ const builder = client.rpc(source.rpc, { ...args, page_limit: take, page_offset: from2 });
311
+ const result = await builder.select(select);
312
+ await throwIfReadError(result, resource, "getList");
313
+ return result.data ?? [];
314
+ };
315
+ const totalOf = (rows) => Number(rows[0]?.[totalColumn] ?? 0);
316
+ if (limit === 0) return { data: [], total: totalOf(await call(0, 0)) };
317
+ const data = await call(offset, limit);
318
+ const total = data.length > 0 || offset === 0 ? totalOf(data) : totalOf(await call(0, 0));
319
+ return { data, total };
320
+ }
269
321
  const configFor = (resource) => options.resources?.[resource] ?? options.resources?.[otherSpelling(resource)] ?? {};
270
322
  const nounFor = (resource) => configFor(resource).noun ?? "record";
271
323
  const recentWrites = /* @__PURE__ */ new Map();
@@ -450,8 +502,7 @@ function createSupabaseProvider(client, options = {}) {
450
502
  }
451
503
  }
452
504
  const mode = countMode(resource, params);
453
- let query = read(resource, params.select, cursor || mode === "none" ? void 0 : mode);
454
- query = applyFilters(query, params.filters);
505
+ let query = readFiltered(resource, params.select, cursor || mode === "none" ? void 0 : mode, params.filters);
455
506
  const search = searchClauses(resource, params);
456
507
  const keyset = after ? keysetClauses(after) : "";
457
508
  if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);
@@ -521,9 +572,13 @@ function createSupabaseProvider(client, options = {}) {
521
572
  return getCursorPage(resource, params, configuredKey === void 0 ? "id" : configuredKey);
522
573
  }
523
574
  const mode = countMode(resource, params);
575
+ if (params.pagination) {
576
+ const { page, perPage } = params.pagination;
577
+ const paged = await readSourcePage(resource, params, (page - 1) * perPage, perPage);
578
+ if (paged) return { data: paged.data, total: mode === "none" ? -1 : paged.total };
579
+ }
524
580
  const run2 = (key) => {
525
- let query = read(resource, params.select, mode === "none" ? void 0 : mode);
526
- query = applyFilters(query, params.filters);
581
+ let query = readFiltered(resource, params.select, mode === "none" ? void 0 : mode, params.filters);
527
582
  const clauses = searchClauses(resource, params);
528
583
  if (clauses) {
529
584
  query = query.or(clauses);
@@ -578,14 +633,17 @@ function createSupabaseProvider(client, options = {}) {
578
633
  resource,
579
634
  "getList"
580
635
  );
581
- const narrow = (query) => {
582
- query = applyFilters(query, params.filters);
636
+ const narrow = (columns, count) => {
637
+ const query = readFiltered(resource, columns, count, params.filters);
583
638
  const clauses = searchClauses(resource, { search: params.search });
584
639
  return clauses ? query.or(clauses) : query;
585
640
  };
586
- if (counts.length > 0) {
641
+ const pagedTotal = counts.length > 0 ? await readSourcePage(resource, { filters: params.filters, search: params.search }, 0, 0) : void 0;
642
+ if (pagedTotal) {
643
+ for (const [name] of counts) values[name] = pagedTotal.total;
644
+ } else if (counts.length > 0) {
587
645
  const mode = params.count ?? "exact";
588
- const result = await narrow(read(resource, "*", mode)).range(0, 0);
646
+ const result = await narrow("*", mode).range(0, 0);
589
647
  await throwIfReadError(result, resource, "getList");
590
648
  for (const [name] of counts) values[name] = result.count ?? 0;
591
649
  isEstimate = mode !== "exact";
@@ -596,7 +654,7 @@ function createSupabaseProvider(client, options = {}) {
596
654
  if (!SAFE.test(name) || !("field" in m) || !SAFE.test(m.field)) await refuse(`"${name}" and its field must be plain column names.`);
597
655
  }
598
656
  const cols = others.map(([name, m]) => `${name}:${m.field}.${m.fn}()`).join(",");
599
- const result = await narrow(read(resource, cols));
657
+ const result = await narrow(cols);
600
658
  await throwIfReadError(result, resource, "getList");
601
659
  const row = result.data?.[0] ?? {};
602
660
  for (const [name] of others) {
@@ -618,13 +676,13 @@ function createSupabaseProvider(client, options = {}) {
618
676
  return isEstimate ? { values, isEstimate } : { values };
619
677
  },
620
678
  async getOne(resource, params) {
621
- const result = await read(resource, params.select).eq("id", params.id).single();
679
+ const result = await read(resource, params.select, void 0, params.scope).eq("id", params.id).single();
622
680
  await throwIfReadError(result, resource, "getOne");
623
681
  return { data: result.data };
624
682
  },
625
683
  async getMany(resource, params) {
626
684
  if (params.ids.length === 0) return { data: [] };
627
- const result = await read(resource, void 0).in("id", params.ids);
685
+ const result = await read(resource, void 0, void 0, params.scope).in("id", params.ids);
628
686
  await throwIfReadError(result, resource, "getMany");
629
687
  return { data: result.data ?? [] };
630
688
  },
@@ -940,5 +998,5 @@ async function createOrAdopt(provider, resource, data, options) {
940
998
  }
941
999
 
942
1000
  export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider };
943
- //# sourceMappingURL=chunk-7EFTWOMA.js.map
944
- //# sourceMappingURL=chunk-7EFTWOMA.js.map
1001
+ //# sourceMappingURL=chunk-UNEZF3ZP.js.map
1002
+ //# sourceMappingURL=chunk-UNEZF3ZP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provider/supabase-provider.ts","../src/provider/write-helpers.ts"],"names":["from","run"],"mappings":";;;;;;AAgYA,SAAS,eAAA,CAAgB,KAAA,EAAgB,KAAA,EAAe,MAAA,EAAyB;AAC/E,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AAChD,EAAA,MAA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AAA;AAC7B,IAAA,MAAM,QAAA,GAAW,KAAK,CAAC,CAAA;AACvB,IAAA,IAAI,OAAA,CAAQ,KAAA,GAAQ,QAAQ,CAAA,EAAG,OAAO,EAAE,GAAA,EAAK,QAAA,EAAU,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-UNEZF3ZP.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\";\nimport { reportError } from \"../errors\";\nimport { resolveAggregate } from \"./aggregate\";\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 /** Another schema's tables, for a resource named `schema.table` outside `public`. */\n schema?(name: string): { 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 /** Another schema's tables, for a resource named `schema.table` outside `public`. Any real client's `schema` fits. */\n schema?(name: string): { 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/** What an `update` override is told besides the row. */\nexport interface SupabaseUpdateContext {\n /**\n * With a `version` rule and an `expectedVersion` from the caller: the\n * version the row must still be at. The override must apply the change\n * only at that version (e.g. `... where id = $1 and version = $2`) and\n * return nothing when no row matched; the provider then tells a\n * `conflict` from `forbidden` and `gone`.\n */\n expectedVersion?: string;\n}\n\n/**\n * A function source that pages itself (`SupabaseResourceConfig.source`'s `pages`): the order its\n * rows come in, and the column that carries the whole result's count. A count alone asks the\n * function for `page_limit: 0`, which it answers with one row that carries the count (and builds\n * no other row).\n *\n * @stability Beta\n */\nexport interface SourcePages {\n readonly order?: readonly { field: string; order: \"asc\" | \"desc\" }[];\n readonly total?: string;\n}\n\n/** Per-resource rules for `createSupabaseProvider`. Every field is optional. */\n/**\n * What a function source's `args` gets (`SupabaseResourceConfig.source`): the list's filters,\n * which carry the viewer's scope, and `take`, which reads one equality filter's value (`null` for\n * \"is empty\") and keeps that filter out of the query.\n *\n * @stability Beta\n */\nexport interface SourceArgsContext {\n readonly resource: string;\n readonly filters: readonly FilterParam[];\n take(field: string): string | number | boolean | null | undefined;\n /**\n * The values of a filter on `field` that an `in` (or an `eq`, as one value) gives, taken out of\n * the query like `take`; undefined when there's none. For a function that filters by a list.\n */\n takeIn(field: string): readonly unknown[] | undefined;\n}\n\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 context?: SupabaseUpdateContext,\n ) => Promise<BaseRecord | Identifier | boolean | null | undefined | void>;\n /**\n * The column every update and delete of this resource is checked against,\n * so an edit made on a stale copy is refused as a `conflict` instead of\n * overwriting someone else's (`UpdateParams.expectedVersion`).\n *\n * The database must advance it on every update, or it detects nothing:\n * `integer` with genesis-supabase's `genesis_version_bump` trigger\n * (migration 0019), or `timestamp` with a trigger that sets it to `now()`\n * on update (`moddatetime`). The provider never writes it: a submitted\n * value is dropped. Writes without an `expectedVersion` are not checked,\n * so turning this on changes nothing for callers that don't send one.\n */\n version?: { field: string; kind: \"integer\" | \"timestamp\" };\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: ({ take }) => ({ group_id: take(\"group_id\") }) } },\n * }\n * ```\n *\n * A function's `args` gets the list's filters (`context.filters`), which hold the viewer's scope\n * as ResourceView applies it (a view's `scope: [\"group_id\"]` filters `group_id`), so a function\n * that takes its scope as an argument reads it there rather than from a module variable.\n * `context.take(field)` returns an equality filter's value and leaves that filter out of the\n * query, for a scope the function takes as an argument and doesn't return as a column. A record\n * read (`getOne`, `getMany`) gets the list's filters from `scope` (less a text search's\n * `contains`, which `useOne` leaves out) when the caller passes them\n * (`useOne`'s `scope`, which ResourceView's table, inbox and NativeResourceView's peek and\n * edit sheet pass for a record off the loaded page), else none, and\n * the function's own default scope applies.\n *\n * A function that pages itself declares `pages`: it takes `page_limit` and `page_offset`\n * arguments, returns its rows in `pages.order` (newest first, say) and carries the whole\n * result's count on each row (`pages.total`, default `total_count`). A list page whose filters\n * the function all took, with no search and no sort other than `pages.order`, then passes the\n * page to the function instead of a `range`, and reads its total from that column, so the\n * function never builds rows outside the page. A count alone (a segment's) sends\n * `page_limit: 0`: the function returns one row carrying the count, and builds no other. Any other list reads every row, as without\n * `pages`, since PostgREST can only filter, search or sort what the function returned.\n */\n source?: string | { rpc: string; args?: (context: SourceArgsContext) => Record<string, unknown>; pages?: SourcePages };\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`. A list matches a `public` table under\n * either spelling; a test is asked once, with the name as the caller gives it.\n */\n binTables?: readonly string[] | ((resource: string) => boolean);\n /**\n * Per-resource rules, keyed by resource name. A `public` resource may be keyed either way\n * (`goals` or `public.goals`). The key spelled exactly as the caller names the resource wins;\n * the other spelling is used only when that key is absent. Rules are never merged.\n */\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). A list matches a `public` resource\n * under either spelling; a test is asked once, with the name as the caller\n * gives it.\n */\n realtime?: boolean | readonly string[] | ((resource: string) => boolean);\n /**\n * Work out `sum`, `avg`, `min` and `max` in the database with PostgREST's aggregate functions\n * (`amount.sum()`), which a project turns on with `pgrst.db_aggregates_enabled`. Off by\n * default: `aggregate` then counts in the database and totals the other metrics from the\n * rows, paged (`resolveAggregate`, up to 10 000 rows). A count is always the database's.\n */\n aggregateFunctions?: 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 /** Where empty values go, when the sort said (`SortParam.nulls`). */\n n?: \"first\" | \"last\";\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 /** Where the one sort column's empty values go, when the sort said. */\n n?: \"first\" | \"last\";\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.n !== undefined && state.n !== \"first\" && state.n !== \"last\") 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\") && (col.n === undefined || col.n === \"first\" || col.n === \"last\"))) 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, ...(state.n ? { n: state.n } : {}), 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 */\n/** A sort as `.order()`'s options: unset `nulls` stays unset, so the store's default holds. */\nfunction orderOptions({ order, nulls }: SortParam): { ascending: boolean; nullsFirst?: boolean } {\n return { ascending: order === \"asc\", ...(nulls ? { nullsFirst: nulls === \"first\" } : {}) };\n}\n\n/** Empty values last: what the sort says, else Postgres's own default for its order. */\nfunction nullsGoLast(order: \"asc\" | \"desc\", nulls: \"first\" | \"last\" | undefined): boolean {\n return nulls ? nulls === \"last\" : order === \"asc\";\n}\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)) {\n columns.push({ field: sort.field, order: sort.order ?? \"asc\", ...(sort.nulls ? { nulls: sort.nulls } : {}) });\n }\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 (empty values\n * where the sort put them; unset, last when ascending and first when\n * descending, as Postgres orders them by 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, n, v } of cols) {\n // Nulls placed last are ahead of every value; going back mirrors which side is \"ahead\".\n const nullsAhead = nullsGoLast(o, n) !== 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/**\n * `\"schema.table\"` or `\"table\"` (schema `public`): the name a generated\n * contract gives a resource, split the way PostgREST and Realtime name it.\n */\nexport function splitRelation(resource: string): { schema: string; table: string } {\n const dot = schemaDot(resource);\n return dot < 0\n ? { schema: \"public\", table: unquote(resource) }\n : { schema: unquote(resource.slice(0, dot)), table: unquote(resource.slice(dot + 1)) };\n}\n\n/** Where the schema ends: the first dot outside double quotes (`\"my.s\".\"we.ird\"`), or -1. */\nfunction schemaDot(resource: string): number {\n let quoted = false;\n for (let i = 0; i < resource.length; i++) {\n const c = resource[i];\n if (c === '\"') quoted = !quoted;\n else if (c === \".\" && !quoted) return i;\n }\n return -1;\n}\n\n/** A name part without its quotes: `\"we.ird\"` → `we.ird`, `\"a\"\"b\"` → `a\"b`. */\nfunction unquote(part: string): string {\n return part.length >= 2 && part.startsWith('\"') && part.endsWith('\"') ? part.slice(1, -1).replace(/\"\"/g, '\"') : part.replace(/\"/g, \"\");\n}\n\n/** A name part as a resource name spells it: quoted when it holds a dot or a quote. */\nfunction quotePart(part: string): string {\n return /[.\"]/.test(part) ? `\"${part.replace(/\"/g, '\"\"')}\"` : part;\n}\n\n/** The same `public` resource named the other way: `public.goals` ↔ `goals`; other schemas have one spelling. */\nfunction otherSpelling(resource: string): string {\n const { schema, table } = splitRelation(resource);\n if (schema !== \"public\") return resource;\n return schemaDot(resource) < 0 ? `public.${quotePart(table)}` : quotePart(table);\n}\n\n/** Every spelling of a resource, for a list given either: a `public` one bare first, then qualified. */\nfunction spellings(resource: string): string[] {\n const { schema } = splitRelation(resource);\n if (schema !== \"public\") return [resource];\n const other = otherSpelling(resource);\n return schemaDot(resource) < 0 ? [resource, other] : [other, resource];\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>();\nconst warnedUncheckedOverride = new Set<string>();\n\n/**\n * A Postgres or ISO timestamp as microseconds since the epoch (a string, to keep every digit), or\n * undefined when it doesn't read as one. Date.parse alone stops at milliseconds.\n */\nfunction instant(text: string): string | undefined {\n const m = /^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2}:\\d{2})(?:\\.(\\d+))?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/.exec(text.trim());\n if (!m) return undefined;\n const [, date, time, fraction = \"\", zone = \"Z\"] = m;\n const offset = zone === \"Z\" ? \"Z\" : zone.length === 3 ? `${zone}:00` : zone.includes(\":\") ? zone : `${zone.slice(0, 3)}:${zone.slice(3)}`;\n const ms = Date.parse(`${date}T${time}${offset}`);\n if (Number.isNaN(ms)) return undefined;\n return `${ms / 1000}.${fraction.padEnd(6, \"0\").slice(0, 6)}`;\n}\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 /** The table or view `name` names, in its schema: `public` through `from(table)`, any other through `schema(s).from(table)`. */\n function relation(name: string): SupabaseQueryBuilder {\n const { schema, table } = splitRelation(name);\n if (schema === \"public\") return client.from(table) as SupabaseQueryBuilder;\n // A client without schema() (not supabase-js) gets the name as given, as before.\n if (typeof client.schema !== \"function\") return client.from(name) as SupabaseQueryBuilder;\n return client.schema(schema).from(table) as SupabaseQueryBuilder;\n }\n\n const from = (resource: string) => relation(resource);\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 filters?: FilterParam[],\n used: Set<FilterParam> = new Set(),\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?.(sourceArgs(resource, filters, used)) ?? {}, count ? { count } : undefined) as SupabaseQueryBuilder;\n return builder.select(cols);\n }\n const table = relation(source ?? resource);\n return count ? table.select(cols, { count }) : table.select(cols);\n }\n\n // The filters a function's `args` took (`take`) land in `used`, which belongs to one read: a\n // later read that passes the same array (a table read, another function) starts from none taken.\n function sourceArgs(resource: string, filters: FilterParam[] | undefined, used: Set<FilterParam>): SourceArgsContext {\n const list = filters ?? [];\n return {\n resource,\n filters: list,\n take: (field: string) => {\n const f = list.find((x) => x.field === field && (x.operator === \"eq\" || x.operator === \"is_null\"));\n if (!f) return undefined;\n used.add(f);\n return f.operator === \"eq\" ? f.value : null;\n },\n takeIn: (field: string) => {\n const f = list.find((x) => x.field === field && (x.operator === \"in\" || x.operator === \"eq\") && !used.has(x));\n if (!f) return undefined;\n used.add(f);\n const value = (f as { value?: unknown }).value;\n return f.operator === \"in\" ? [...(value as unknown[])] : [value];\n },\n };\n }\n\n /** A read with the list's filters: a function source sees them first, and the ones it took aren't applied again. */\n function readFiltered(\n resource: string,\n columns: string | undefined,\n count: \"exact\" | \"estimated\" | \"planned\" | undefined,\n filters: FilterParam[] | undefined,\n ): SupabaseQueryBuilder {\n const used = new Set<FilterParam>();\n const query = read(resource, columns, count, filters, used);\n return applyFilters(query, used.size ? filters!.filter((f) => !used.has(f)) : filters);\n }\n /**\n * A page read by a function that pages itself (`source.pages`), or undefined when this list can't\n * be: a filter the function didn't take, a search or another sort would apply after the function,\n * so it has to return every row. `limit` 0 reads only the total (the one row the function answers with).\n */\n async function readSourcePage(\n resource: string,\n params: ListParams,\n offset: number,\n limit: number,\n ): Promise<{ data: Record<string, unknown>[]; total: number } | undefined> {\n const source = configFor(resource).source;\n if (!source || typeof source !== \"object\" || !source.pages || !client.rpc) return undefined;\n if (searchClauses(resource, params)) return undefined;\n const order = source.pages.order ?? [];\n const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (requested.length > 0 && (requested.length > order.length || requested.some((r, k) => r.field !== order[k]!.field || r.order !== order[k]!.order))) {\n return undefined;\n }\n const used = new Set<FilterParam>();\n const args = source.args?.(sourceArgs(resource, params.filters, used)) ?? {};\n if ((params.filters ?? []).some((f) => !used.has(f))) return undefined;\n const totalColumn = source.pages.total ?? \"total_count\";\n const cols = params.select ?? configFor(resource).select ?? \"*\";\n const select = cols.trim() === \"*\" ? cols : `${cols},${totalColumn}`;\n const call = async (from: number, take: number) => {\n const builder = client.rpc!(source.rpc, { ...args, page_limit: take, page_offset: from }) as SupabaseQueryBuilder;\n const result = (await builder.select(select)) as unknown as { data: Record<string, unknown>[] | null; error: unknown };\n await throwIfReadError(result, resource, \"getList\");\n return result.data ?? [];\n };\n const totalOf = (rows: Record<string, unknown>[]) => Number(rows[0]?.[totalColumn] ?? 0);\n // A count alone (limit 0): the function's one row carries it, and no row is data.\n if (limit === 0) return { data: [], total: totalOf(await call(0, 0)) };\n const data = await call(offset, limit);\n // A page past the end has no row to carry the total: ask for the count alone.\n const total = data.length > 0 || offset === 0 ? totalOf(data) : totalOf(await call(0, 0));\n return { data, total };\n }\n\n /** A resource's rules, keyed either way: `\"public.goals\"` finds `goals`, and `goals` finds `\"public.goals\"`. */\n const configFor = (resource: string): SupabaseResourceConfig =>\n options.resources?.[resource] ?? options.resources?.[otherSpelling(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 // A test is asked once, as the caller names the resource: asking the other spelling too would\n // let `r => r !== \"x\"` say yes to `public.x`. Only a list matches either spelling.\n if (typeof all === \"function\") return all(resource);\n return spellings(resource).some((name) => all.includes(name));\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 if (typeof bin === \"function\") return bin(resource);\n return spellings(resource).some((name) => bin.includes(name));\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 function versionFor(resource: string): { field: string; kind: \"integer\" | \"timestamp\" } | undefined {\n return configFor(resource).version;\n }\n\n /** The version token a caller asked a write to be checked against, when the resource has one. */\n function expectedFor(resource: string, expectedVersion: string | null | undefined): string | undefined {\n return versionFor(resource) && expectedVersion != null ? String(expectedVersion) : undefined;\n }\n\n /**\n * Whether two version tokens name the same version. A timestamp is compared\n * as an instant to the microsecond, since a realtime payload and a PostgREST\n * read format the same value differently (\"2026-11-03 16:00:00.5+00\" and\n * \"2026-11-03T16:00:00.500000+00:00\").\n */\n function sameVersion(kind: \"integer\" | \"timestamp\", a: string | null, b: string): boolean {\n if (a === b) return true;\n if (a === null || kind !== \"timestamp\") return false;\n const x = instant(a);\n return x !== undefined && x === instant(b);\n }\n\n /**\n * A version-checked write matched no rows: read the row back to say why.\n * Not visible is `gone`; visible at another version is a `conflict` (with\n * the row as it is now, read the way the resource reads); visible at the\n * expected version means the change itself was refused (`forbidden`).\n * Without an expected version, as `noRowsError`. `known` is the row\n * already read back, when the caller has it.\n */\n async function staleOrNoRowsError(\n resource: string,\n id: Identifier,\n verb: \"change\" | \"delete\",\n expected: string | undefined,\n known?: BaseRecord,\n ): Promise<DataWriteError> {\n if (expected === undefined) return noRowsError(resource, id, verb);\n const { field, kind } = versionFor(resource)!;\n let current: BaseRecord | undefined = known;\n try {\n current ??= await readBack(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 (!current) return goneError(resource);\n const currentVersion = current[field] == null ? null : String(current[field]);\n if (sameVersion(kind, currentVersion, expected)) {\n return new DataWriteError(\"forbidden\", `You can't ${verb} this ${nounFor(resource)}.`);\n }\n // Their change, the way this resource is read (a view's joined columns too), so a screen can\n // show it. The table's row stands in when that read fails or finds nothing.\n const config = configFor(resource);\n if (config.source !== undefined || config.select !== undefined) {\n const viewed = await run(read(resource, undefined).eq(\"id\", id)).then((rows) => rows[0] as BaseRecord | undefined, () => undefined);\n if (viewed) current = viewed;\n }\n return new DataWriteError(\n \"conflict\",\n `Someone else changed this ${nounFor(resource)} after you opened it. Review their change, then make yours again.`,\n { current, currentVersion },\n );\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\" | \"n\" | \"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, ...(columns[0]!.nulls ? { n: columns[0]!.nulls } : {}), v: values[0] ?? null }\n : { s: null, o: \"asc\", c: columns.map((c) => ({ s: c.field, o: c.order, ...(c.nulls ? { n: c.nulls } : {}) })), vs: values };\n const sortId = JSON.stringify([columns.map((c) => [c.field, c.order, c.nulls ?? null]), 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, c.n ?? null]), 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 = readFiltered(resource, params.select, cursor || mode === \"none\" ? undefined : mode, 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, nulls } of columns) {\n // Always pinned: the keyset has to know where empty values are. Going back reverses them too.\n const ascending = (order === \"asc\") !== back;\n query = query.order(field, { ascending, nullsFirst: nullsGoLast(order, nulls) === back });\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 if (params.pagination) {\n const { page, perPage } = params.pagination;\n const paged = await readSourcePage(resource, params, (page - 1) * perPage, perPage);\n if (paged) return { data: paged.data, total: mode === \"none\" ? -1 : paged.total } as never;\n }\n const run = (key: string | false) => {\n let query = readFiltered(resource, params.select, mode === \"none\" ? undefined : mode, 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 sort of columns) query = query.order(sort.field, orderOptions(sort));\n query = query.order(key, { ascending: keyOrder === \"asc\" });\n } else if (requested.length > 0) {\n for (const sort of requested) query = query.order(sort.field, orderOptions(sort));\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 aggregate(resource, params) {\n const entries = Object.entries(params.metrics);\n const counts = entries.filter(([, m]) => m.fn === \"count\");\n const others = entries.filter(([, m]) => m.fn !== \"count\");\n const values: Record<string, number | null> = {};\n let isEstimate = false;\n const SAFE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n const refuse = (why: string) =>\n reportReadError(\n new DataReadError(\"invalid\", readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural), {\n cause: new Error(`[SupabaseProvider] aggregate of \"${resource}\": ${why}`),\n }),\n resource,\n \"getList\",\n );\n const narrow = (columns: string, count?: \"exact\" | \"estimated\" | \"planned\") => {\n const query = readFiltered(resource, columns, count, params.filters);\n const clauses = searchClauses(resource, { search: params.search });\n return clauses ? query.or(clauses) : query;\n };\n const pagedTotal = counts.length > 0 ? await readSourcePage(resource, { filters: params.filters, search: params.search }, 0, 0) : undefined;\n if (pagedTotal) {\n for (const [name] of counts) values[name] = pagedTotal.total;\n } else if (counts.length > 0) {\n const mode = params.count ?? \"exact\";\n const result = (await narrow(\"*\", mode).range(0, 0)) as unknown as { error: unknown; count?: number | null };\n await throwIfReadError(result, resource, \"getList\");\n for (const [name] of counts) values[name] = result.count ?? 0;\n isEstimate = mode !== \"exact\";\n }\n if (others.length > 0) {\n if (options.aggregateFunctions) {\n for (const [name, m] of others) {\n if (!SAFE.test(name) || !(\"field\" in m) || !SAFE.test(m.field)) await refuse(`\"${name}\" and its field must be plain column names.`);\n }\n const cols = others.map(([name, m]) => `${name}:${(m as { field: string }).field}.${m.fn}()`).join(\",\");\n const result = (await narrow(cols)) as unknown as { data: Record<string, unknown>[] | null; error: unknown };\n await throwIfReadError(result, resource, \"getList\");\n const row = result.data?.[0] ?? {};\n for (const [name] of others) {\n const raw = row[name];\n const n = raw == null || raw === \"\" ? NaN : Number(raw);\n values[name] = Number.isFinite(n) ? n : null;\n }\n } else {\n // The same reads without this method, so the fallback pages rows instead of calling back here.\n const { aggregate: _self, ...reads } = provider;\n // Pages no bigger than getList allows here (maxPerPage), so the fallback isn't refused.\n const rows = await resolveAggregate(\n reads,\n resource,\n { ...params, metrics: Object.fromEntries(others) },\n { pageSize: Math.max(1, Math.min(500, maxPerPage - 1)) },\n );\n Object.assign(values, rows.values);\n }\n }\n return isEstimate ? { values, isEstimate } : { values };\n },\n\n async getOne(resource, params) {\n // A function source reads in the list's scope (`scope`), never the RPC's default; the\n // filters it doesn't take aren't applied: they choose a list, not the record.\n const result = (await read(resource, params.select, undefined, params.scope)\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, undefined, params.scope)\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: resource ? !!versionFor(resource) : false,\n ...(resource && versionFor(resource) ? { version: { ...versionFor(resource)! } } : {}),\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 } = splitRelation(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 // A copy: with no prepare step this is the caller's own object, and the version is taken out below.\n const row = {\n ...(await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"update\", id }),\n id,\n )),\n };\n const version = versionFor(resource);\n const expected = expectedFor(resource, params.expectedVersion);\n // The database advances the version; a submitted value is never written.\n if (version) delete row[version.field];\n const override = configFor(resource).update;\n let record: BaseRecord;\n if (override && version && override.length < 3 && !warnedUncheckedOverride.has(resource)) {\n warnedUncheckedOverride.add(resource);\n reportError(\n new Error(\n `[SupabaseProvider] \"${resource}\" has a version rule and an update rule that takes no third argument. ` +\n `The update rule is given { expectedVersion }: apply it (match the row at that version, return nothing when none matches), or updates go unchecked.`,\n ),\n { source: \"core:versioned-writes\", tags: { resource } },\n );\n }\n if (override) {\n let returned: BaseRecord | Identifier | boolean | null | undefined | void;\n try {\n returned = expected === undefined ? await override(id, row) : await override(id, row, { expectedVersion: expected });\n } catch (error) {\n throw toDataWriteError(error);\n }\n const result: unknown = returned;\n if (result == null || result === false) throw await staleOrNoRowsError(resource, id, \"change\", expected);\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 let query = from(resource).update(row).eq(\"id\", id);\n if (expected !== undefined) query = query.eq(version!.field, expected);\n const rows = await run(query.select(\"*\"));\n if (rows.length === 0) throw await staleOrNoRowsError(resource, id, \"change\", expected);\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"update\", id, record });\n const newVersion = version && record[version.field] != null ? String(record[version.field]) : undefined;\n return { data: record, ...(newVersion !== undefined ? { version: newVersion } : {}) } as never;\n },\n\n async deleteOne(resource, params) {\n const { id } = params;\n let deletedId: Identifier = id;\n const expected = expectedFor(resource, params.expectedVersion);\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. With a version, the\n // row is checked at it first (a binned delete can't carry the check).\n if (expected !== undefined) {\n const current = await readBack(resource, id);\n if (!current) throw goneError(resource);\n const { field, kind } = versionFor(resource)!;\n if (!sameVersion(kind, current[field] == null ? null : String(current[field]), expected)) {\n throw await staleOrNoRowsError(resource, id, \"delete\", expected, current);\n }\n } else if (!(await isVisible(resource, id))) throw goneError(resource);\n // The version goes on the delete too, so a change landing after the check above isn't\n // binned unseen: the row then stays, and the read-back says it's a conflict.\n let binning = from(resource).delete().eq(\"id\", id);\n if (expected !== undefined) binning = binning.eq(versionFor(resource)!.field, expected);\n await run(binning);\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 if (expected !== undefined) throw await staleOrNoRowsError(resource, id, \"delete\", expected);\n throw new DataWriteError(\"forbidden\", `You can't delete this ${nounFor(resource)}.`);\n }\n } else {\n let query = from(resource).delete().eq(\"id\", id);\n if (expected !== undefined) query = query.eq(versionFor(resource)!.field, expected);\n const rows = await run(query.select(\"id\"));\n if (rows.length === 0) throw await staleOrNoRowsError(resource, id, \"delete\", expected);\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"]}