@marktiderman/genesis-core 2.14.0 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aggregate-y-qqJioF.d.ts +34 -0
- package/dist/{chunk-7PUFVNPB.js → chunk-2IGAUXYH.js} +5 -3
- package/dist/chunk-2IGAUXYH.js.map +1 -0
- package/dist/{chunk-KA3BUJ4H.js → chunk-42NVJJTT.js} +3 -3
- package/dist/{chunk-KA3BUJ4H.js.map → chunk-42NVJJTT.js.map} +1 -1
- package/dist/{chunk-JN47G4UE.js → chunk-7EFTWOMA.js} +56 -2
- package/dist/chunk-7EFTWOMA.js.map +1 -0
- package/dist/{chunk-S2VYJWB4.js → chunk-E3K2A3PK.js} +3 -3
- package/dist/{chunk-S2VYJWB4.js.map → chunk-E3K2A3PK.js.map} +1 -1
- package/dist/{chunk-SDAJSJNN.js → chunk-IYGVJFCV.js} +3 -3
- package/dist/{chunk-SDAJSJNN.js.map → chunk-IYGVJFCV.js.map} +1 -1
- package/dist/chunk-J54XXKQD.js +104 -0
- package/dist/chunk-J54XXKQD.js.map +1 -0
- package/dist/{chunk-OYDJGPDY.js → chunk-JFHRSG6G.js} +5 -5
- package/dist/{chunk-OYDJGPDY.js.map → chunk-JFHRSG6G.js.map} +1 -1
- package/dist/{chunk-UHOMTFBD.js → chunk-JTRRAVR4.js} +55 -3
- package/dist/chunk-JTRRAVR4.js.map +1 -0
- package/dist/{chunk-KV2HW4G4.js → chunk-LB6FMQQM.js} +11 -3
- package/dist/chunk-LB6FMQQM.js.map +1 -0
- package/dist/{chunk-G6GQPXQS.js → chunk-M5IX7C6U.js} +5 -5
- package/dist/{chunk-G6GQPXQS.js.map → chunk-M5IX7C6U.js.map} +1 -1
- package/dist/{chunk-AHFIS42U.js → chunk-NZP7YQHS.js} +5 -5
- package/dist/{chunk-AHFIS42U.js.map → chunk-NZP7YQHS.js.map} +1 -1
- package/dist/{chunk-DFABPMEQ.js → chunk-POUI7GAI.js} +5 -5
- package/dist/{chunk-DFABPMEQ.js.map → chunk-POUI7GAI.js.map} +1 -1
- package/dist/{chunk-NE2D74BP.js → chunk-QGWQ6LK3.js} +5 -5
- package/dist/{chunk-NE2D74BP.js.map → chunk-QGWQ6LK3.js.map} +1 -1
- package/dist/{chunk-2K4747KX.js → chunk-R3YXYVWF.js} +7 -2
- package/dist/chunk-R3YXYVWF.js.map +1 -0
- package/dist/{chunk-RFHUOXZC.js → chunk-SOO54YYY.js} +4 -4
- package/dist/{chunk-RFHUOXZC.js.map → chunk-SOO54YYY.js.map} +1 -1
- package/dist/{chunk-P3FHXRS2.js → chunk-TKK7D2ZT.js} +6 -6
- package/dist/{chunk-P3FHXRS2.js.map → chunk-TKK7D2ZT.js.map} +1 -1
- package/dist/{chunk-WDPM5TBO.js → chunk-UDSTWXXZ.js} +3 -3
- package/dist/{chunk-WDPM5TBO.js.map → chunk-UDSTWXXZ.js.map} +1 -1
- package/dist/chunk-XPBS5YE4.js +24 -0
- package/dist/chunk-XPBS5YE4.js.map +1 -0
- package/dist/csv.d.ts +1 -1
- package/dist/form-types.d.ts +1 -1
- package/dist/hooks/index.d.ts +4 -2
- package/dist/hooks/index.js +16 -14
- package/dist/hooks/mutation-mode.d.ts +1 -1
- package/dist/hooks/mutation-mode.js +5 -4
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-aggregate.d.ts +25 -0
- package/dist/hooks/use-aggregate.js +10 -0
- package/dist/hooks/use-aggregate.js.map +1 -0
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +4 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +6 -4
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-link-options.js +8 -6
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +4 -2
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-one.js +6 -4
- package/dist/hooks/use-persisted-ui-state.js +4 -2
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +4 -2
- package/dist/hooks/use-resource-form.d.ts +1 -1
- package/dist/hooks/use-resource-form.js +8 -7
- package/dist/hooks/use-resource.d.ts +1 -1
- package/dist/hooks/use-resource.js +7 -6
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +110 -6
- package/dist/index.js +125 -17
- package/dist/index.js.map +1 -1
- package/dist/navigation.d.ts +77 -1
- package/dist/navigation.js +32 -2
- package/dist/navigation.js.map +1 -1
- package/dist/provider/index.d.ts +12 -4
- package/dist/provider/index.js +3 -2
- package/dist/resource-view/index.d.ts +456 -166
- package/dist/resource-view/index.js +251 -5
- package/dist/resource-view/index.js.map +1 -1
- package/dist/schema/index.d.ts +3 -3
- package/dist/schema/index.js +1 -2
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-CtJxwoyv.d.ts → types-D4Bi_Iq8.d.ts} +76 -3
- package/dist/workspaces-BKhloJPK.d.ts +255 -0
- package/dist/workspaces.d.ts +2 -160
- package/dist/workspaces.js +1 -1
- package/dist/{write-outcome-Goy1v39G.d.ts → write-outcome-CHPT7Slm.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2K4747KX.js.map +0 -1
- package/dist/chunk-7PUFVNPB.js.map +0 -1
- package/dist/chunk-JN47G4UE.js.map +0 -1
- package/dist/chunk-KV2HW4G4.js.map +0 -1
- package/dist/chunk-UHOMTFBD.js.map +0 -1
- package/dist/chunk-YDMKMNDS.js +0 -8
- package/dist/chunk-YDMKMNDS.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider/mock-provider.ts","../src/provider/context.tsx"],"names":[],"mappings":";;;;;;AAiBO,SAAS,kBAAA,CACd,QAAA,EACA,OAAA,GAA+B,EAAC,EAClB;AACd,EAAA,MAAM,EAAE,KAAA,GAAQ,CAAA,EAAE,GAAI,OAA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;AACzE,IAAA,MAAM,OAAO,MAAM;AACjB,MAAA,IAAI,CAAC,KAAA,CAAM,MAAA,CAAO,OAAA,WAAkB,IAAI,CAAA;AAAA,IAC1C,CAAA;AACA,IAAA,MAAM,IAAA,GAAO,UAAA,CAAW,IAAA,EAAM,eAAe,CAAA;AAC7C,IAAA,KAAK,QAAA,CAAS,QACX,IAAA,CAAK,MAAO,MAAM,MAAA,CAAO,OAAA,GAAU,SAAY,WAAA,CAAY,OAAA,CAAQ,OAAO,KAAA,CAAM,MAAM,CAAE,CAAA,CACxF,KAAA,CAAM,MAAM,MAAS,CAAA,CACrB,QAAQ,MAAM;AACb,MAAA,YAAA,CAAa,IAAI,CAAA;AACjB,MAAA,IAAA,EAAK;AAAA,IACP,CAAC,CAAA;AACH,IAAA,OAAO,MAAM;AACX,MAAA,KAAA,CAAM,KAAA,EAAM;AACZ,MAAA,YAAA,CAAa,IAAI,CAAA;AACjB,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,WAAA,EAAa,KAAK,CAAC,CAAA;AACvB,EAAA,OAAO,KAAA;AACT;AAMO,IAAM,sBAAA,GAAyB,cAAkC,MAAS","file":"chunk-2K4747KX.js","sourcesContent":["import type {\n DataProvider,\n ListParams,\n FilterParam,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Mock DataProvider — operates on in-memory arrays, deep-cloned on creation\n// ---------------------------------------------------------------------------\n\nexport interface MockProviderOptions {\n /** Simulated latency in ms (default 0). */\n delay?: number;\n}\n\ntype Row = Record<string, unknown>;\n\nexport function createMockProvider(\n datasets: Record<string, Row[]>,\n options: MockProviderOptions = {},\n): DataProvider {\n const { delay = 0 } = options;\n\n // Deep clone so mutations don't affect the original data.\n const store: Record<string, Row[]> = JSON.parse(JSON.stringify(datasets));\n\n // Instance-scoped ID counter (NOT module-level).\n let nextId = 1;\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n function getTable(resource: string): Row[] {\n if (!store[resource]) {\n store[resource] = [];\n }\n return store[resource];\n }\n\n async function withDelay<T>(value: T): Promise<T> {\n if (delay > 0) {\n await new Promise((r) => setTimeout(r, delay));\n }\n return value;\n }\n\n function matchesFilter(row: Row, filter: FilterParam): boolean {\n const val = row[filter.field];\n\n switch (filter.operator) {\n case \"eq\":\n return val === filter.value;\n case \"neq\":\n return val !== filter.value;\n case \"gt\":\n return (val as number) > (filter.value as number);\n case \"lt\":\n return (val as number) < (filter.value as number);\n case \"gte\":\n return (val as number) >= (filter.value as number);\n case \"lte\":\n return (val as number) <= (filter.value as number);\n case \"contains\":\n return typeof val === \"string\" &&\n val.toLowerCase().includes(String(filter.value).toLowerCase());\n case \"in\":\n return filter.value.includes(val as string | number | boolean);\n case \"is_null\":\n return val === null || val === undefined;\n case \"is_not_null\":\n return val !== null && val !== undefined;\n case \"between\": {\n const [lo, hi] = filter.value;\n return (val as number) >= (lo as number) && (val as number) <= (hi as number);\n }\n }\n }\n\n function matchesSearch(\n row: Row,\n search: { query: string; fields: string[] },\n ): boolean {\n const q = search.query.toLowerCase();\n return search.fields.some((field) => {\n const val = row[field];\n return typeof val === \"string\" && val.toLowerCase().includes(q);\n });\n }\n\n function compareValues(a: unknown, b: unknown): number {\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a.localeCompare(b, undefined, { numeric: true });\n }\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n // Fallback: coerce to string.\n return String(a ?? \"\").localeCompare(String(b ?? \"\"), undefined, {\n numeric: true,\n });\n }\n\n function applyListParams(table: Row[], params: ListParams): { data: Row[]; total: number } {\n let rows = [...table];\n\n // Filters (AND).\n if (params.filters) {\n for (const f of params.filters) {\n rows = rows.filter((r) => matchesFilter(r, f));\n }\n }\n\n // Search (OR across fields, AND with filters).\n if (params.search && params.search.query) {\n rows = rows.filter((r) => matchesSearch(r, params.search!));\n }\n\n const total = rows.length;\n\n // Sort.\n // By each sort field in turn (`sorts`, else `sort`).\n const sorts = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (sorts.length > 0) {\n rows.sort((a, b) => {\n for (const { field, order, nulls } of sorts) {\n if (nulls && (a[field] == null) !== (b[field] == null)) {\n return (a[field] == null) === (nulls === \"first\") ? -1 : 1;\n }\n const cmp = compareValues(a[field], b[field]);\n if (cmp !== 0) return order === \"desc\" ? -cmp : cmp;\n }\n return 0;\n });\n }\n\n // Pagination (offset-based).\n if (params.pagination) {\n const { page, perPage } = params.pagination;\n const start = (page - 1) * perPage;\n rows = rows.slice(start, start + perPage);\n }\n\n return { data: rows, total };\n }\n\n // ---------------------------------------------------------------------------\n // DataProvider implementation\n // ---------------------------------------------------------------------------\n\n const provider: DataProvider = {\n async getList(_resource, params) {\n const table = getTable(_resource);\n const result = applyListParams(table, params);\n return withDelay(result) as never;\n },\n\n async getOne(_resource, params) {\n const table = getTable(_resource);\n const row = table.find((r) => String(r.id) === String(params.id));\n if (!row) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n return withDelay({ data: JSON.parse(JSON.stringify(row)) }) as never;\n },\n\n async getMany(_resource, params) {\n const table = getTable(_resource);\n const idSet = new Set(params.ids.map(String));\n const rows = table.filter((r) => idSet.has(String(r.id)));\n return withDelay({ data: JSON.parse(JSON.stringify(rows)) }) as never;\n },\n\n async create(_resource, params) {\n const table = getTable(_resource);\n const id = String(nextId++);\n const row = { id, ...params.data } as Row;\n table.push(row);\n return withDelay({ data: JSON.parse(JSON.stringify(row)) }) as never;\n },\n\n async update(_resource, params) {\n const table = getTable(_resource);\n const idx = table.findIndex((r) => String(r.id) === String(params.id));\n if (idx === -1) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n table[idx] = { ...table[idx], ...params.data };\n return withDelay({ data: JSON.parse(JSON.stringify(table[idx])) }) as never;\n },\n\n async deleteOne(_resource, params) {\n const table = getTable(_resource);\n const idx = table.findIndex((r) => String(r.id) === String(params.id));\n if (idx === -1) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n table.splice(idx, 1);\n return withDelay({ data: { id: params.id } });\n },\n };\n\n return provider;\n}\n","import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport type { DataProvider } from \"./types\";\nimport { createMockProvider, type MockProviderOptions } from \"./mock-provider\";\nimport type { StorageAdapter } from \"../storage/types\";\nimport { createLocalStorageAdapter } from \"../storage/adapters\";\nimport type { QueryPersistence } from \"../offline/types\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nconst DataProviderContext = createContext<DataProvider | null>(null);\nconst StorageContext = createContext<StorageAdapter>(createLocalStorageAdapter());\n\n// ---------------------------------------------------------------------------\n// DataProviderRoot — thin context wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Puts a `DataProvider` in context, and nothing else. Mount it inside your\n * app's own `QueryClientProvider` and the Genesis hooks share that cache:\n * the same query keys (`[resource, \"list\", params]`,\n * `[resource, \"detail\", id, select]`), so invalidating `[resource]` from app\n * code refreshes Genesis lists too, and vice versa.\n */\nexport interface DataProviderRootProps {\n provider: DataProvider;\n children: ReactNode;\n}\n\nexport function DataProviderRoot({ provider, children }: DataProviderRootProps) {\n return (\n <DataProviderContext.Provider value={provider}>\n {children}\n </DataProviderContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useDataProvider(): DataProvider {\n const ctx = useContext(DataProviderContext);\n if (!ctx) {\n throw new Error(\n \"useDataProvider must be used inside <DataProviderRoot> or <GenesisProvider>. \" +\n \"Wrap your app (or the relevant subtree) in one of these providers.\",\n );\n }\n return ctx;\n}\n\nexport function useStorage(): StorageAdapter {\n return useContext(StorageContext);\n}\n\n// ---------------------------------------------------------------------------\n// GenesisProvider — convenience wrapper\n// ---------------------------------------------------------------------------\n\ntype Row = Record<string, unknown>;\n\nexport type GenesisProviderProps =\n | {\n children: ReactNode;\n /** Pass a ready-made DataProvider. Mutually exclusive with `mock`. */\n provider: DataProvider;\n mock?: never;\n /** Platform-specific storage adapter. Defaults to localStorage (SSR-safe). */\n storage?: StorageAdapter;\n /**\n * Keep reads on the device and restore them on the next start, so lists and records open at\n * once: `persistOffline({ cache: indexedDbLocalCache(), resources, buster })` from\n * `@marktiderman/genesis-core/offline`. Needs `persistScope`. Give it from the first render:\n * the provider keeps the first one it's given.\n */\n persist?: (client: QueryClient) => QueryPersistence;\n /**\n * Whose cache this is: `cacheScope(user.id, workspaceKey)` once someone is signed in,\n * `null` once nobody is, and `undefined` while that isn't known yet (the session loading).\n * A device is one person's: restoring someone deletes everyone else's kept reads, and\n * `null` deletes them all, so a session that ended outside the app (it expired, or was\n * signed out elsewhere) leaves nothing on the device. Undefined does nothing. A change of\n * scope restores the new one's reads. Clear the QueryClient yourself when the person\n * changes, as a sign-out already does; a `ViewerScope` inside keeps the restored reads for\n * this person. Restoring is client-only: in a server-rendered app, give it after hydration\n * (undefined on the server and the first client render), and the screens restore in the\n * background. Change it only once the provider's session has: a scope must never name a\n * person before the data provider's requests are made as them.\n */\n persistScope?: string | null;\n /**\n * The TanStack Query client to use. Without it, GenesisProvider creates\n * its OWN client — a second cache beside any the app already has, so app\n * queries and Genesis queries would not see each other's invalidations.\n * An app with a `QueryClientProvider` should pass its client here, or\n * use `DataProviderRoot` inside that provider instead.\n */\n queryClient?: QueryClient;\n }\n | {\n children: ReactNode;\n provider?: never;\n /** Pass mock datasets. Mutually exclusive with `provider`. */\n mock: {\n datasets: Record<string, Row[]>;\n options?: MockProviderOptions;\n };\n /** Platform-specific storage adapter. Defaults to localStorage (SSR-safe). */\n storage?: StorageAdapter;\n /** See the `provider` variant. */\n queryClient?: QueryClient;\n /** See the `provider` variant. */\n persist?: (client: QueryClient) => QueryPersistence;\n /** See the `provider` variant. */\n persistScope?: string | null;\n };\n\nconst defaultStorage = createLocalStorageAdapter();\n\n/**\n * Convenience root: a `QueryClientProvider`, storage, and a data provider\n * (yours, or a mock built from datasets). It creates its own `QueryClient`\n * unless you pass `queryClient`; an app that already has one should pass it,\n * or mount `DataProviderRoot` inside its existing `QueryClientProvider`.\n */\nexport function GenesisProvider({\n children,\n provider,\n mock,\n storage,\n queryClient: queryClientProp,\n persist,\n persistScope,\n}: GenesisProviderProps) {\n if (provider && mock) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[GenesisProvider] Both `provider` and `mock` were passed. `provider` takes precedence. This is likely a mistake.\");\n }\n }\n\n // Build provider from mock datasets when no explicit provider is given.\n const resolvedProvider = useMemo(() => {\n if (provider) return provider;\n if (mock) return createMockProvider(mock.datasets, mock.options);\n throw new Error(\n \"<GenesisProvider> requires either a `provider` or `mock` prop.\",\n );\n }, [provider, mock]);\n\n // The caller's QueryClient, or an internal one with sensible defaults.\n const queryClient = useMemo(\n () =>\n queryClientProp ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 5 * 60 * 1000, // 5 minutes\n },\n },\n }),\n [queryClientProp],\n );\n\n const resolvedStorage = storage ?? defaultStorage;\n const restored = useRestoredReads(queryClient, persist, persistScope);\n\n return (\n <QueryClientProvider client={queryClient}>\n <StorageContext.Provider value={resolvedStorage}>\n <DataProviderRoot provider={resolvedProvider}>\n <PersistedViewerContext.Provider value={persist && typeof persistScope === \"string\" ? userOf(persistScope) : undefined}>\n {restored ? children : null}\n </PersistedViewerContext.Provider>\n </DataProviderRoot>\n </StorageContext.Provider>\n </QueryClientProvider>\n );\n}\n\n/** How long the first render waits for the device's reads before it goes on without them. */\nconst RESTORE_WAIT_MS = 400;\n\n/** The person a scope belongs to (`u:<user>|<workspace>`, or a bare user id). */\nconst userOf = (scope: string) => (scope.startsWith(\"u:\") ? scope.slice(2, scope.indexOf(\"|\") < 0 ? undefined : scope.indexOf(\"|\")) : scope);\n\n/**\n * Restores `scope`'s kept reads before the screens first render (so they open from the device),\n * waiting at most RESTORE_WAIT_MS, then saves new reads. Only the first render waits, and never on\n * the server; a later scope change restores in the background. When the person changes or signs\n * out, their reads are deleted from the device before anything of the next scope is restored.\n */\nfunction useRestoredReads(\n queryClient: QueryClient,\n persist: ((client: QueryClient) => QueryPersistence) | undefined,\n scope: string | null | undefined,\n): boolean {\n // The first `persist` given is kept (one given only later is ignored), so a screen that writes\n // it inline doesn't restart the restore on every render.\n const persistRef = useRef(persist);\n const persistence = useMemo(() => (persistRef.current ? persistRef.current(queryClient) : null), [queryClient]);\n const [ready, setReady] = useState(!persistence || !scope || typeof window === \"undefined\");\n // Whose reads this provider last restored or saved, and the clear of them still running.\n const person = useRef<string | null>(null);\n const clearing = useRef<Promise<void>>(Promise.resolve());\n // The scope the last run of the effect saw (\"not known yet\" at mount). A scope that arrives from\n // there is saved only from reads fetched once it's known: whatever the client already holds or\n // is reading may be another session's (the session was loading, or the client outlived this\n // provider and someone else's session), so it's fetched again (`refresh`), never adopted.\n const previous = useRef<string | null | undefined>(undefined);\n useEffect(() => {\n const from = previous.current;\n previous.current = scope;\n if (!persistence || scope === undefined) {\n // Not known yet who's signed in: nothing is restored, saved or deleted.\n setReady(true);\n return;\n }\n if (scope === null) {\n // Nobody signed in: nothing of anyone's stays on the device.\n person.current = null;\n clearing.current = persistence.restore(\"\").catch(() => undefined);\n setReady(true);\n return;\n }\n const next = userOf(scope);\n if (person.current !== null && person.current !== next) {\n clearing.current = persistence.clear().catch(() => undefined);\n }\n person.current = next;\n const abort = new AbortController();\n // Saving starts with the scope. A read made before it is saved only when the scope before was\n // \"not known yet\" (the same session, loading); from another person or workspace, never.\n const stop = persistence.subscribe(scope, { refresh: from === undefined });\n const open = () => {\n if (!abort.signal.aborted) setReady(true);\n };\n const wait = setTimeout(open, RESTORE_WAIT_MS);\n void clearing.current\n .then(() => (abort.signal.aborted ? undefined : persistence.restore(scope, abort.signal)))\n .catch(() => undefined)\n .finally(() => {\n clearTimeout(wait);\n open();\n });\n return () => {\n abort.abort();\n clearTimeout(wait);\n stop();\n };\n }, [persistence, scope]);\n return ready;\n}\n\n/**\n * The person whose kept reads `GenesisProvider` restored (`persistScope`'s user), so a\n * `ViewerScope` inside keeps them for that viewer instead of emptying the cache.\n */\nexport const PersistedViewerContext = createContext<string | undefined>(undefined);\n\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/query-keys.ts"],"names":[],"mappings":";AAyDA,SAAS,YAAY,KAAA,EAAyB;AAC5C,EAAA,MAAM,GAAA,GAAc,EAAE,MAAA,EAAQ,KAAA,CAAM,MAAA,EAAO;AAC3C,EAAA,IAAI,KAAA,CAAM,KAAA,KAAU,MAAA,EAAW,GAAA,CAAI,QAAQ,KAAA,CAAM,KAAA;AACjD,EAAA,IAAI,KAAA,CAAM,GAAA,KAAQ,MAAA,EAAW,GAAA,CAAI,MAAM,KAAA,CAAM,GAAA;AAE7C,EAAA,IAAI,KAAA,CAAM,KAAA,IAAS,MAAA,CAAO,IAAA,CAAK,MAAM,KAAK,CAAA,CAAE,MAAA,GAAS,CAAA,EAAG,GAAA,CAAI,KAAA,GAAQ,EAAE,GAAG,MAAM,KAAA,EAAM;AACrF,EAAA,OAAO,GAAA;AACT;AAEA,IAAM,UAAA,GAAa,CAAC,KAAA,KAClB,IAAA,CAAK,SAAA;AAAA,EAAU,KAAA;AAAA,EAAO,CAAC,IAAA,EAAM,CAAA,KAC3B,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAQ,CAAC,CAAA,GAC1C,MAAA,CAAO,WAAA,CAAY,OAAO,OAAA,CAAQ,CAAW,CAAA,CAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,CAAA,GAAI,KAAK,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAE,CAAC,CAAA,GAC/F;AACN,CAAA;AAGF,SAAS,I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AAG,IAAI,CAAC,CAAA;AAAA,QAC5G;AAAA,OACF;AAAA,IACF;AAAA,GACF;AACA,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,EAAG;AACvC,IAAA,IAAI,IAAA,IAAQ,MAAM,MAAM,IAAI,MAAM,CAAA,eAAA,EAAkB,MAAM,CAAA,2BAAA,EAA8B,IAAI,CAAA,CAAA,CAAG,CAAA;AAC/F,IAAA,IAAA,CAAK,IAAI,CAAA,GAAI,EAAE,KAAK,CAAC,MAAA,EAAQ,IAAI,CAAA,EAAW;AAAA,EAC9C;AACA,EAAA,OAAO,IAAA;AACT;AAMO,SAAS,aAAa,QAAA,EAAkB;AAC7C,EAAA,OAAO;AAAA,IACL,GAAA,EAAK,CAAC,QAAQ,CAAA;AAAA,IACd,KAAA,EAAO,CAAC,QAAA,EAAU,MAAM,CAAA;AAAA,IACxB,MAAM,CAAC,MAAA,KAAuB,CAAC,QAAA,EAAU,QAAQ,MAAM,CAAA;AAAA,IACvD,OAAA,EAAS,CAAC,QAAA,EAAU,QAAQ,CAAA;AAAA;AAAA,IAE5B,WAAW,CAAC,EAAA,KAAsC,CAAC,QAAA,EAAU,UAAU,EAAE,CAAA;AAAA,IACzE,MAAA,EAAQ,CAAC,EAAA,EAAmC,MAAA,KAAoB,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,MAAM,CAAA;AAAA,IAC/F,UAAU,CAAC,MAAA,KAAoB,CAAC,QAAA,EAAU,YAAY,MAAM;AAAA,GAC9D;AACF","file":"chunk-7PUFVNPB.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Query keys (README \"Query keys\")\n//\n// One place that builds every cache key, so a write invalidates what it made\n// stale and nothing shows across people. Keys are `[domain, kind, fields]`:\n// TanStack matches keys by prefix and matches objects by their fields, so\n// `[domain]` and `[domain, kind]` invalidate everything under them, and\n// `where({...})` reaches keys by any field, including one person inside a\n// multi-person key.\n//\n// App keys are scoped to the signed-in viewer by default: `for({ viewer })`\n// is the only way to build one, and the scope (viewer, group, day) is part of\n// the fields. Resource keys carry no viewer: `ViewerScope` (or\n// `clearViewerCache` in the sign-in/out action) keeps those apart.\n// ---------------------------------------------------------------------------\n\nimport type { Query } from \"@tanstack/react-query\";\nimport type { Identifier, ListParams } from \"./provider/types\";\n\n/** Who and when a key is for. `viewer` is required; null means signed out. */\nexport interface KeyScope {\n viewer: string | null;\n /** The group, organization or space the screen is filtered to. */\n group?: string | null;\n /** The person-day (YYYY-MM-DD) a \"today\" read is for. */\n day?: string | null;\n /**\n * Where the viewer is working (ViewerScope's `scope`: an org, a league, a person…). Part of\n * every key, so the same query for two scopes never shares a cache entry.\n */\n scope?: Readonly<Record<string, unknown>>;\n}\n\ntype Fields = Record<string, unknown>;\ntype QueryDefs = Record<string, (...args: never[]) => Fields>;\n\nexport type ScopedKey<D extends string, K> = readonly [D, K, Fields];\n\n/** A filter for `invalidateQueries` / `removeQueries` / `getQueriesData`. */\nexport interface KeyFilter {\n predicate: (query: Query) => boolean;\n}\n\nexport type QueryKeys<D extends string, Q extends QueryDefs> = {\n /** Every key in the domain: `[domain]`. */\n readonly all: readonly [D];\n /** Builds keys for one scope. */\n for(scope: KeyScope): { [K in keyof Q]: (...args: Parameters<Q[K]>) => ScopedKey<D, K> };\n /**\n * Keys whose fields match `fields`: an equal value (`1` matches `\"1\"`,\n * objects whatever their key order), an array field containing the value,\n * or, for an array value, an array field containing every item. `kind`\n * narrows it to one query.\n */\n where(fields: Fields, kind?: keyof Q): KeyFilter;\n} & { readonly [K in keyof Q]: { readonly all: readonly [D, K] } };\n\nfunction scopeFields(scope: KeyScope): Fields {\n const out: Fields = { viewer: scope.viewer };\n if (scope.group !== undefined) out.group = scope.group;\n if (scope.day !== undefined) out.day = scope.day;\n // Key order doesn't matter: TanStack hashes keys with object keys sorted.\n if (scope.scope && Object.keys(scope.scope).length > 0) out.scope = { ...scope.scope };\n return out;\n}\n\nconst stableText = (value: unknown) =>\n JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Fields).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : v,\n );\n\n/** Equal, with numbers and their text equal, and objects equal whatever their key order. */\nfunction same(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const scalar = (v: unknown) => typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\";\n if (scalar(a) && scalar(b)) return String(a) === String(b);\n return stableText(a) === stableText(b);\n}\n\nfunction fieldMatches(have: unknown, want: unknown): boolean {\n if (same(have, want)) return true;\n if (!Array.isArray(have)) return false;\n // An empty list asks for an empty list, not \"any list\".\n if (Array.isArray(want)) return want.length > 0 && want.every((w) => have.some((h) => same(h, w)));\n return have.some((h) => same(h, want));\n}\n\n/**\n * The keys of one domain. Each query maps its arguments to the fields that\n * make it distinct (sort arrays so order never makes two keys):\n *\n * ```ts\n * export const worksheetKeys = defineQueryKeys(\"worksheet-items\", {\n * lessonParts: (people: string[]) => ({ people: [...people].sort() }),\n * byEntry: (entryId: string) => ({ entryId }),\n * });\n * useQuery({ queryKey: worksheetKeys.for({ viewer }).lessonParts(people), … });\n * queryClient.invalidateQueries(worksheetKeys.where({ people: personId }));\n * queryClient.invalidateQueries(worksheetKeys.where({ entryId }, \"byEntry\"));\n * queryClient.invalidateQueries({ queryKey: worksheetKeys.lessonParts.all });\n * ```\n */\nexport function defineQueryKeys<const D extends string, Q extends QueryDefs>(domain: D, queries: Q): QueryKeys<D, Q> {\n const keys: Record<string, unknown> = {\n all: [domain] as const,\n for(scope: KeyScope) {\n if (!scope || !(\"viewer\" in scope)) throw new Error(`[genesis-core] ${domain} keys need a scope with a viewer`);\n const scoped = scopeFields(scope);\n return Object.fromEntries(\n Object.entries(queries).map(([kind, fields]) => [\n kind,\n (...args: never[]) => {\n const own = fields(...args);\n for (const name of Object.keys(scoped)) {\n if (name in own) throw new Error(`[genesis-core] ${domain}.${kind} can't name a field \"${name}\": it's the scope's`);\n }\n return [domain, kind, { ...own, ...scoped }] as const;\n },\n ]),\n );\n },\n where(fields: Fields, kind?: string): KeyFilter {\n return {\n predicate: (query) => {\n const [d, k, f] = query.queryKey as readonly unknown[];\n if (d !== domain || (kind !== undefined && k !== kind)) return false;\n if (!f || typeof f !== \"object\") return Object.keys(fields).length === 0;\n // A key without the field never matches it, even when the value asked for is undefined.\n return Object.entries(fields).every(([name, want]) => name in f && fieldMatches((f as Fields)[name], want));\n },\n };\n },\n };\n for (const kind of Object.keys(queries)) {\n if (kind in keys) throw new Error(`[genesis-core] ${domain} can't have a query named \"${kind}\"`);\n keys[kind] = { all: [domain, kind] as const };\n }\n return keys as QueryKeys<D, Q>;\n}\n\n/**\n * The keys Genesis's own hooks cache a resource under, for writing into or\n * invalidating them by hand: `[resource]` covers them all.\n */\nexport function resourceKeys(resource: string) {\n return {\n all: [resource] as const,\n lists: [resource, \"list\"] as const,\n list: (params: ListParams) => [resource, \"list\", params] as const,\n details: [resource, \"detail\"] as const,\n /** Every projection of one record: `detail(id, select)` for any `select`. */\n detailsOf: (id: Identifier | null | undefined) => [resource, \"detail\", id] as const,\n detail: (id: Identifier | null | undefined, select?: string) => [resource, \"detail\", id, select] as const,\n infinite: (params: unknown) => [resource, \"infinite\", params] as const,\n };\n}\n\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider/supabase-provider.ts","../src/provider/write-helpers.ts"],"names":["run","from"],"mappings":";;;;;AAqUA,SAAS,eAAA,CAAgB,KAAA,EAAgB,KAAA,EAAe,MAAA,EAAyB;AAC/E,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AAChD,EAAA,MAAM,EAAE,IAAA,EAAM,OAAA,EAAQ,GAAI,KAAA;AAC1B,EAAA,IAAI,IAAA,KAAS,OAAA,IAAW,OAAO,OAAA,KAAY,UAAU,OAAO,KAAA;AAC5D,EAAA,MAAM,KAAA,GA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AM;AAAA,IACxC,CAAC,CAAA;AACD,IAAA,MAAM,EAAE,IAAA,EAAM,IAAA,KAAS,MAAM,QAAA,CAAS,QAAW,QAAA,EAAU;AAAA,MACzD,OAAA,EAAS,CAAC,GAAG,OAAA,EAAS,GAAI,OAAA,CAAQ,KAAA,IAAS,EAAG,CAAA;AAAA,MAC9C,UAAA,EAAY,EAAE,IAAA,EAAM,CAAA,EAAG,SAAS,CAAA;AAAE,KACnC,CAAA;AACD,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,MAAM,KAAA;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-JN47G4UE.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\";\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/** Per-resource rules for `createSupabaseProvider`. Every field is optional. */\nexport interface SupabaseResourceConfig {\n /** Singular noun for failure messages, e.g. \"project\". Defaults to \"record\". */\n noun?: string;\n /** Plural for list messages, when it isn't `noun` + \"s\" (\"categories\"). */\n nounPlural?: string;\n /**\n * The columns a search covers. `[]` means the resource can't be searched,\n * and `capabilities(resource).search` reports false so a UI hides the box.\n * Set, they replace the caller's `search.fields`; omitted, those are used\n * as given.\n */\n searchFields?: readonly string[];\n /**\n * The column a sorted list orders by last, so rows with equal sort values\n * keep one order from page to page (none repeats, none is skipped).\n * Default `\"id\"`; `false` for a table or view without one. With the\n * default, a view that turns out to have no `id` column is read as before\n * (without the key order) and a development warning suggests setting this.\n */\n orderKey?: string | false;\n /**\n * `\"bin\"` for a table whose delete trigger moves the row to a recycle bin\n * instead of removing it (see `SupabaseProviderOptions.binTables`).\n * `\"hard\"` forces a plain delete even when `binTables` lists the table.\n */\n deleteMode?: \"hard\" | \"bin\";\n /**\n * Turns submitted values into the row to write: trim, drop read-only keys,\n * validate. Runs before every create and update, including the `create`\n * and `update` overrides. Throw (ideally `DataWriteError(\"invalid\", ...)`)\n * to refuse the write; nothing is sent.\n */\n prepare?: (\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /**\n * Creates the row some other way than an insert, e.g. a security-definer\n * RPC. Return the new row, or its id and the provider reads the row back\n * (if the read-back fails, the create is still reported as saved, with\n * just the id, so the user does not retry and make a second one). Throw to\n * fail; a Supabase `{ message, code }` error is mapped like any other.\n */\n create?: (row: Record<string, unknown>) => Promise<BaseRecord | Identifier>;\n /**\n * Updates the row some other way than an update, e.g. an RPC. Return the\n * updated row, or its id (or `true`) and the provider reads it back.\n * Returning nothing (`undefined`/`null`/`false`) means no row changed: the provider then reads the\n * row to say why (`forbidden` or `gone`), exactly as for a plain update,\n * so a function that silently skips a row never reports a save.\n */\n update?: (\n id: Identifier,\n row: Record<string, unknown>,\n 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: () => ({ group_id: currentGroup() }) } },\n * }\n * ```\n */\n source?: string | { rpc: string; args?: () => Record<string, unknown> };\n /**\n * How lists of this resource count their total (default `exact`). Use\n * `estimated` for large tables, or `none` when no screen shows a count.\n */\n count?: CountMode;\n /** The columns read when the caller names none, e.g. embedded joins: `\"*, person:people(full_name)\"`. Default `\"*\"`. */\n select?: string;\n /**\n * With a `source` (or a `select` that embeds other tables), the table's own\n * columns: creates and updates write only these, so a form built from the\n * richer read row never sends its joined or computed columns to the table.\n * Without it, an update writes only the columns the table's row has.\n */\n writeColumns?: readonly string[];\n}\n\n/** Options for `createSupabaseProvider`. All optional; none changes reads. */\nexport interface SupabaseProviderOptions {\n /**\n * Recycle-bin tables: their delete trigger turns a delete into a \"binned\"\n * mark and the binned row drops out of the caller's view (RLS or a view\n * filter). The database reports such a delete as zero rows, so for these\n * the provider checks the row is visible, deletes it, and reads it back:\n * gone from view is success, still visible is `forbidden`. A row that was\n * not visible beforehand is `gone`. 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\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 ): SupabaseQueryBuilder {\n const config = configFor(resource);\n const cols = columns ?? config.select ?? \"*\";\n const source = config.source;\n if (source && typeof source === \"object\") {\n if (!client.rpc) {\n throw new DataReadError(\"error\", `[SupabaseProvider] \"${resource}\" reads from ${source.rpc}(), but the client has no rpc.`);\n }\n const builder = client.rpc(source.rpc, source.args?.() ?? {}, count ? { count } : undefined) as SupabaseQueryBuilder;\n return builder.select(cols);\n }\n const table = relation(source ?? resource);\n return count ? table.select(cols, { count }) : table.select(cols);\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 = read(resource, params.select, cursor || mode === \"none\" ? undefined : mode);\n query = applyFilters(query, params.filters);\n const search = searchClauses(resource, params);\n const keyset = after ? keysetClauses(after) : \"\";\n // Both are OR groups that must hold together: nest them in one `or`.\n if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);\n else if (search || keyset) query = query.or(search || keyset);\n\n // Going back reads the rows before the cursor in the reverse order (nearest first), then\n // turns them around.\n const back = after?.d === \"b\";\n for (const { field, order, 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 const run = (key: string | false) => {\n let query = read(resource, params.select, mode === \"none\" ? undefined : mode);\n\n query = applyFilters(query, params.filters);\n\n // Search — convert to OR of ilike. A resource's configured\n // `searchFields` win over the caller's.\n const clauses = searchClauses(resource, params);\n if (clauses) {\n query = query.or(clauses);\n }\n\n // Each sort column, then the key column, so equal sort values keep\n // one order across pages (otherwise a row can repeat on page 2 or be\n // skipped). An unsorted page is ordered by the key alone: without an\n // ORDER BY the database may return pages in any order.\n const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (requested.length > 0 && key) {\n const { columns, keyOrder } = sortColumns(params, key);\n for (const 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 getOne(resource, params) {\n const result = (await read(resource, params.select)\n .eq(\"id\", params.id)\n .single()) as { data: unknown; error: unknown };\n await throwIfReadError(result, resource, \"getOne\");\n return { data: result.data } as never;\n },\n\n async getMany(resource, params) {\n if (params.ids.length === 0) return { data: [] } as never;\n const result = (await read(resource, undefined)\n .in(\"id\", params.ids)) as { data: unknown[]; error: unknown };\n await throwIfReadError(result, resource, \"getMany\");\n return { data: result.data ?? [] } as never;\n },\n\n async capabilities(resource?: string): Promise<ProviderCapabilities> {\n return {\n search: resource ? configFor(resource).searchFields?.length !== 0 : true,\n sort: true,\n filterOperators: SERVED_OPERATORS,\n bulkWrites: false,\n versionedWrites: 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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema/keys.ts"],"names":[],"mappings":";AAYO,SAAS,UAAU,QAAA,EAA4D;AACpF,EAAA,OAAO,OAAO,SAAS,GAAA,KAAQ,QAAA,GAAW,CAAC,QAAA,CAAS,GAAG,IAAI,QAA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AAC,CAAA;AAAA,EAChC,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,8BAAA,EAAiC,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,EAAA,CAAI,CAAA;AAAA,EACtF;AACA,EAAA,IACE,CAAC,MAAM,OAAA,CAAQ,MAAM,KACrB,MAAA,CAAO,MAAA,KAAW,OAAO,MAAA,IACzB,CAAC,OAAO,KAAA,CAAM,CAAC,MAAM,OAAO,CAAA,KAAM,YAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EACnE;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,8BAAA,EAAiC,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,EAAA,CAAI,CAAA;AAAA,EACtF;AACA,EAAA,MAAM,MAAuC,EAAC;AAC9C,EAAA,MAAA,CAAO,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AAC3B,IAAA,GAAA,CAAI,KAAK,CAAA,GAAI,MAAA,CAAO,CAAC,CAAA;AAAA,EACvB,CAAC,CAAA;AACD,EAAA,OAAO,GAAA;AACT","file":"chunk-KV2HW4G4.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Record identity for single and composite keys (DATA-STUDIO.md decision 13)\n//\n// `DataProvider` methods take one `Identifier`. A composite key travels\n// through that same slot as a canonical string, so every existing provider\n// signature stays as it is and a junction table still has one id per row.\n// ---------------------------------------------------------------------------\n\nimport type { Identifier } from \"../provider/types\";\nimport type { DataRow, ResourceContract } from \"./types\";\n\n/** The key of a contract as a list, whichever form `key` was declared in. */\nexport function keyFields(contract: Pick<ResourceContract, \"key\">): readonly string[] {\n return typeof contract.key === \"string\" ? [contract.key] : contract.key;\n}\n\nfunction keyValue(row: DataRow, field: string): string | number {\n const value = row[field];\n if (typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\" || typeof value === \"boolean\") return String(value);\n throw new Error(\n `Record key field \"${field}\" is ${value === null ? \"null\" : typeof value}; ` +\n \"a key value must be a string or a number.\",\n );\n}\n\n/**\n * One `Identifier` for a row.\n *\n * A single-field key returns the raw value, so `id`-keyed resources look\n * exactly as they always have. A composite key returns a JSON array of the\n * values in key order, e.g. `'[\"c-1\",\"u-7\"]'`.\n */\nexport function encodeRecordKey(\n contract: Pick<ResourceContract, \"key\">,\n row: DataRow,\n): Identifier {\n const fields = keyFields(contract);\n if (fields.length === 0) throw new Error(\"This resource has no key, so its rows cannot be addressed.\");\n if (fields.length === 1) return keyValue(row, fields[0]!);\n return JSON.stringify(fields.map((field) => keyValue(row, field)));\n}\n\n/**\n * The inverse of {@link encodeRecordKey}: field name → value.\n *\n * Throws on an id that does not fit the key, rather than guessing, because a\n * guessed key addresses the wrong row.\n */\nexport function decodeRecordKey(\n contract: Pick<ResourceContract, \"key\">,\n id: Identifier,\n): Record<string, string | number> {\n const fields = keyFields(contract);\n if (fields.length === 0) throw new Error(\"This resource has no key, so its rows cannot be addressed.\");\n if (fields.length === 1) return { [fields[0]!]: id };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(String(id));\n } catch {\n throw new Error(`\"${String(id)}\" is not a composite key for (${fields.join(\", \")}).`);\n }\n if (\n !Array.isArray(parsed) ||\n parsed.length !== fields.length ||\n !parsed.every((v) => typeof v === \"string\" || typeof v === \"number\")\n ) {\n throw new Error(`\"${String(id)}\" is not a composite key for (${fields.join(\", \")}).`);\n }\n const out: Record<string, string | number> = {};\n fields.forEach((field, i) => {\n out[field] = parsed[i] as string | number;\n });\n return out;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/workspaces.ts"],"names":[],"mappings":";AAwFO,IAAM,oBAAA,GAAiD,CAAC,UAAA,EAAY,QAAA,EAAU,QAAQ;AAE7F,SAAS,SAAS,IAAA,EAAsB;AACtC,EAA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AA,CAAsC,YAA0B,KAAA,EAAoB;AAClG,EAAA,MAAM,KAAA,GAAQ,KAAK,KAAK,CAAA,CAAE,MAAM,KAAK,CAAA,CAAE,OAAO,OAAO,CAAA;AACrD,EAAA,IAAI,MAAM,MAAA,KAAW,CAAA,EAAG,OAAO,CAAC,GAAG,UAAU,CAAA;AAC7C,EAAA,OAAO,UAAA,CAAW,MAAA,CAAO,CAAC,CAAA,KAAM;AAC9B,IAAA,MAAM,IAAA,GAAO,KAAK,CAAA,EAAG,CAAA,CAAE,KAAK,CAAA,CAAA,EAAI,CAAA,CAAE,WAAA,IAAe,EAAE,CAAA,CAAE,CAAA;AACrD,IAAA,OAAO,MAAM,KAAA,CAAM,CAAC,SAAS,IAAA,CAAK,QAAA,CAAS,IAAI,CAAC,CAAA;AAAA,EAClD,CAAC,CAAA;AACH;AAEA,SAAS,KAAK,IAAA,EAAsB;AAClC,EAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA,CAAE,QAAQ,SAAA,EAAW,EAAE,EAAE,WAAA,EAAY;AAClE;AAQO,SAAS,iBAAA,CACd,UAAA,EACA,KAAA,GAAkC,oBAAA,EAC7B;AACL,EAAA,OAAO,eAAA,CAAgB,YAAY,KAAK,CAAA,CAAE,QAAQ,CAAC,CAAA,KAAM,EAAE,UAAU,CAAA;AACvE","file":"chunk-UHOMTFBD.js","sourcesContent":["/**\n * Workspaces (docs/adr/0004-workspaces.md): where the viewer is working, chosen first and kept in\n * the URL. A workspace is one tenant (an organization), the roll-up across them, or the viewer's\n * own personal space. Everything inside it is scoped to it: its `scope` is the `ResourceScope`\n * every view reads, and its path prefixes every URL inside it.\n *\n * Router-free and DOM-free, like `navigation`: web and native shells share it.\n */\n\nimport type { ResourceScope } from \"./hooks/viewer-scope\";\nimport type { GenesisViewerRoles } from \"./viewer\";\n\n/**\n * The kinds of workspace. Genesis ships three; an app adds its own by module augmentation, and\n * the switcher groups and orders them like the built-in ones:\n *\n * ```ts\n * declare module \"@marktiderman/genesis-core/workspaces\" {\n * interface GenesisWorkspaceKinds {\n * location: true;\n * }\n * }\n * ```\n *\n * @stability Beta\n */\nexport interface GenesisWorkspaceKinds {\n /** One tenant: an organization the viewer is a member or staff of. */\n tenant: true;\n /** The roll-up across every tenant the viewer works in. */\n rollup: true;\n /** The viewer's own things, belonging to no tenant. */\n personal: true;\n}\n\n/** @stability Beta */\nexport type WorkspaceKind = keyof GenesisWorkspaceKinds;\n\n/**\n * One place the viewer can work in.\n *\n * @stability Beta\n */\nexport interface Workspace {\n /** Unique among the viewer's workspaces. For a tenant, usually its URL segment. */\n id: string;\n kind: WorkspaceKind;\n /** Its name: the organization's name, \"All organizations\", \"Personal\". */\n label: string;\n /** A second line in the switcher: the viewer's role there, a location. */\n description?: string;\n /**\n * Where it starts, and the prefix of every URL inside it: `/o/acme`, `/all`, `/me`. Matched at\n * segment boundaries, so `/o/acme` never matches `/o/acme-west`.\n */\n path: string;\n /** What views read inside it: `{ orgId }`, `{ orgId: [...] }`, `{ personId }`. */\n scope: ResourceScope;\n /** The viewer's roles here, for view guards (see `GenesisViewerRoles`). */\n roles?: GenesisViewerRoles;\n /** The workspace's IANA time zone, for columns read on the scope's clock. */\n timeZone?: string | null;\n /** Its picture: a logo URL, else initials made from `label`. */\n image?: string;\n /**\n * A count or short status beside it in the switcher: unread messages, tasks waiting. `0`, an\n * empty string, `null` and undefined show nothing.\n */\n badge?: string | number | null;\n /** Its brand, for the switcher's picture and anything the app themes inside it. */\n theme?: WorkspaceTheme;\n /** Anything else the app needs; Genesis never reads it. */\n meta?: Readonly<Record<string, unknown>>;\n}\n\n/**\n * A workspace's brand. `accent` takes the same values as a public page's brand accent (`#rgb`,\n * `#rrggbb`, `rgb()`, `hsl()` or a bare token triplet like `\"160 84% 39%\"`); genesis-ui turns it\n * into the design system's `--primary` (`workspaceThemeStyle`), darkened when it is too light to\n * carry text.\n *\n * @stability Beta\n */\nexport interface WorkspaceTheme {\n accent?: string;\n}\n\n/** The kinds in their default order: personal, roll-up, then each tenant. */\nexport const WORKSPACE_KIND_ORDER: readonly WorkspaceKind[] = [\"personal\", \"rollup\", \"tenant\"];\n\nfunction trimPath(path: string): string {\n const bare = path.split(/[?#]/)[0] ?? \"\";\n // Trailing slashes off, keeping \"/\" itself. A loop, not /\\/+$/, which is slow on many slashes.\n let end = bare.length;\n while (end > 1 && bare[end - 1] === \"/\") end--;\n return bare.slice(0, end);\n}\n\nfunction within(pathname: string, prefix: string): boolean {\n const p = trimPath(pathname);\n const w = trimPath(prefix);\n if (w === \"/\") return true;\n return p === w || p.startsWith(`${w}/`);\n}\n\n/**\n * The workspace a URL is in: the one whose `path` is the longest prefix of `pathname`, or\n * undefined when the URL is in none (a sign-in page, the app's front door).\n *\n * @stability Beta\n */\nexport function workspaceAt<W extends Workspace>(workspaces: readonly W[], pathname: string): W | undefined {\n let best: W | undefined;\n for (const w of workspaces) {\n if (within(pathname, w.path) && (!best || trimPath(w.path).length > trimPath(best.path).length)) best = w;\n }\n return best;\n}\n\n/**\n * The path inside a workspace: `/o/acme/clients/42` in `/o/acme` is `/clients/42`; the workspace's\n * own landing page is `/`.\n *\n * @stability Beta\n */\nexport function pathInWorkspace(workspace: Pick<Workspace, \"path\">, pathname: string): string {\n const w = trimPath(workspace.path);\n const p = trimPath(pathname);\n if (!within(p, w)) return \"/\";\n const rest = w === \"/\" ? p : p.slice(w.length);\n return rest || \"/\";\n}\n\n/** @stability Beta */\nexport interface WorkspaceHrefOptions {\n /**\n * Whether to keep the viewer's place when switching: given the path inside the current\n * workspace (`/clients`) and the two workspaces, return the path to open in the target, or\n * false for its landing page. By default the place is kept between workspaces of the same kind,\n * up to the first segment (a list, not one record that belongs to the old workspace):\n * `/o/acme/clients/42` switches to `/o/globex/clients`.\n */\n keep?: (rest: string, from: Workspace, to: Workspace) => string | false;\n}\n\n/** The default `keep`: the same kind keeps the section (the first segment), never a record. */\nexport function keepSection(rest: string, from: Workspace, to: Workspace): string | false {\n if (from.kind !== to.kind) return false;\n const section = rest.split(\"/\").filter(Boolean)[0];\n return section ? `/${section}` : false;\n}\n\n/**\n * Where switching to `to` goes from `pathname`. The URL moves with the viewer: it lands in the same\n * section of the new workspace when that makes sense (see `keep`), else on its landing page.\n *\n * @stability Beta\n */\nexport function workspaceHref(\n workspaces: readonly Workspace[],\n to: Workspace,\n pathname: string | undefined,\n options: WorkspaceHrefOptions = {},\n): string {\n const from = pathname === undefined ? undefined : workspaceAt(workspaces, pathname);\n if (!from || from.id === to.id || pathname === undefined) return to.path;\n const kept = (options.keep ?? keepSection)(pathInWorkspace(from, pathname), from, to);\n if (!kept || kept === \"/\") return to.path;\n const base = trimPath(to.path);\n return `${base === \"/\" ? \"\" : base}${kept.startsWith(\"/\") ? kept : `/${kept}`}`;\n}\n\n/** @stability Beta */\nexport interface WorkspaceGroup<W extends Workspace = Workspace> {\n kind: WorkspaceKind;\n workspaces: W[];\n}\n\n/**\n * The workspaces grouped by kind, in `order` (default {@link WORKSPACE_KIND_ORDER}, then any kind\n * an app added), each group in the order given. Empty groups are left out.\n *\n * @stability Beta\n */\nexport function groupWorkspaces<W extends Workspace>(\n workspaces: readonly W[],\n order: readonly WorkspaceKind[] = WORKSPACE_KIND_ORDER,\n): WorkspaceGroup<W>[] {\n const kinds = [...order];\n for (const w of workspaces) if (!kinds.includes(w.kind)) kinds.push(w.kind);\n return kinds\n .map((kind) => ({ kind, workspaces: workspaces.filter((w) => w.kind === kind) }))\n .filter((g) => g.workspaces.length > 0);\n}\n\n/**\n * The workspace to open when the URL names none (the app's front door): the remembered one if the\n * viewer still has it, else the first tenant, else the first workspace.\n *\n * @stability Beta\n */\nexport function defaultWorkspace<W extends Workspace>(workspaces: readonly W[], rememberedId?: string | null): W | undefined {\n return (\n (rememberedId ? workspaces.find((w) => w.id === rememberedId) : undefined) ??\n workspaces.find((w) => w.kind === \"tenant\") ??\n workspaces[0]\n );\n}\n\n/**\n * Initials for a workspace with no image: the first letters of its first two words.\n *\n * @stability Beta\n */\nexport function workspaceInitials(label: string): string {\n const words = label.trim().split(/\\s+/).filter(Boolean);\n const letters = words.length > 1 ? [words[0]![0], words[1]![0]] : [...(words[0] ?? \"\")].slice(0, 2);\n return letters.join(\"\").toUpperCase();\n}\n\n/**\n * The workspaces whose label or second line contains every word of `query`, ignoring case and\n * accents, in the order given. An empty query keeps them all. For the switcher's search box, on\n * the web and on the phone.\n *\n * @stability Beta\n */\nexport function filterWorkspaces<W extends Workspace>(workspaces: readonly W[], query: string): W[] {\n const words = fold(query).split(/\\s+/).filter(Boolean);\n if (words.length === 0) return [...workspaces];\n return workspaces.filter((w) => {\n const text = fold(`${w.label} ${w.description ?? \"\"}`);\n return words.every((word) => text.includes(word));\n });\n}\n\nfunction fold(text: string): string {\n return text.normalize(\"NFD\").replace(/\\p{M}/gu, \"\").toLowerCase();\n}\n\n/**\n * The workspaces in the order the switcher lists them (grouped by kind, in `order`): the order its\n * keyboard jump numbers them, 1 to 9.\n *\n * @stability Beta\n */\nexport function orderedWorkspaces<W extends Workspace>(\n workspaces: readonly W[],\n order: readonly WorkspaceKind[] = WORKSPACE_KIND_ORDER,\n): W[] {\n return groupWorkspaces(workspaces, order).flatMap((g) => g.workspaces);\n}\n"]}
|
package/dist/chunk-YDMKMNDS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schema/types.ts"],"names":[],"mappings":";AA+IO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC","file":"chunk-YDMKMNDS.js","sourcesContent":["// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType as WidgetHint } from \"../form-types\";\n\nexport type { WidgetHint };\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /** Which control fits this field. A hint: a UI may still choose another. */\n readonly widget?: WidgetHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /**\n * The version field the resource's writes are checked against, asked per\n * resource (`capabilities(resource)`). Present only with `versionedWrites`.\n * The Genesis write hooks send `String(row[version.field])` from the row\n * they last read as `expectedVersion`, so an edit made on a stale copy is\n * refused as a `conflict` instead of overwriting someone else's.\n */\n readonly version?: VersionField;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n"]}
|