@marktiderman/genesis-core 2.17.0 → 2.18.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-v_r-nZbH.d.ts → aggregate-CUirs7ka.d.ts} +1 -1
- package/dist/{chunk-UNEZF3ZP.js → chunk-5PCGMSDX.js} +209 -28
- package/dist/chunk-5PCGMSDX.js.map +1 -0
- package/dist/{chunk-JNWTHDGF.js → chunk-AOIVTOHX.js} +3 -3
- package/dist/{chunk-JNWTHDGF.js.map → chunk-AOIVTOHX.js.map} +1 -1
- package/dist/{chunk-FBMKI22S.js → chunk-ATVK3VYS.js} +3 -3
- package/dist/{chunk-FBMKI22S.js.map → chunk-ATVK3VYS.js.map} +1 -1
- package/dist/{chunk-NOPS5EIH.js → chunk-CJ5V6JES.js} +5 -114
- package/dist/chunk-CJ5V6JES.js.map +1 -0
- package/dist/{chunk-TWLPC4S3.js → chunk-DJRT4DUF.js} +3 -3
- package/dist/{chunk-TWLPC4S3.js.map → chunk-DJRT4DUF.js.map} +1 -1
- package/dist/{chunk-WNOCPV4A.js → chunk-DTVYCATJ.js} +3 -3
- package/dist/{chunk-WNOCPV4A.js.map → chunk-DTVYCATJ.js.map} +1 -1
- package/dist/chunk-LYNIHY3F.js +115 -0
- package/dist/chunk-LYNIHY3F.js.map +1 -0
- package/dist/{chunk-6B4CN2TC.js → chunk-OCMYW2YE.js} +3 -3
- package/dist/{chunk-6B4CN2TC.js.map → chunk-OCMYW2YE.js.map} +1 -1
- package/dist/{chunk-AQX5HQD6.js → chunk-OTUTSAZD.js} +3 -3
- package/dist/{chunk-AQX5HQD6.js.map → chunk-OTUTSAZD.js.map} +1 -1
- package/dist/{chunk-KRRESUXT.js → chunk-PH25HOAL.js} +6 -6
- package/dist/{chunk-KRRESUXT.js.map → chunk-PH25HOAL.js.map} +1 -1
- package/dist/{chunk-XIBQ5BTZ.js → chunk-RZVLUUMY.js} +4 -4
- package/dist/{chunk-XIBQ5BTZ.js.map → chunk-RZVLUUMY.js.map} +1 -1
- package/dist/{chunk-2ORQLYVW.js → chunk-SMEG63MO.js} +4 -4
- package/dist/{chunk-2ORQLYVW.js.map → chunk-SMEG63MO.js.map} +1 -1
- package/dist/{chunk-YMFJLBIZ.js → chunk-UKJCF2CM.js} +3 -3
- package/dist/{chunk-YMFJLBIZ.js.map → chunk-UKJCF2CM.js.map} +1 -1
- package/dist/{chunk-K33LWVUF.js → chunk-UKWM32CG.js} +3 -3
- package/dist/{chunk-K33LWVUF.js.map → chunk-UKWM32CG.js.map} +1 -1
- package/dist/csv.d.ts +1 -1
- package/dist/errors.js +2 -1
- package/dist/form-types.d.ts +1 -1
- package/dist/headless/index.d.ts +1 -1
- package/dist/hooks/index.d.ts +4 -4
- package/dist/hooks/index.js +13 -12
- package/dist/hooks/mutation-mode.d.ts +1 -1
- package/dist/hooks/mutation-mode.js +3 -2
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-aggregate.d.ts +2 -2
- package/dist/hooks/use-board-columns.d.ts +1 -1
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-list-state.d.ts +3 -3
- package/dist/hooks/use-list-state.js +5 -4
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-resource-form.d.ts +1 -1
- package/dist/hooks/use-resource-form.js +4 -3
- package/dist/hooks/use-resource.d.ts +1 -1
- package/dist/hooks/use-resource.js +4 -3
- package/dist/hooks/use-segment-counts.d.ts +2 -2
- package/dist/hooks/use-segment-counts.js +5 -4
- package/dist/hooks/use-view-board.d.ts +2 -2
- package/dist/hooks/use-view-board.js +8 -7
- package/dist/hooks/use-view-calendar-range.d.ts +2 -2
- package/dist/hooks/use-view-calendar-range.js +6 -5
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +15 -14
- package/dist/index.js.map +1 -1
- package/dist/provider/index.d.ts +7 -378
- package/dist/provider/index.js +3 -2
- package/dist/{write-outcome-DuwfsnyO.d.ts → read-outcome-Cq0h2oAG.d.ts} +31 -2
- package/dist/resource-view/index.d.ts +4 -4
- package/dist/resource-view/index.js +5 -4
- package/dist/resource-view/index.js.map +1 -1
- package/dist/{saved-views-C45lRm7i.d.ts → saved-views-Bcox3blZ.d.ts} +2 -2
- package/dist/schema/index.d.ts +3 -4
- package/dist/supabase-provider-D5ditkHi.d.ts +465 -0
- package/dist/testing/index.d.ts +87 -3
- package/dist/testing/index.js +88 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/{types-CiQY6hUy.d.ts → types-BnOCVJzm.d.ts} +1 -1
- package/dist/{types-BAhcze_-.d.ts → types-CBtBvGw0.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-NOPS5EIH.js.map +0 -1
- package/dist/chunk-UNEZF3ZP.js.map +0 -1
- package/dist/read-outcome-BnboMYOV.d.ts +0 -30
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/testing/index.ts"],"names":[],"mappings":";;;;AAmBO,IAAM,aAAA,GAAgB;AAAA,EAC3B,KAAA,EAAO,sCAAA;AAAA,EACP,KAAA,EAAO,sCAAA;AAAA,EACP,MAAA,EAAQ,sCAAA;AAAA,EACR,QAAA,EAAU;AACZ;AAKO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AAQA,eAAsB,kBAAA,CACpB,MACA,OAAA,EACiB;AACjB,EAAA,MAAM,GAAA,GAAM,OAAO,MAAA,CAAO,aAAA,EAAe,IAAI,CAAA,GAAI,aAAA,CAAc,IAAmB,CAAA,GAAI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O,QAAA,EAAU,EAAE,IAAI,CAAA;AAAA,EAClC,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,CAAC,gBAAgB,KAAK,CAAA,IAAM,MAAM,OAAA,KAAY,MAAA,IAAU,KAAA,CAAM,OAAA,KAAY,WAAA,EAAc;AAC1F,MAAA,MAAM,IAAI,aAAA,CAAc,CAAA,wBAAA,EAA2B,aAAA,CAAc,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,IAC3E;AACA,IAAA,IAAI,CAAE,MAAM,KAAA,EAAM,EAAI,MAAM,IAAI,aAAA,CAAc,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,iCAAA,CAAmC,CAAA;AAC1G,IAAA;AAAA,EACF;AACA,EAAA,MAAM,IAAI,cAAc,CAAA,EAAG,QAAQ,IAAI,MAAA,CAAO,EAAE,CAAC,CAAA,kCAAA,CAAoC,CAAA;AACvF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Contract test kit (README \"Test your data contract\")\n//\n// Checks an app's own provider keeps the Genesis data rules, run against the\n// app's real schema (a local Supabase in CI): a write the user may not make is\n// refused in plain words, a column only the server sets stays as it was, a\n// private value never shows, a binned delete keeps the row. The pgTAP half is\n// genesis-supabase's `genesis_testing`; both use the same fixture people.\n//\n// Every check passes only on evidence and throws a ContractError otherwise, so\n// it works in vitest, jest or node:test alike. A wrong resource, a missing row\n// or a typo fails the check instead of passing it.\n// ---------------------------------------------------------------------------\n\nimport type { BaseRecord, DataProvider, Identifier } from \"../provider/types\";\nimport { isDataReadError } from \"../schema/read-outcome\";\nimport { isDataWriteError, type DataWriteError } from \"../schema/write-outcome\";\n\n/** The shared fixture logins, the same ids `genesis_testing.user_id()` uses. */\nexport const FIXTURE_USERS = {\n owner: \"00000000-0000-4000-8000-000000000001\",\n staff: \"00000000-0000-4000-8000-000000000002\",\n client: \"00000000-0000-4000-8000-000000000003\",\n stranger: \"00000000-0000-4000-8000-000000000004\",\n} as const;\n\nexport type FixtureUser = keyof typeof FIXTURE_USERS;\n\n/** A broken contract: the message says what happened instead. */\nexport class ContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ContractError\";\n }\n}\n\n/**\n * A signed access token for a fixture person (or any user id), for a test\n * database's legacy JWT secret. Hand it to the client as\n * `Authorization: Bearer <token>`; `auth.uid()` then reads that user. Test\n * databases only: never give it a production secret.\n */\nexport async function fixtureAccessToken(\n user: FixtureUser | string,\n options: { secret: string; expiresInSeconds?: number; role?: string },\n): Promise<string> {\n const sub = Object.hasOwn(FIXTURE_USERS, user) ? FIXTURE_USERS[user as FixtureUser] : user;\n const now = Math.floor(Date.now() / 1000);\n const role = options.role ?? \"authenticated\";\n const claims = { sub, role, aud: role, iat: now, exp: now + (options.expiresInSeconds ?? 3600) };\n const encode = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n const text = (value: unknown) => encode(new TextEncoder().encode(JSON.stringify(value)));\n const body = `${text({ alg: \"HS256\", typ: \"JWT\" })}.${text(claims)}`;\n const key = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(options.secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(body));\n return `${body}.${encode(new Uint8Array(signature))}`;\n}\n\n/** Raw database text that must never reach a person. */\nconst RAW_TEXT =\n /violates|constraint|duplicate key|row-level security|permission denied for|relation \"|syntax error|null value in column|\\b(?:42501|42P01|42703|23505|23503|23502|23514|22P02|P0001|PGRST[0-9]{3})\\b/i;\n\n/** The error's message is plain words: no raw database text or error codes. */\nexport function expectPlainMessage(error: unknown): void {\n const message =\n error instanceof Error\n ? error.message\n : error && typeof error === \"object\" && typeof (error as { message?: unknown }).message === \"string\"\n ? (error as { message: string }).message\n : typeof error === \"string\"\n ? error\n : \"\";\n if (!message.trim()) throw new ContractError(\"the error has no message to show\");\n if (RAW_TEXT.test(message)) throw new ContractError(`the message shows raw database text: ${message}`);\n}\n\n/** Codes that are refusals: insufficient privilege (RLS, grants) and a guard's `raise exception`. */\nconst REFUSAL_CODES = new Set([\"42501\", \"P0001\"]);\n\n/**\n * Whether a failed write is a refusal: a refusal code (42501, P0001), or the\n * provider's own `forbidden` (the row is still visible but unchanged) or\n * `unauthenticated`. `gone` is not: it also means the id matched nothing.\n */\nexport function isRefusal(error: unknown): error is DataWriteError {\n if (!isDataWriteError(error)) return false;\n if (error.code !== undefined && REFUSAL_CODES.has(error.code)) return true;\n return error.outcome === \"forbidden\" || error.outcome === \"unauthenticated\";\n}\n\nconst describeError = (error: unknown) =>\n isDataWriteError(error) || isDataReadError(error)\n ? `${error.outcome}${error.code ? ` (${error.code})` : \"\"}: ${error.message}`\n : String(error);\n\n/** Whether a write's result shows a row it changed: `{ data: row }` or a non-empty `data` list, with no `error`. */\nfunction changedARow(result: unknown): boolean {\n if (!result || typeof result !== \"object\") return false;\n const r = result as { data?: unknown; error?: unknown };\n if (r.error !== undefined && r.error !== null) return false;\n if (Array.isArray(r.data)) return r.data.length > 0;\n return r.data !== null && typeof r.data === \"object\";\n}\n\nexport interface ExpectRefusedOptions {\n /** With a write function: who tries it (and must be refused). */\n as?: DataProvider;\n /**\n * Proof a write that reached no row (`gone`) was refused, not mistyped.\n * With a write function: a provider for someone who may make it, which runs\n * the same function. With a promise: a function making the same write as\n * that someone. Either way it must resolve with the row it changed. Its\n * write is real: run the check on test data.\n */\n control?: DataProvider | (() => Promise<unknown>);\n}\n\n/**\n * The write is refused, in plain words: a refusal code (42501, P0001) or the\n * provider's `forbidden` / `unauthenticated`. A write that reaches no row\n * (`gone`) counts only with a `control` that makes the same write and changes\n * a row, so a typo'd id or resource can't pass. Pass the write as a function\n * of a provider (with `as` and a control provider) to run exactly the same\n * write both ways. Returns the refusal for more checks.\n *\n * ```ts\n * await expectRefused((p) => p.update(\"tasks\", { id, data: { title: \"x\" } }), { as: stranger, control: owner });\n * ```\n */\nexport async function expectRefused(\n write: Promise<unknown> | ((provider: DataProvider) => Promise<unknown>),\n options: ExpectRefusedOptions = {},\n): Promise<DataWriteError> {\n // A write promise may reject before an argument check below throws: mark it handled now\n // (awaiting it later still sees the rejection).\n if (typeof write !== \"function\") void write.catch(() => undefined);\n let attempt: Promise<unknown>;\n let control: (() => Promise<unknown>) | undefined;\n if (typeof write === \"function\") {\n if (!options.as) throw new ContractError(\"pass `as`: the provider that should be refused\");\n const by = options.control;\n if (by !== undefined && typeof by === \"function\") {\n throw new ContractError(\"with a write function, `control` is a provider that runs the same write\");\n }\n attempt = write(options.as);\n control = by ? () => write(by) : undefined;\n } else {\n attempt = write;\n if (options.control !== undefined && typeof options.control !== \"function\") {\n throw new ContractError(\"with a write promise, `control` is a function making the same write\");\n }\n control = options.control;\n }\n let result: unknown;\n try {\n result = await attempt;\n } catch (error) {\n if (isRefusal(error)) {\n expectPlainMessage(error);\n return error;\n }\n if (isDataWriteError(error) && error.outcome === \"gone\") {\n if (!control) {\n throw new ContractError(\n `it reached no row (${error.message}); pass a control that can make the same write, or it could be a wrong id`,\n );\n }\n let controlResult: unknown;\n try {\n controlResult = await control();\n } catch (controlError) {\n throw new ContractError(`the control failed too (${describeError(controlError)}): nothing was refused`);\n }\n if (!changedARow(controlResult)) {\n throw new ContractError(\n `the control changed no row (${JSON.stringify(controlResult)?.slice(0, 200)}): nothing was refused`,\n );\n }\n expectPlainMessage(error);\n return error;\n }\n throw new ContractError(`it failed, but not as a refusal: ${describeError(error)}`);\n }\n throw new ContractError(`it was allowed: ${JSON.stringify(result)?.slice(0, 300)}`);\n}\n\n/** The write succeeds. Returns what it resolved to. */\nexport async function expectAllowed<T>(write: Promise<T>): Promise<T> {\n try {\n return await write;\n } catch (error) {\n throw new ContractError(`it was refused: ${describeError(error)}`);\n }\n}\n\nconst stable = (value: unknown) =>\n JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : 1)))\n : v,\n );\n\n/**\n * A client can't change a column only the server sets. First `system` (the\n * service role, or whoever the server writes as) sets `field` to `value` and\n * must change the stored value, then puts it back: that proves the row exists\n * and the value can change at all. Then `as` tries the same update, and the\n * stored value must stay as it was, whether the update was refused, reached\n * no row, or a trigger put the value back. Any other error fails.\n */\nexport async function expectServerOwned(args: {\n as: DataProvider;\n system: DataProvider;\n resource: string;\n id: Identifier;\n field: string;\n value: unknown;\n}): Promise<void> {\n const { as, system, resource, id, field, value } = args;\n const read = async () => {\n const row = (await system.getOne<BaseRecord>(resource, { id })).data;\n if (!row || !(field in row)) throw new ContractError(`${resource} ${String(id)} has no field ${field}`);\n return row[field];\n };\n const before = await read();\n if (stable(before) === stable(value)) {\n throw new ContractError(`${field} is already ${stable(value)}: try a different value`);\n }\n const set = async (to: unknown, what: string) => {\n try {\n await system.update(resource, { id, data: { [field]: to } });\n } catch (error) {\n throw new ContractError(`the system couldn't ${what} ${field} (${describeError(error)}): nothing was tested`);\n }\n };\n await set(value, \"set\");\n const changed = await read();\n await set(before, \"put back\");\n if (stable(changed) === stable(before)) {\n throw new ContractError(`the system couldn't change ${field} either: nothing was tested`);\n }\n if (stable(await read()) !== stable(before)) {\n throw new ContractError(`the system couldn't put ${field} back to ${stable(before)}`);\n }\n try {\n await as.update(resource, { id, data: { [field]: value } });\n } catch (error) {\n if (!isRefusal(error) && !(isDataWriteError(error) && error.outcome === \"gone\")) {\n throw new ContractError(`setting ${field} failed, but not as a refusal: ${describeError(error)}`);\n }\n }\n const after = await read();\n if (stable(after) !== stable(before)) {\n // Put the value back, so a failed check doesn't change what the next one sees.\n await system.update(resource, { id, data: { [field]: before } }).catch(() => undefined);\n throw new ContractError(`${resource}.${field} changed from ${stable(before)} to ${stable(after)}`);\n }\n}\n\n/**\n * `marker` (a value only a private row holds) appears nowhere in what the read\n * returns: use a list or report read that returns the rows around the private\n * one. A refused read (42501, or `forbidden` / `unauthenticated`) shows\n * nothing and passes; any other failure fails, `gone` included, so a wrong id\n * or a broken query can't pass.\n */\nexport async function expectNeverShows(read: Promise<unknown>, marker: string): Promise<void> {\n if (!marker) throw new ContractError(\"give a marker to look for\");\n let result: unknown;\n try {\n result = await read;\n } catch (error) {\n const refused =\n (isDataReadError(error) || isDataWriteError(error)) &&\n ((error.code !== undefined && REFUSAL_CODES.has(error.code)) ||\n error.outcome === \"forbidden\" ||\n error.outcome === \"unauthenticated\");\n if (refused) return;\n throw new ContractError(`the read failed: ${describeError(error)}`);\n }\n if (result === undefined) throw new ContractError(\"the read returned nothing to look through\");\n if (result && typeof result === \"object\" && \"error\" in result && (result as { error: unknown }).error != null) {\n throw new ContractError(`the read failed: ${JSON.stringify((result as { error: unknown }).error)?.slice(0, 200)}`);\n }\n const text = JSON.stringify(result) ?? \"\";\n const escaped = JSON.stringify(marker).slice(1, -1);\n if (text.includes(marker) || text.includes(escaped)) {\n throw new ContractError(`\"${marker}\" appears in: ${text.slice(0, 300)}`);\n }\n}\n\n/** The read returns exactly `expected` rows (a list result, a getMany result or an array). */\nexport async function expectSees(read: Promise<unknown>, expected: number): Promise<void> {\n let result: unknown;\n try {\n result = await read;\n } catch (error) {\n throw new ContractError(`the read failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n const rows = Array.isArray(result)\n ? result\n : result && typeof result === \"object\" && Array.isArray((result as { data?: unknown }).data)\n ? (result as { data: unknown[] }).data\n : undefined;\n if (!rows) throw new ContractError(`the read returned no rows to count: ${JSON.stringify(result)?.slice(0, 300)}`);\n if (rows.length !== expected) throw new ContractError(`saw ${rows.length} row(s), expected ${expected}`);\n}\n\n/**\n * A delete on a recycle-bin table moves the row to the bin: `as` deletes it,\n * can no longer read it (gone or forbidden), and `inBin` (a check with the\n * service role or a bin query) confirms the row is still stored.\n */\nexport async function expectBinned(args: {\n as: DataProvider;\n resource: string;\n id: Identifier;\n inBin: () => Promise<boolean>;\n}): Promise<void> {\n const { as, resource, id, inBin } = args;\n // Visible first, so \"can't read it back\" is evidence of the delete.\n try {\n await as.getOne(resource, { id });\n } catch (error) {\n throw new ContractError(`${resource} ${String(id)} isn't visible before the delete: ${describeError(error)}`);\n }\n await expectAllowed(as.deleteOne(resource, { id }));\n try {\n await as.getOne(resource, { id });\n } catch (error) {\n if (!isDataReadError(error) || (error.outcome !== \"gone\" && error.outcome !== \"forbidden\")) {\n throw new ContractError(`reading it back failed: ${describeError(error)}`);\n }\n if (!(await inBin())) throw new ContractError(`${resource} ${String(id)} was deleted for good, not binned`);\n return;\n }\n throw new ContractError(`${resource} ${String(id)} is still visible after the delete`);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/testing/access-rules.ts","../../src/testing/index.ts"],"names":[],"mappings":";;;;;;AAwDA,SAAS,cAAc,KAAA,EAAyB;AAC9C,EAAA,MAAM,MAAA,GAAS,iBAAiB,KAAK,CAAA;AACrC,EAAA,IAAI,OAAO,IAAA,KAAS,OAAA,IAAW,MAAA,CAAO,IAAA,KAAS,SAAS,OAAO,IAAA;AAC/D,EAAA,OAAO,OAAO,OAAA,KAAY,WAAA;AAC5B;AAEA,IAAM,iBAAA,GAAoB,CAAC,IAAA,KACzB,EAAE,SAAS,IAAA,IAAQ,IAAA,KAAS,MAAA,IAAa,IAAA,KAAS,SAAU,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAA,IAAK,KAAK,MAAA,KAAW,CAAA,CAAA;AAkB9F,SAAS,YAAgC,IAAA,EAAkD;AAChG,EAAA,IAAI,CAAC,KAAK,EAAA,CAAG,IAAA,IAAQ,MAAM,IAAI,cAAc,6CAA6C,CAAA;AAC1F,EAAA,IAAI,IAAA,CAAK,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG;AAC7B,IAAA,MAAM,IAAI,aAAA,CAAc,CAAA,YAAA,EAAe,IAAA,CAAK,EAAE,CAAA,sDAAA,CAAwD,CAAA;AAAA,EACxG;AACA,EAAA,IA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cAAc,EAAA,CAAG,SAAA,CAAU,UAAU,EAAE,EAAA,EAAI,CAAC,CAAA;AAClD,EAAA,IAAI;AACF,IAAA,MAAM,EAAA,CAAG,MAAA,CAAO,QAAA,EAAU,EAAE,IAAI,CAAA;AAAA,EAClC,SAAS,KAAA,EAAO;AACd,IAAA,IAAI,CAAC,gBAAgB,KAAK,CAAA,IAAM,MAAM,OAAA,KAAY,MAAA,IAAU,KAAA,CAAM,OAAA,KAAY,WAAA,EAAc;AAC1F,MAAA,MAAM,IAAI,aAAA,CAAc,CAAA,wBAAA,EAA2B,aAAA,CAAc,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,IAC3E;AACA,IAAA,IAAI,CAAE,MAAM,KAAA,EAAM,EAAI,MAAM,IAAI,aAAA,CAAc,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,iCAAA,CAAmC,CAAA;AAC1G,IAAA;AAAA,EACF;AACA,EAAA,MAAM,IAAI,cAAc,CAAA,EAAG,QAAQ,IAAI,MAAA,CAAO,EAAE,CAAC,CAAA,kCAAA,CAAoC,CAAA;AACvF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Access-rule tests (docs/DATA-ACCESS.md, \"Test every function's access rule\")\n//\n// Every database function a resource writes through (`writes`, `actions`) or reads through\n// (`source: { rpc }`) holds an access rule: who may call it. `accessRules` turns one function's\n// rule into test cases, one per person: each allowed person's call must act, each refused\n// person's call must be refused. Runner-neutral: register the cases with vitest, jest or\n// node:test. `expectAccessRulesCover` fails for a declared function whose name is missing from the\n// specs it is given (a name check: pass it the specs the cases are registered from), and the\n// doctor's `data/access-rule-tests` rule checks that some test calls it.\n// ---------------------------------------------------------------------------\n\nimport { toDataWriteError } from \"../provider/postgrest-errors\";\nimport type { SupabaseProviderOptions } from \"../provider/supabase-provider\";\nimport { ContractError } from \"./index\";\n\n/** The part of a Supabase client an access-rule test calls: any real client's `rpc` fits. */\nexport interface AccessRuleClient {\n rpc(fn: string, args?: Record<string, unknown>): unknown;\n}\n\n/** One function's access rule: who may call it, who may not, and the arguments for a call. */\nexport interface AccessRuleSpec<Who extends string> {\n /** The database function under test, as the resource declares it. */\n readonly fn: string;\n /** A client signed in as `who`: the app's own test people (a local stack's seeded logins, say). */\n readonly as: (who: Who) => AccessRuleClient | Promise<AccessRuleClient>;\n /**\n * The arguments for one call by `who`, made fresh for each case (a row of its own to change, so\n * one allowed call never changes what the next case sees).\n */\n readonly args: (who: Who) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /** Who may call it. At least one: a rule that admits no one tests nothing. */\n readonly allowed: readonly Who[];\n /** Who may not. At least one: a rule that refuses no one is not a rule. */\n readonly refused: readonly Who[];\n /**\n * Whether a call's answer shows it acted. Default: anything but `null`, `false` or an empty list,\n * the same answers the provider reads as \"no row matched\".\n */\n readonly acted?: (data: unknown) => boolean;\n}\n\n/** One test case: register it as `test(c.name, c.run)`. */\nexport interface AccessRuleCase<Who extends string = string> {\n readonly name: string;\n readonly who: Who;\n readonly expect: \"allowed\" | \"refused\";\n run(): Promise<void>;\n}\n\n/**\n * Whether an error is the function refusing: insufficient privilege (42501), a guard's raise\n * (P0001), or another forbidden answer. Not a failed sign-in (an expired or malformed token): that\n * never reached the rule, so it proves nothing about it.\n */\nfunction refusedByRule(error: unknown): boolean {\n const mapped = toDataWriteError(error);\n if (mapped.code === \"42501\" || mapped.code === \"P0001\") return true;\n return mapped.outcome === \"forbidden\";\n}\n\nconst answeredSomething = (data: unknown): boolean =>\n !(data === null || data === undefined || data === false || (Array.isArray(data) && data.length === 0));\n\n/**\n * The test cases for one function's access rule. An allowed person's call must succeed and act; a\n * refused person's call must be refused (an insufficient-privilege or guard error, 42501 or P0001)\n * or act on nothing. Any other error fails the case, so a wrong name or wrong arguments can't pass\n * as a refusal, and the allowed cases prove the same arguments do work.\n *\n * ```ts\n * for (const c of accessRules({\n * fn: \"save_task\",\n * as: (who) => signedIn(who),\n * args: async () => ({ p_id: await newTask(), p_values: { title: \"Renamed\" } }),\n * allowed: [\"owner\", \"admin\"],\n * refused: [\"member\", \"stranger\"],\n * })) test(c.name, c.run);\n * ```\n */\nexport function accessRules<Who extends string>(spec: AccessRuleSpec<Who>): AccessRuleCase<Who>[] {\n if (!spec.fn.trim()) throw new ContractError(\"accessRules needs the function's name (fn).\");\n if (spec.allowed.length === 0) {\n throw new ContractError(`accessRules(${spec.fn}): name at least one person who may call it (allowed).`);\n }\n if (spec.refused.length === 0) {\n throw new ContractError(`accessRules(${spec.fn}): name at least one person who may not call it (refused).`);\n }\n const both = spec.allowed.filter((who) => spec.refused.includes(who));\n if (both.length > 0) {\n throw new ContractError(`accessRules(${spec.fn}): ${both.join(\", \")} is both allowed and refused.`);\n }\n const acted = spec.acted ?? answeredSomething;\n\n const call = async (who: Who): Promise<{ data: unknown; error: unknown }> => {\n const client = await spec.as(who);\n const args = await spec.args(who);\n try {\n return (await client.rpc(spec.fn, args)) as { data: unknown; error: unknown };\n } catch (error) {\n return { data: null, error };\n }\n };\n const describe = (error: unknown): string => {\n const mapped = toDataWriteError(error);\n return `${mapped.outcome}${mapped.code ? ` (${mapped.code})` : \"\"}: ${mapped.message}`;\n };\n\n const allowed = spec.allowed.map(\n (who): AccessRuleCase<Who> => ({\n name: `${spec.fn}: ${who} may call it`,\n who,\n expect: \"allowed\",\n async run() {\n const { data, error } = await call(who);\n if (error) throw new ContractError(`${spec.fn} refused ${who}, who should be allowed: ${describe(error)}`);\n if (!acted(data)) throw new ContractError(`${spec.fn} acted on nothing for ${who}, who should be allowed.`);\n },\n }),\n );\n const refused = spec.refused.map(\n (who): AccessRuleCase<Who> => ({\n name: `${spec.fn}: ${who} is refused`,\n who,\n expect: \"refused\",\n async run() {\n const { data, error } = await call(who);\n if (error) {\n if (refusedByRule(error)) return;\n throw new ContractError(`${spec.fn} failed for ${who} with an error that isn't a refusal: ${describe(error)}`);\n }\n if (acted(data)) throw new ContractError(`${spec.fn} acted for ${who}, who should be refused.`);\n },\n }),\n );\n return [...allowed, ...refused];\n}\n\n// ---------------------------------------------------------------------------\n// Coverage: every function the provider declares has an access-rule test\n// ---------------------------------------------------------------------------\n\n/** One database function a Supabase resource declares, read from the provider's options. */\nexport interface DeclaredFunction {\n /** The resource that declares it, as `resources` names it. */\n readonly resource: string;\n /** Where: a write (`create`, `update`, `delete`), an action (its name), or the read (`source`). */\n readonly use: \"create\" | \"update\" | \"delete\" | \"source\" | `action:${string}`;\n /** The database function's name. */\n readonly fn: string;\n}\n\n/** The name a `FunctionCall` calls: the string itself, or its `fn`. */\nconst fnOf = (call: string | { readonly fn: string }): string => (typeof call === \"string\" ? call : call.fn);\n\n/**\n * Every database function the provider's resources declare: their `writes`, their `actions` and a\n * `source: { rpc }`. Read from the options themselves, so nothing a resource declares is missed and\n * nothing else is counted.\n */\nexport function declaredFunctions(options: Pick<SupabaseProviderOptions, \"resources\">): DeclaredFunction[] {\n const out: DeclaredFunction[] = [];\n for (const [resource, config] of Object.entries(options.resources ?? {})) {\n for (const use of [\"create\", \"update\", \"delete\"] as const) {\n const call = config.writes?.[use];\n if (call) out.push({ resource, use, fn: fnOf(call) });\n }\n for (const [name, call] of Object.entries(config.actions ?? {})) out.push({ resource, use: `action:${name}`, fn: fnOf(call) });\n if (config.source && typeof config.source === \"object\") out.push({ resource, use: \"source\", fn: config.source.rpc });\n }\n return out;\n}\n\n/**\n * Fails, naming each one, when a function the provider declares has no spec among `tested`. It\n * compares names only, so pass it the specs the access-rule cases are registered from, with the\n * options the app's provider is made from:\n *\n * ```ts\n * const specs = [saveTask, createTask, archiveTask];\n * for (const spec of specs) for (const c of accessRules(spec)) test(c.name, c.run);\n * test(\"every declared function has an access-rule test\", () => {\n * expectAccessRulesCover(providerOptions, specs);\n * });\n * ```\n *\n * The doctor's `data/access-rule-tests` rule checks that a test suite calls it.\n */\nexport function expectAccessRulesCover(\n options: Pick<SupabaseProviderOptions, \"resources\">,\n tested: readonly (string | { readonly fn: string })[],\n): void {\n const covered = new Set(tested.map(fnOf));\n const missing = declaredFunctions(options).filter((d) => !covered.has(d.fn));\n if (missing.length === 0) return;\n const list = missing.map((d) => `${d.fn} (${d.resource} ${d.use})`).join(\", \");\n throw new ContractError(\n `No access-rule test for ${missing.length === 1 ? \"this declared function\" : `these ${missing.length} declared functions`}: ${list}. ` +\n `Give each one accessRules({ fn, allowed, refused, … }) and pass its spec here (docs/DATA-ACCESS.md).`,\n );\n}\n","// ---------------------------------------------------------------------------\n// Contract test kit (README \"Test your data contract\")\n//\n// Checks an app's own provider keeps the Genesis data rules, run against the\n// app's real schema (a local Supabase in CI): a write the user may not make is\n// refused in plain words, a column only the server sets stays as it was, a\n// private value never shows, a binned delete keeps the row. The pgTAP half is\n// genesis-supabase's `genesis_testing`; both use the same fixture people.\n//\n// Every check passes only on evidence and throws a ContractError otherwise, so\n// it works in vitest, jest or node:test alike. A wrong resource, a missing row\n// or a typo fails the check instead of passing it.\n// ---------------------------------------------------------------------------\n\nimport type { BaseRecord, DataProvider, Identifier } from \"../provider/types\";\nimport { isDataReadError } from \"../schema/read-outcome\";\nimport { isDataWriteError, type DataWriteError } from \"../schema/write-outcome\";\n\n/** The shared fixture logins, the same ids `genesis_testing.user_id()` uses. */\nexport const FIXTURE_USERS = {\n owner: \"00000000-0000-4000-8000-000000000001\",\n staff: \"00000000-0000-4000-8000-000000000002\",\n client: \"00000000-0000-4000-8000-000000000003\",\n stranger: \"00000000-0000-4000-8000-000000000004\",\n} as const;\n\nexport type FixtureUser = keyof typeof FIXTURE_USERS;\n\n/** A broken contract: the message says what happened instead. */\nexport class ContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ContractError\";\n }\n}\n\n/**\n * A signed access token for a fixture person (or any user id), for a test\n * database's legacy JWT secret. Hand it to the client as\n * `Authorization: Bearer <token>`; `auth.uid()` then reads that user. Test\n * databases only: never give it a production secret.\n */\nexport async function fixtureAccessToken(\n user: FixtureUser | string,\n options: { secret: string; expiresInSeconds?: number; role?: string },\n): Promise<string> {\n const sub = Object.hasOwn(FIXTURE_USERS, user) ? FIXTURE_USERS[user as FixtureUser] : user;\n const now = Math.floor(Date.now() / 1000);\n const role = options.role ?? \"authenticated\";\n const claims = { sub, role, aud: role, iat: now, exp: now + (options.expiresInSeconds ?? 3600) };\n const encode = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n const text = (value: unknown) => encode(new TextEncoder().encode(JSON.stringify(value)));\n const body = `${text({ alg: \"HS256\", typ: \"JWT\" })}.${text(claims)}`;\n const key = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(options.secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(body));\n return `${body}.${encode(new Uint8Array(signature))}`;\n}\n\n/** Raw database text that must never reach a person. */\nconst RAW_TEXT =\n /violates|constraint|duplicate key|row-level security|permission denied for|relation \"|syntax error|null value in column|\\b(?:42501|42P01|42703|23505|23503|23502|23514|22P02|P0001|PGRST[0-9]{3})\\b/i;\n\n/** The error's message is plain words: no raw database text or error codes. */\nexport function expectPlainMessage(error: unknown): void {\n const message =\n error instanceof Error\n ? error.message\n : error && typeof error === \"object\" && typeof (error as { message?: unknown }).message === \"string\"\n ? (error as { message: string }).message\n : typeof error === \"string\"\n ? error\n : \"\";\n if (!message.trim()) throw new ContractError(\"the error has no message to show\");\n if (RAW_TEXT.test(message)) throw new ContractError(`the message shows raw database text: ${message}`);\n}\n\n/** Codes that are refusals: insufficient privilege (RLS, grants) and a guard's `raise exception`. */\nconst REFUSAL_CODES = new Set([\"42501\", \"P0001\"]);\n\n/**\n * Whether a failed write is a refusal: a refusal code (42501, P0001), or the\n * provider's own `forbidden` (the row is still visible but unchanged) or\n * `unauthenticated`. `gone` is not: it also means the id matched nothing.\n */\nexport function isRefusal(error: unknown): error is DataWriteError {\n if (!isDataWriteError(error)) return false;\n if (error.code !== undefined && REFUSAL_CODES.has(error.code)) return true;\n return error.outcome === \"forbidden\" || error.outcome === \"unauthenticated\";\n}\n\nconst describeError = (error: unknown) =>\n isDataWriteError(error) || isDataReadError(error)\n ? `${error.outcome}${error.code ? ` (${error.code})` : \"\"}: ${error.message}`\n : String(error);\n\n/** Whether a write's result shows a row it changed: `{ data: row }` or a non-empty `data` list, with no `error`. */\nfunction changedARow(result: unknown): boolean {\n if (!result || typeof result !== \"object\") return false;\n const r = result as { data?: unknown; error?: unknown };\n if (r.error !== undefined && r.error !== null) return false;\n if (Array.isArray(r.data)) return r.data.length > 0;\n return r.data !== null && typeof r.data === \"object\";\n}\n\nexport interface ExpectRefusedOptions {\n /** With a write function: who tries it (and must be refused). */\n as?: DataProvider;\n /**\n * Proof a write that reached no row (`gone`) was refused, not mistyped.\n * With a write function: a provider for someone who may make it, which runs\n * the same function. With a promise: a function making the same write as\n * that someone. Either way it must resolve with the row it changed. Its\n * write is real: run the check on test data.\n */\n control?: DataProvider | (() => Promise<unknown>);\n}\n\n/**\n * The write is refused, in plain words: a refusal code (42501, P0001) or the\n * provider's `forbidden` / `unauthenticated`. A write that reaches no row\n * (`gone`) counts only with a `control` that makes the same write and changes\n * a row, so a typo'd id or resource can't pass. Pass the write as a function\n * of a provider (with `as` and a control provider) to run exactly the same\n * write both ways. Returns the refusal for more checks.\n *\n * ```ts\n * await expectRefused((p) => p.update(\"tasks\", { id, data: { title: \"x\" } }), { as: stranger, control: owner });\n * ```\n */\nexport async function expectRefused(\n write: Promise<unknown> | ((provider: DataProvider) => Promise<unknown>),\n options: ExpectRefusedOptions = {},\n): Promise<DataWriteError> {\n // A write promise may reject before an argument check below throws: mark it handled now\n // (awaiting it later still sees the rejection).\n if (typeof write !== \"function\") void write.catch(() => undefined);\n let attempt: Promise<unknown>;\n let control: (() => Promise<unknown>) | undefined;\n if (typeof write === \"function\") {\n if (!options.as) throw new ContractError(\"pass `as`: the provider that should be refused\");\n const by = options.control;\n if (by !== undefined && typeof by === \"function\") {\n throw new ContractError(\"with a write function, `control` is a provider that runs the same write\");\n }\n attempt = write(options.as);\n control = by ? () => write(by) : undefined;\n } else {\n attempt = write;\n if (options.control !== undefined && typeof options.control !== \"function\") {\n throw new ContractError(\"with a write promise, `control` is a function making the same write\");\n }\n control = options.control;\n }\n let result: unknown;\n try {\n result = await attempt;\n } catch (error) {\n if (isRefusal(error)) {\n expectPlainMessage(error);\n return error;\n }\n if (isDataWriteError(error) && error.outcome === \"gone\") {\n if (!control) {\n throw new ContractError(\n `it reached no row (${error.message}); pass a control that can make the same write, or it could be a wrong id`,\n );\n }\n let controlResult: unknown;\n try {\n controlResult = await control();\n } catch (controlError) {\n throw new ContractError(`the control failed too (${describeError(controlError)}): nothing was refused`);\n }\n if (!changedARow(controlResult)) {\n throw new ContractError(\n `the control changed no row (${JSON.stringify(controlResult)?.slice(0, 200)}): nothing was refused`,\n );\n }\n expectPlainMessage(error);\n return error;\n }\n throw new ContractError(`it failed, but not as a refusal: ${describeError(error)}`);\n }\n throw new ContractError(`it was allowed: ${JSON.stringify(result)?.slice(0, 300)}`);\n}\n\n/** The write succeeds. Returns what it resolved to. */\nexport async function expectAllowed<T>(write: Promise<T>): Promise<T> {\n try {\n return await write;\n } catch (error) {\n throw new ContractError(`it was refused: ${describeError(error)}`);\n }\n}\n\nconst stable = (value: unknown) =>\n JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : 1)))\n : v,\n );\n\n/**\n * A client can't change a column only the server sets. First `system` (the\n * service role, or whoever the server writes as) sets `field` to `value` and\n * must change the stored value, then puts it back: that proves the row exists\n * and the value can change at all. Then `as` tries the same update, and the\n * stored value must stay as it was, whether the update was refused, reached\n * no row, or a trigger put the value back. Any other error fails.\n */\nexport async function expectServerOwned(args: {\n as: DataProvider;\n system: DataProvider;\n resource: string;\n id: Identifier;\n field: string;\n value: unknown;\n}): Promise<void> {\n const { as, system, resource, id, field, value } = args;\n const read = async () => {\n const row = (await system.getOne<BaseRecord>(resource, { id })).data;\n if (!row || !(field in row)) throw new ContractError(`${resource} ${String(id)} has no field ${field}`);\n return row[field];\n };\n const before = await read();\n if (stable(before) === stable(value)) {\n throw new ContractError(`${field} is already ${stable(value)}: try a different value`);\n }\n const set = async (to: unknown, what: string) => {\n try {\n await system.update(resource, { id, data: { [field]: to } });\n } catch (error) {\n throw new ContractError(`the system couldn't ${what} ${field} (${describeError(error)}): nothing was tested`);\n }\n };\n await set(value, \"set\");\n const changed = await read();\n await set(before, \"put back\");\n if (stable(changed) === stable(before)) {\n throw new ContractError(`the system couldn't change ${field} either: nothing was tested`);\n }\n if (stable(await read()) !== stable(before)) {\n throw new ContractError(`the system couldn't put ${field} back to ${stable(before)}`);\n }\n try {\n await as.update(resource, { id, data: { [field]: value } });\n } catch (error) {\n if (!isRefusal(error) && !(isDataWriteError(error) && error.outcome === \"gone\")) {\n throw new ContractError(`setting ${field} failed, but not as a refusal: ${describeError(error)}`);\n }\n }\n const after = await read();\n if (stable(after) !== stable(before)) {\n // Put the value back, so a failed check doesn't change what the next one sees.\n await system.update(resource, { id, data: { [field]: before } }).catch(() => undefined);\n throw new ContractError(`${resource}.${field} changed from ${stable(before)} to ${stable(after)}`);\n }\n}\n\n/**\n * `marker` (a value only a private row holds) appears nowhere in what the read\n * returns: use a list or report read that returns the rows around the private\n * one. A refused read (42501, or `forbidden` / `unauthenticated`) shows\n * nothing and passes; any other failure fails, `gone` included, so a wrong id\n * or a broken query can't pass.\n */\nexport async function expectNeverShows(read: Promise<unknown>, marker: string): Promise<void> {\n if (!marker) throw new ContractError(\"give a marker to look for\");\n let result: unknown;\n try {\n result = await read;\n } catch (error) {\n const refused =\n (isDataReadError(error) || isDataWriteError(error)) &&\n ((error.code !== undefined && REFUSAL_CODES.has(error.code)) ||\n error.outcome === \"forbidden\" ||\n error.outcome === \"unauthenticated\");\n if (refused) return;\n throw new ContractError(`the read failed: ${describeError(error)}`);\n }\n if (result === undefined) throw new ContractError(\"the read returned nothing to look through\");\n if (result && typeof result === \"object\" && \"error\" in result && (result as { error: unknown }).error != null) {\n throw new ContractError(`the read failed: ${JSON.stringify((result as { error: unknown }).error)?.slice(0, 200)}`);\n }\n const text = JSON.stringify(result) ?? \"\";\n const escaped = JSON.stringify(marker).slice(1, -1);\n if (text.includes(marker) || text.includes(escaped)) {\n throw new ContractError(`\"${marker}\" appears in: ${text.slice(0, 300)}`);\n }\n}\n\n/** The read returns exactly `expected` rows (a list result, a getMany result or an array). */\nexport async function expectSees(read: Promise<unknown>, expected: number): Promise<void> {\n let result: unknown;\n try {\n result = await read;\n } catch (error) {\n throw new ContractError(`the read failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n const rows = Array.isArray(result)\n ? result\n : result && typeof result === \"object\" && Array.isArray((result as { data?: unknown }).data)\n ? (result as { data: unknown[] }).data\n : undefined;\n if (!rows) throw new ContractError(`the read returned no rows to count: ${JSON.stringify(result)?.slice(0, 300)}`);\n if (rows.length !== expected) throw new ContractError(`saw ${rows.length} row(s), expected ${expected}`);\n}\n\n/**\n * A delete on a recycle-bin table moves the row to the bin: `as` deletes it,\n * can no longer read it (gone or forbidden), and `inBin` (a check with the\n * service role or a bin query) confirms the row is still stored.\n */\nexport async function expectBinned(args: {\n as: DataProvider;\n resource: string;\n id: Identifier;\n inBin: () => Promise<boolean>;\n}): Promise<void> {\n const { as, resource, id, inBin } = args;\n // Visible first, so \"can't read it back\" is evidence of the delete.\n try {\n await as.getOne(resource, { id });\n } catch (error) {\n throw new ContractError(`${resource} ${String(id)} isn't visible before the delete: ${describeError(error)}`);\n }\n await expectAllowed(as.deleteOne(resource, { id }));\n try {\n await as.getOne(resource, { id });\n } catch (error) {\n if (!isDataReadError(error) || (error.outcome !== \"gone\" && error.outcome !== \"forbidden\")) {\n throw new ContractError(`reading it back failed: ${describeError(error)}`);\n }\n if (!(await inBin())) throw new ContractError(`${resource} ${String(id)} was deleted for good, not binned`);\n return;\n }\n throw new ContractError(`${resource} ${String(id)} is still visible after the delete`);\n}\n\nexport {\n accessRules,\n declaredFunctions,\n expectAccessRulesCover,\n type AccessRuleCase,\n type AccessRuleClient,\n type AccessRuleSpec,\n type DeclaredFunction,\n} from \"./access-rules\";\n"]}
|
|
@@ -910,4 +910,4 @@ interface DataProvider {
|
|
|
910
910
|
invalidates?(event: WriteEvent): InvalidationKey[];
|
|
911
911
|
}
|
|
912
912
|
|
|
913
|
-
export { type UpdateParams as $, type AggregateParams as A, type BaseRecord as B, type
|
|
913
|
+
export { type UpdateParams as $, type AggregateParams as A, type BaseRecord as B, type CountMode as C, type DataProvider as D, type GetOneResult as E, type FieldSchema as F, type GetManyParams as G, type HistoryParams as H, type InvalidationKey as I, type ImportParams as J, type PaginationParam as K, type ListResult as L, type RangeFilter as M, type NullFilter as N, type RecordComment as O, type ProviderCapabilities as P, type ResourceAccess as Q, type ResourceContract as R, type SortParam as S, type ResourceRelation as T, type ResourceSchema as U, type ResourceSummary as V, type WriteEvent as W, type RowFailure as X, type ScalarFilter as Y, type SelectOption as Z, type StorageType as _, type FilterParam as a, type UpdateResult as a0, type VersionField as a1, type WidgetHint as a2, defineResource as a3, fieldControl as a4, type ListParams as b, type Identifier as c, type AggregateResult as d, type DataRow as e, type FieldReference as f, type SubscribeParams as g, type ResourceChangeEvent as h, type ResourceFormFieldDef as i, type AuditEntry as j, type AggregateMetric as k, type RowOf as l, type RowAction as m, type ArrayFilter as n, type BulkChange as o, type BulkResult as p, type ControlHint as q, type CreateParams as r, type CreateResult as s, type DeleteParams as t, type DeleteResult as u, type FieldPermissions as v, type FieldType as w, type FilterOperator as x, type GetManyResult as y, type GetOneParams as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as ResourceContract, e as DataRow, l as RowOf, c as Identifier, m as RowAction, a as FilterParam, F as FieldSchema } from './types-
|
|
1
|
+
import { R as ResourceContract, e as DataRow, l as RowOf, c as Identifier, m as RowAction, a as FilterParam, F as FieldSchema } from './types-BnOCVJzm.js';
|
|
2
2
|
import { R as Readiness, C as ChipTone } from './status-BXRokZD9.js';
|
|
3
3
|
import { V as Viewer, R as ResourceScope } from './viewer-oOk0ZZk9.js';
|
|
4
4
|
import { GalleryItem } from './gallery/index.js';
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider/postgrest-errors.ts","../src/errors.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,oBAAoB,IAAA,EAA8C;AAChF,EAAA,IAAI,CAAC,MAAM,OAAO,OAAA;AAClB,EAAA,IAAI,IAAA,KAAS,WAAW,IAAA,KAAS,OAAA,IAAY,eAAe,IAAA,CAAK,IAAI,CAAA,IAAK,IAAA,KAAS,UAAA,EAAa;AAC9F,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAQ,qBAAqB,IAAI,CAAA;AACvC,EAAA,OAAO,KAAA,KAAU,eAAe,KAAA,KAAU,MAAA,IAAU,UAAU,iBAAA,IAAqB,KAAA,KAAU,YACzF,KAAA,GACA,OAAA;AACN;AAiBO,SAAS,qBAAqB,IAAA,EAA+C;AAClF,EAAA,IAAI,CAAC,MAAM,OAAO,OAAA;AAClB,EAAA,IAAI,IAAA,KAAS,SAAS,OAAO,WAAA;AAC7B,EAAA,IAAI,IAAA,KAAS,YAAY,OAAO,MAAA;AAChC,EAAA,IAAI,SAAS,UAAA,IAAc,IAAA,KAAS,UAAA,IAAc,IAAA,KAAS,YAAY,OAAO,iBAAA;AAC9E,EAAA,IAAI,IAAA,KAAS,OAAA,IAAW,IAAA,KAAS,OAAA,EAAS,OAAO,iBAAA;AACjD,EAAA,IAAI,IAAA,KAAS,SAAS,OAAO,WAAA;AAC7B,EAAA,IAAI,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAA,EAAG,OAAO,SAAA;AAC5C,EAAA,OAAO,OAAA;AACT;AAGA,IA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A,EAAM;AACxF,EAAA,MAAM,SAAS,KAAA,CAAM,KAAA,EAAO,QAAQ,CAAA,IAAK,KAAA,CAAM,OAAO,YAAY,CAAA;AAClE,EAAA,MAAM,OAAA,GAAU,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,GAAS,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,CAAO,MAAM,CAAA,GAAI,GAAA;AACpG,EAAA,IAAI,MAAA,CAAO,SAAA,CAAU,OAAO,CAAA,EAAG;AAC7B,IAAA,MAAM,QAAA,GAAW,WAAW,OAAO,CAAA;AACnC,IAAA,IAAI,UAAU,OAAO,QAAA;AAAA,EACvB;AACA,EAAA,IAAI,OAAA,CAAQ,aAAY,EAAG,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,QAAQ,KAAA,EAAM;AACnE,EAAA,OAAO,EAAE,IAAA,EAAM,YAAA,EAAc,MAAA,EAAQ,IAAA,EAAK;AAC5C;AAWO,SAAS,aAAA,CAAc,KAAA,EAAgB,OAAA,GAAgC,EAAC,EAAoB;AACjG,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAO,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,EAC9B,CAAA,CAAA,MAAQ;AAEN,IAAA,IAAA,GAAO,EAAE,IAAA,EAAM,YAAA,EAAc,MAAA,EAAQ,IAAA,EAAK;AAAA,EAC5C;AACA,EAAA,MAAM,OAAA,GAAU,QAAQ,QAAA,GAAW,IAAA,CAAK,IAAI,CAAA,IAAK,aAAA,CAAc,KAAK,IAAI,CAAA;AACxE,EAAA,OAAO,EAAE,GAAG,IAAA,EAAM,OAAA,EAAQ;AAC5B","file":"chunk-NOPS5EIH.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Postgres / PostgREST error codes → Genesis write outcomes\n// ---------------------------------------------------------------------------\n\nimport {\n DataWriteError,\n isDataWriteError,\n type WriteOutcome,\n} from \"../schema/write-outcome\";\nimport type { ReadOutcome } from \"../schema/read-outcome\";\nimport { titleCase } from \"../utils\";\n\n/**\n * Maps a store error code to the read outcome it means: the write mapping,\n * with `22***` and PostgREST request errors (`PGRST1**` other than PGRST116,\n * `42703` unknown column, `42P01` unknown table) read as `invalid`.\n */\nexport function readOutcomeFromCode(code: string | null | undefined): ReadOutcome {\n if (!code) return \"error\";\n if (code === \"42703\" || code === \"42P01\" || (/^PGRST1\\d\\d$/.test(code) && code !== \"PGRST116\")) {\n return \"invalid\";\n }\n const write = writeOutcomeFromCode(code);\n return write === \"forbidden\" || write === \"gone\" || write === \"unauthenticated\" || write === \"invalid\"\n ? write\n : \"error\";\n}\n\n/**\n * Maps a Postgres SQLSTATE or PostgREST error code to the write outcome it\n * means. Anything not listed is `error`: a code is only read as a refusal or\n * a bad value when it says so.\n *\n * - `42501` (insufficient privilege, including \"new row violates row-level\n * security policy\") → `forbidden`\n * - `23505` (unique violation) → `duplicate`\n * - `22***` (data exception: bad type, out of range) and the other `23***`\n * (integrity constraint: `23503` foreign key, `23502` not null, `23514`\n * check) → `invalid`\n * - `PGRST301`–`PGRST303` (JWT missing, expired or rejected), `28000`,\n * `28P01` → `unauthenticated`\n * - `PGRST116` (one row was asked for and none came back) → `gone`\n */\nexport function writeOutcomeFromCode(code: string | null | undefined): WriteOutcome {\n if (!code) return \"error\";\n if (code === \"42501\") return \"forbidden\";\n if (code === \"PGRST116\") return \"gone\";\n if (code === \"PGRST301\" || code === \"PGRST302\" || code === \"PGRST303\") return \"unauthenticated\";\n if (code === \"28000\" || code === \"28P01\") return \"unauthenticated\";\n if (code === \"23505\") return \"duplicate\";\n if (/^2[23][0-9A-Z]{3}$/.test(code)) return \"invalid\";\n return \"error\";\n}\n\n/** A column name as Postgres reports it unquoted; anything else is not mapped. */\nconst COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * One index expression as Postgres prints it: a plain column, or one column\n * wrapped in a function, optionally cast (`lower(email::text)`,\n * `lower((email)::text)`). Anything else is not mapped.\n */\nconst WRAPPED_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*\\(\\(?([A-Za-z_][A-Za-z0-9_]*)\\)?(?:::[A-Za-z_][A-Za-z0-9_ ]*)?\\)$/;\n\nfunction columnOf(expression: string): string | undefined {\n if (COLUMN.test(expression)) return expression;\n return WRAPPED_COLUMN.exec(expression)?.[1];\n}\n\n/**\n * The columns of a `Key (a, b)=(...)` detail line, or none when any is not a\n * plain column (or one column in a simple expression index). The key list is\n * read with its parentheses balanced, so an expression index such as\n * `Key (lower(email::text))=(…)` is recognised.\n */\nfunction keyColumns(details: string, tail: RegExp): string[] {\n if (!details.startsWith(\"Key (\") || !tail.test(details)) return [];\n let depth = 1;\n let end = -1;\n for (let i = \"Key (\".length; i < details.length; i++) {\n const ch = details[i];\n if (ch === \"(\") depth++;\n else if (ch === \")\" && --depth === 0) {\n end = i;\n break;\n }\n }\n if (end < 0 || details.slice(end + 1, end + 3) !== \"=(\") return [];\n const parts: string[] = [];\n let level = 0;\n let current = \"\";\n for (const ch of details.slice(\"Key (\".length, end)) {\n if (ch === \"(\") level++;\n else if (ch === \")\") level--;\n if (ch === \",\" && level === 0) {\n parts.push(current.trim());\n current = \"\";\n } else {\n current += ch;\n }\n }\n parts.push(current.trim());\n const columns = parts.map(columnOf);\n return columns.length > 0 && columns.every((c): c is string => !!c) ? columns : [];\n}\n\nfunction listLabels(columns: string[]): string {\n const labels = columns.map((c) => titleCase(c));\n if (labels.length === 1) return labels[0]!;\n return `${labels.slice(0, -1).join(\", \")} and ${labels[labels.length - 1]}`;\n}\n\n/** Field errors read from a store error, with the safe sentence that sums them up. */\nexport interface PostgrestFieldErrors {\n /** Column name → safe message for that input. */\n fields: Record<string, string>;\n /** One safe sentence for the whole error, to replace the store's raw text. */\n message: string;\n}\n\n/**\n * Reads which columns a Postgres constraint error is about, from PostgREST's\n * `message` / `details`, and gives safe messages for them. Only plain column\n * names are taken from the store's text; the values it echoes are never\n * used. A unique violation whose columns cannot be read (a complex\n * expression index, no details), or an insert/update foreign-key violation\n * whose key is an expression, gets the safe sentence with no `fields`, so the\n * store's raw text (constraint name, echoed value) never reaches the user.\n * Returns `undefined` for anything else.\n *\n * - `23505` unique violation, `Key (email)=(…) already exists.` → each\n * column: \"This value is already in use.\" (several columns: \"This\n * combination is already in use.\")\n * - `23502` not-null, `null value in column \"title\" …` → \"This field is\n * required.\"\n * - `23503` foreign key on insert/update, `Key (owner_id)=(…) is not present\n * in table …` → \"The selected item doesn't exist.\"\n */\nexport function fieldErrorsFromPostgrest(error: {\n code?: unknown;\n message?: unknown;\n details?: unknown;\n}): PostgrestFieldErrors | undefined {\n const code = typeof error.code === \"string\" ? error.code : undefined;\n const details = typeof error.details === \"string\" ? error.details.trim() : \"\";\n const message = typeof error.message === \"string\" ? error.message : \"\";\n if (code === \"23505\") {\n const columns = keyColumns(details, /\\) already exists\\.?$/);\n // Not mappable to a column: still never show the store's raw text (it\n // names the constraint and echoes the value).\n if (columns.length === 0) return { fields: {}, message: \"This value is already in use.\" };\n const each = columns.length === 1 ? \"This value is already in use.\" : \"This combination is already in use.\";\n return {\n fields: Object.fromEntries(columns.map((c) => [c, each])),\n message:\n columns.length === 1\n ? `${listLabels(columns)} is already in use.`\n : `This combination of ${listLabels(columns)} is already in use.`,\n };\n }\n if (code === \"23502\") {\n const column = /^null value in column \"([A-Za-z_][A-Za-z0-9_]*)\"(?: |$)/.exec(message)?.[1];\n if (!column || !COLUMN.test(column)) return undefined;\n return {\n fields: { [column]: \"This field is required.\" },\n message: `${titleCase(column)} is required.`,\n };\n }\n if (code === \"23503\") {\n const tail = /\\) is not present in table \"[^\"]*\"\\.?$/;\n if (!tail.test(details)) return undefined;\n const columns = keyColumns(details, tail);\n if (columns.length === 0) return { fields: {}, message: \"The selected item doesn't exist.\" };\n return {\n fields: Object.fromEntries(columns.map((c) => [c, \"The selected item doesn't exist.\"])),\n message: `${listLabels(columns)}: the selected item doesn't exist.`,\n };\n }\n return undefined;\n}\n\n/**\n * Turns anything a write threw, or the `{ message, code }` error a Supabase\n * client returned, into a `DataWriteError`. A `DataWriteError` passes through\n * unchanged; anything else keeps its message and `code`, and is kept as the\n * `cause`.\n *\n * When the error names the columns it is about (`fieldErrorsFromPostgrest`:\n * unique, not-null and foreign-key violations), the result carries `fields`\n * and its message is replaced with a safe sentence; the raw text stays on\n * the `cause`.\n */\nexport function toDataWriteError(error: unknown): DataWriteError {\n if (isDataWriteError(error)) return error;\n const shape = (typeof error === \"object\" && error !== null ? error : {}) as {\n message?: unknown;\n code?: unknown;\n details?: unknown;\n };\n const code = typeof shape.code === \"string\" ? shape.code : undefined;\n const mapped = fieldErrorsFromPostgrest(shape);\n if (mapped) {\n return new DataWriteError(writeOutcomeFromCode(code), mapped.message, {\n code,\n fields: Object.keys(mapped.fields).length > 0 ? mapped.fields : undefined,\n cause: error,\n });\n }\n const message =\n typeof shape.message === \"string\" && shape.message\n ? shape.message\n : error instanceof Error\n ? error.message\n : String(error);\n return new DataWriteError(writeOutcomeFromCode(code), message, { code, cause: error });\n}\n","// ---------------------------------------------------------------------------\n// Errors: one way for every Genesis package to report a caught error, and one\n// way to say what kind of error it is.\n//\n// `reportError(error, context)` is the seam a package calls when it catches\n// something it can't handle itself (a card's action that threw, a draft that\n// couldn't be saved). The host app decides where it goes: a native app's\n// observability block registers itself with `setErrorReporter` and sends it,\n// scrubbed, to Sentry; with nothing registered it is written with\n// `console.warn` in development and dropped in production.\n//\n// `classifyError(error)` sorts anything thrown into a few kinds a screen can\n// act on (offline, signed out, refused, gone, conflict, bad input, a bug),\n// with a sentence that is safe to show and whether it is worth reporting.\n// It is built on the provider's read and write outcomes.\n// ---------------------------------------------------------------------------\n\nimport { readOutcomeFromCode, writeOutcomeFromCode } from \"./provider/postgrest-errors\";\nimport { isDataReadError } from \"./schema/read-outcome\";\nimport { isDataWriteError } from \"./schema/write-outcome\";\n\n/** Where a reported error came from. */\nexport interface ErrorReportContext {\n /**\n * Which part caught it, as `package:part` (`chat:attachment-action`,\n * `forms-native:draft-save`). Low-cardinality: never an id or text.\n */\n source: string;\n /** True when the app could not go on. Default false: a package that reports has handled it. */\n fatal?: boolean;\n /** Low-cardinality labels (`query.key: \"tasks\"`), never ids, emails or text someone typed. */\n tags?: Readonly<Record<string, string>>;\n}\n\n/** Where `reportError` sends errors. A throw inside it is ignored. */\nexport type ErrorReporter = (error: unknown, context: ErrorReportContext) => void;\n\ndeclare const __DEV__: boolean | undefined;\n\n/**\n * True in a development build: `__DEV__` on React Native, else `NODE_ENV`, else true (no bundler\n * and no `process`). For development-only hints.\n *\n * @stability Beta\n */\nexport function isDevelopment(): boolean {\n if (typeof __DEV__ !== \"undefined\") return Boolean(__DEV__);\n let env: string | undefined;\n try {\n // Written out in full: bundlers (Vite, webpack, esbuild) replace exactly `process.env.NODE_ENV`\n // at build time, and a browser has no `process` to read at run time.\n env = process.env.NODE_ENV;\n } catch {\n env = undefined;\n }\n return env !== \"production\";\n}\n\n/** The reporter used when the app registered none: `console.warn` in development, nothing in production. */\nexport const defaultErrorReporter: ErrorReporter = (error, context) => {\n if (!isDevelopment()) return;\n // genesis-allow-console: the development fallback of the reporting seam itself.\n console.warn(`[genesis] ${context.source}:`, error);\n};\n\n// Kept on globalThis so two copies of this package (a bundling slip) still share one reporter.\nconst KEY = Symbol.for(\"genesis.errorReporter\");\ntype Holder = { [KEY]?: ErrorReporter };\n\n/** The reporter `reportError` uses now. */\nexport function getErrorReporter(): ErrorReporter {\n return (globalThis as Holder)[KEY] ?? defaultErrorReporter;\n}\n\n/**\n * Send every `reportError` to `reporter` (`null` puts the default back).\n * Returns a function that restores the reporter that was there before.\n * The native observability block calls it when it is created.\n */\nexport function setErrorReporter(reporter: ErrorReporter | null): () => void {\n const holder = globalThis as Holder;\n const previous = holder[KEY];\n if (reporter) holder[KEY] = reporter;\n else delete holder[KEY];\n return () => {\n if (previous) holder[KEY] = previous;\n else delete holder[KEY];\n };\n}\n\n/**\n * Report an error a package caught and handled. Never throws: a failing\n * reporter must not take the caller (an event handler, a render) down.\n * `context` may be just the source.\n */\nexport function reportError(error: unknown, context: ErrorReportContext | string): void {\n const full: ErrorReportContext = typeof context === \"string\" ? { source: context } : context;\n try {\n getErrorReporter()(error, full);\n } catch {\n // A failing reporter is ignored; reporting is never worth a second error.\n }\n}\n\n// ---------------------------------------------------------------------------\n// classifyError\n// ---------------------------------------------------------------------------\n\n/**\n * - `offline`: the request never reached the server (no network).\n * - `unauthenticated`: nobody is signed in, or the session ended.\n * - `forbidden`: the server refused this user.\n * - `not-found`: the record doesn't exist, or this user can't see it.\n * - `conflict`: someone else changed it first, or it already exists.\n * - `invalid`: the request or a value in it was rejected.\n * - `unexpected`: anything else (a bug, a server error).\n */\nexport type ErrorKind = \"offline\" | \"unauthenticated\" | \"forbidden\" | \"not-found\" | \"conflict\" | \"invalid\" | \"unexpected\";\n\n/** The sentence shown for each kind. Override any of them with `classifyError(e, { messages })`. */\nexport type ErrorMessages = Readonly<Record<ErrorKind, string>>;\n\n/** The English catalogue. Plain words, never the store's text. */\nexport const errorMessages: ErrorMessages = {\n offline: \"You're offline. Check your connection and try again.\",\n unauthenticated: \"Your session has ended. Sign in again to continue.\",\n forbidden: \"You don't have permission to do that.\",\n \"not-found\": \"This isn't here any more, or you can't see it.\",\n conflict: \"Someone else changed this first. Refresh and try again.\",\n invalid: \"Something in this couldn't be accepted. Check it and try again.\",\n unexpected: \"Something went wrong. Try again.\",\n};\n\nexport interface ClassifiedError {\n kind: ErrorKind;\n /** Safe to show: from the messages catalogue, never the error's own text. */\n message: string;\n /** Worth reporting to a crash tracker: a bug or a server failure, not something the user or the network caused. */\n report: boolean;\n}\n\nexport interface ClassifyErrorOptions {\n /** Reworded or translated sentences; what you leave out stays English. */\n messages?: Partial<ErrorMessages>;\n /** True when the device knows it is offline (TanStack's `onlineManager`, NetInfo). */\n isOffline?: () => boolean;\n}\n\n// The text each runtime's fetch throws when the request never left the device.\nconst NETWORK_MESSAGES = [\n /^network request failed$/i, // React Native\n /^failed to fetch$/i, // Chromium\n /^load failed$/i, // Safari\n /^networkerror when attempting to fetch resource\\.?$/i, // Firefox\n /^network error$/i,\n /^the internet connection appears to be offline\\.?$/i,\n];\n// Supabase's wrappers around a fetch that never reached the server.\nconst NETWORK_NAMES = new Set([\"AuthRetryableFetchError\", \"FunctionsFetchError\", \"StorageUnknownError\"]);\n\nfunction field(error: unknown, name: string): unknown {\n return typeof error === \"object\" && error !== null ? (error as Record<string, unknown>)[name] : undefined;\n}\n\nfunction isNetworkError(error: unknown): boolean {\n const name = field(error, \"name\");\n const message = field(error, \"message\");\n if (typeof name === \"string\" && NETWORK_NAMES.has(name)) {\n // StorageUnknownError covers other failures too; only its network form counts.\n return name !== \"StorageUnknownError\" || (typeof message === \"string\" && NETWORK_MESSAGES.some((re) => re.test(message)));\n }\n return typeof message === \"string\" && NETWORK_MESSAGES.some((re) => re.test(message.trim()));\n}\n\nfunction fromStatus(status: number): Omit<ClassifiedError, \"message\"> | null {\n if (status === 401) return { kind: \"unauthenticated\", report: false };\n if (status === 403) return { kind: \"forbidden\", report: false };\n if (status === 404 || status === 410) return { kind: \"not-found\", report: false };\n if (status === 409 || status === 412) return { kind: \"conflict\", report: false };\n if (status === 400 || status === 422) return { kind: \"invalid\", report: true };\n if (status === 429) return { kind: \"unexpected\", report: false };\n return null;\n}\n\nfunction kindOf(error: unknown, options: ClassifyErrorOptions): Omit<ClassifiedError, \"message\"> {\n if (isDataWriteError(error)) {\n switch (error.outcome) {\n case \"conflict\":\n case \"duplicate\":\n return { kind: \"conflict\", report: false };\n case \"gone\":\n return { kind: \"not-found\", report: false };\n case \"forbidden\":\n return { kind: \"forbidden\", report: false };\n case \"invalid\":\n return { kind: \"invalid\", report: false };\n case \"unauthenticated\":\n return { kind: \"unauthenticated\", report: false };\n default:\n // `error` and `audit_failed`: a network failure surfaces here as the write's cause.\n if (isNetworkError(error.cause ?? error) || options.isOffline?.()) return { kind: \"offline\", report: false };\n return { kind: \"unexpected\", report: true };\n }\n }\n if (isDataReadError(error)) {\n switch (error.outcome) {\n case \"unauthenticated\":\n return { kind: \"unauthenticated\", report: false };\n case \"forbidden\":\n return { kind: \"forbidden\", report: false };\n case \"gone\":\n return { kind: \"not-found\", report: false };\n case \"invalid\":\n // The request itself was wrong (an unknown column): a bug worth seeing.\n return { kind: \"invalid\", report: true };\n default:\n if (isNetworkError(error.cause ?? error) || options.isOffline?.()) return { kind: \"offline\", report: false };\n return { kind: \"unexpected\", report: true };\n }\n }\n if (isNetworkError(error)) return { kind: \"offline\", report: false };\n const code = field(error, \"code\");\n if (typeof code === \"string\" && code) {\n const read = readOutcomeFromCode(code);\n if (read === \"invalid\" && writeOutcomeFromCode(code) === \"error\") return { kind: \"invalid\", report: true };\n switch (writeOutcomeFromCode(code)) {\n case \"unauthenticated\":\n return { kind: \"unauthenticated\", report: false };\n case \"forbidden\":\n return { kind: \"forbidden\", report: false };\n case \"gone\":\n return { kind: \"not-found\", report: false };\n case \"duplicate\":\n return { kind: \"conflict\", report: false };\n case \"invalid\":\n return { kind: \"invalid\", report: false };\n default:\n break;\n }\n }\n const name = field(error, \"name\");\n if (name === \"AuthSessionMissingError\") return { kind: \"unauthenticated\", report: false };\n const status = field(error, \"status\") ?? field(error, \"statusCode\");\n const numeric = typeof status === \"number\" ? status : typeof status === \"string\" ? Number(status) : NaN;\n if (Number.isInteger(numeric)) {\n const byStatus = fromStatus(numeric);\n if (byStatus) return byStatus;\n }\n if (options.isOffline?.()) return { kind: \"offline\", report: false };\n return { kind: \"unexpected\", report: true };\n}\n\n/**\n * What kind of error this is, a sentence that is safe to show, and whether it\n * is worth reporting. Understands the provider's `DataWriteError` and\n * `DataReadError`, Postgres and PostgREST codes, HTTP statuses, Supabase's\n * auth and fetch errors, and each runtime's \"network request failed\".\n *\n * Use it for a toast (`toast.error(classifyError(e).message)`) and to decide\n * whether to report (`if (classifyError(e).report) reportError(e, …)`).\n */\nexport function classifyError(error: unknown, options: ClassifyErrorOptions = {}): ClassifiedError {\n let base: Omit<ClassifiedError, \"message\">;\n try {\n base = kindOf(error, options);\n } catch {\n // A getter that throws on an exotic value: still an answer, never a second error.\n base = { kind: \"unexpected\", report: true };\n }\n const message = options.messages?.[base.kind] ?? errorMessages[base.kind];\n return { ...base, message };\n}\n"]}
|