@marktiderman/genesis-core 2.16.1 → 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.
Files changed (134) hide show
  1. package/README.md +3 -2
  2. package/dist/{aggregate-Y5IJ5aPn.d.ts → aggregate-CUirs7ka.d.ts} +1 -1
  3. package/dist/{chunk-M5IX7C6U.js → chunk-24X4HWL5.js} +4 -4
  4. package/dist/{chunk-M5IX7C6U.js.map → chunk-24X4HWL5.js.map} +1 -1
  5. package/dist/{chunk-XPBS5YE4.js → chunk-4POVYF6P.js} +4 -4
  6. package/dist/{chunk-XPBS5YE4.js.map → chunk-4POVYF6P.js.map} +1 -1
  7. package/dist/{chunk-IYGVJFCV.js → chunk-5KLIFJYG.js} +3 -3
  8. package/dist/{chunk-IYGVJFCV.js.map → chunk-5KLIFJYG.js.map} +1 -1
  9. package/dist/{chunk-7EFTWOMA.js → chunk-5PCGMSDX.js} +280 -41
  10. package/dist/chunk-5PCGMSDX.js.map +1 -0
  11. package/dist/chunk-6JOWGO2X.js +266 -0
  12. package/dist/chunk-6JOWGO2X.js.map +1 -0
  13. package/dist/{chunk-E3K2A3PK.js → chunk-6SHGMEA6.js} +3 -3
  14. package/dist/{chunk-E3K2A3PK.js.map → chunk-6SHGMEA6.js.map} +1 -1
  15. package/dist/chunk-6VNM6KAX.js +59 -0
  16. package/dist/chunk-6VNM6KAX.js.map +1 -0
  17. package/dist/chunk-AOIVTOHX.js +892 -0
  18. package/dist/chunk-AOIVTOHX.js.map +1 -0
  19. package/dist/{chunk-FXPODKCK.js → chunk-ATVK3VYS.js} +6 -6
  20. package/dist/{chunk-FXPODKCK.js.map → chunk-ATVK3VYS.js.map} +1 -1
  21. package/dist/chunk-BNKP2H7J.js +11 -0
  22. package/dist/chunk-BNKP2H7J.js.map +1 -0
  23. package/dist/{chunk-NOPS5EIH.js → chunk-CJ5V6JES.js} +5 -114
  24. package/dist/chunk-CJ5V6JES.js.map +1 -0
  25. package/dist/chunk-DJRT4DUF.js +53 -0
  26. package/dist/chunk-DJRT4DUF.js.map +1 -0
  27. package/dist/chunk-DTVYCATJ.js +220 -0
  28. package/dist/chunk-DTVYCATJ.js.map +1 -0
  29. package/dist/{chunk-POUI7GAI.js → chunk-JF7FXSQB.js} +5 -5
  30. package/dist/{chunk-POUI7GAI.js.map → chunk-JF7FXSQB.js.map} +1 -1
  31. package/dist/{chunk-LB6FMQQM.js → chunk-KV2HW4G4.js} +3 -11
  32. package/dist/chunk-KV2HW4G4.js.map +1 -0
  33. package/dist/chunk-LYNIHY3F.js +115 -0
  34. package/dist/chunk-LYNIHY3F.js.map +1 -0
  35. package/dist/{chunk-42NVJJTT.js → chunk-MMMC37AP.js} +3 -3
  36. package/dist/{chunk-42NVJJTT.js.map → chunk-MMMC37AP.js.map} +1 -1
  37. package/dist/chunk-MZVFOTAE.js +96 -0
  38. package/dist/chunk-MZVFOTAE.js.map +1 -0
  39. package/dist/{chunk-ALLWIK62.js → chunk-OCMYW2YE.js} +8 -6
  40. package/dist/chunk-OCMYW2YE.js.map +1 -0
  41. package/dist/{chunk-R3YXYVWF.js → chunk-OIZNABG4.js} +5 -4
  42. package/dist/chunk-OIZNABG4.js.map +1 -0
  43. package/dist/{chunk-SOO54YYY.js → chunk-OTUTSAZD.js} +4 -4
  44. package/dist/{chunk-SOO54YYY.js.map → chunk-OTUTSAZD.js.map} +1 -1
  45. package/dist/chunk-PH25HOAL.js +192 -0
  46. package/dist/chunk-PH25HOAL.js.map +1 -0
  47. package/dist/{chunk-QGWQ6LK3.js → chunk-QJOKZZKY.js} +9 -6
  48. package/dist/chunk-QJOKZZKY.js.map +1 -0
  49. package/dist/{chunk-ZYOJWU62.js → chunk-RZVLUUMY.js} +13 -54
  50. package/dist/chunk-RZVLUUMY.js.map +1 -0
  51. package/dist/chunk-SMEG63MO.js +115 -0
  52. package/dist/chunk-SMEG63MO.js.map +1 -0
  53. package/dist/chunk-UKJCF2CM.js +159 -0
  54. package/dist/chunk-UKJCF2CM.js.map +1 -0
  55. package/dist/chunk-UKWM32CG.js +31 -0
  56. package/dist/chunk-UKWM32CG.js.map +1 -0
  57. package/dist/{chunk-UDSTWXXZ.js → chunk-ZKLB2HB5.js} +3 -3
  58. package/dist/{chunk-UDSTWXXZ.js.map → chunk-ZKLB2HB5.js.map} +1 -1
  59. package/dist/csv.d.ts +12 -3
  60. package/dist/csv.js +4 -4
  61. package/dist/csv.js.map +1 -1
  62. package/dist/errors.js +2 -1
  63. package/dist/form-types.d.ts +1 -1
  64. package/dist/headless/index.d.ts +1 -1
  65. package/dist/hooks/index.d.ts +16 -6
  66. package/dist/hooks/index.js +29 -16
  67. package/dist/hooks/mutation-mode.d.ts +1 -1
  68. package/dist/hooks/mutation-mode.js +5 -4
  69. package/dist/hooks/related-keys.d.ts +1 -1
  70. package/dist/hooks/use-aggregate.d.ts +2 -2
  71. package/dist/hooks/use-aggregate.js +3 -3
  72. package/dist/hooks/use-board-columns.d.ts +79 -0
  73. package/dist/hooks/use-board-columns.js +4 -0
  74. package/dist/hooks/use-board-columns.js.map +1 -0
  75. package/dist/hooks/use-capabilities.d.ts +1 -1
  76. package/dist/hooks/use-capabilities.js +2 -2
  77. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  78. package/dist/hooks/use-infinite-resource.js +3 -3
  79. package/dist/hooks/use-link-options.d.ts +1 -1
  80. package/dist/hooks/use-link-options.js +5 -5
  81. package/dist/hooks/use-list-state.d.ts +103 -0
  82. package/dist/hooks/use-list-state.js +22 -0
  83. package/dist/hooks/use-list-state.js.map +1 -0
  84. package/dist/hooks/use-live.d.ts +1 -1
  85. package/dist/hooks/use-live.js +2 -2
  86. package/dist/hooks/use-one.d.ts +7 -1
  87. package/dist/hooks/use-one.js +3 -3
  88. package/dist/hooks/use-persisted-ui-state.js +2 -2
  89. package/dist/hooks/use-relation-label.d.ts +1 -1
  90. package/dist/hooks/use-relation-label.js +2 -2
  91. package/dist/hooks/use-resource-form.d.ts +1 -1
  92. package/dist/hooks/use-resource-form.js +9 -8
  93. package/dist/hooks/use-resource.d.ts +7 -1
  94. package/dist/hooks/use-resource.js +7 -6
  95. package/dist/hooks/use-segment-counts.d.ts +23 -0
  96. package/dist/hooks/use-segment-counts.js +20 -0
  97. package/dist/hooks/use-segment-counts.js.map +1 -0
  98. package/dist/hooks/use-view-board.d.ts +120 -0
  99. package/dist/hooks/use-view-board.js +30 -0
  100. package/dist/hooks/use-view-board.js.map +1 -0
  101. package/dist/hooks/use-view-calendar-range.d.ts +91 -0
  102. package/dist/hooks/use-view-calendar-range.js +23 -0
  103. package/dist/hooks/use-view-calendar-range.js.map +1 -0
  104. package/dist/hooks/use-write.d.ts +1 -1
  105. package/dist/index.d.ts +42 -12
  106. package/dist/index.js +122 -28
  107. package/dist/index.js.map +1 -1
  108. package/dist/provider/index.d.ts +7 -325
  109. package/dist/provider/index.js +4 -3
  110. package/dist/{write-outcome-CkQXgtJq.d.ts → read-outcome-Cq0h2oAG.d.ts} +31 -2
  111. package/dist/resource-view/index.d.ts +162 -757
  112. package/dist/resource-view/index.js +32 -686
  113. package/dist/resource-view/index.js.map +1 -1
  114. package/dist/saved-views-Bcox3blZ.d.ts +155 -0
  115. package/dist/schema/index.d.ts +3 -4
  116. package/dist/schema/index.js +2 -1
  117. package/dist/supabase-provider-D5ditkHi.d.ts +465 -0
  118. package/dist/testing/index.d.ts +87 -3
  119. package/dist/testing/index.js +88 -1
  120. package/dist/testing/index.js.map +1 -1
  121. package/dist/{types-BriIV4e_.d.ts → types-BnOCVJzm.d.ts} +11 -1
  122. package/dist/types-CBtBvGw0.d.ts +1063 -0
  123. package/dist/{viewer-scope-Dx0N9AYk.d.ts → viewer-oOk0ZZk9.d.ts} +36 -34
  124. package/dist/{workspaces-CxpiFu2-.d.ts → workspaces-DeaFix5Z.d.ts} +1 -1
  125. package/dist/workspaces.d.ts +2 -2
  126. package/package.json +11 -1
  127. package/dist/chunk-7EFTWOMA.js.map +0 -1
  128. package/dist/chunk-ALLWIK62.js.map +0 -1
  129. package/dist/chunk-LB6FMQQM.js.map +0 -1
  130. package/dist/chunk-NOPS5EIH.js.map +0 -1
  131. package/dist/chunk-QGWQ6LK3.js.map +0 -1
  132. package/dist/chunk-R3YXYVWF.js.map +0 -1
  133. package/dist/chunk-ZYOJWU62.js.map +0 -1
  134. package/dist/read-outcome-BnboMYOV.d.ts +0 -30
@@ -1,5 +1,89 @@
1
- import { D as DataProvider, d as Identifier } from '../types-BriIV4e_.js';
2
- import { D as DataWriteError } from '../write-outcome-CkQXgtJq.js';
1
+ import { D as DataProvider, c as Identifier } from '../types-BnOCVJzm.js';
2
+ import { b as DataWriteError } from '../read-outcome-Cq0h2oAG.js';
3
+ import { d as SupabaseProviderOptions } from '../supabase-provider-D5ditkHi.js';
4
+
5
+ /** The part of a Supabase client an access-rule test calls: any real client's `rpc` fits. */
6
+ interface AccessRuleClient {
7
+ rpc(fn: string, args?: Record<string, unknown>): unknown;
8
+ }
9
+ /** One function's access rule: who may call it, who may not, and the arguments for a call. */
10
+ interface AccessRuleSpec<Who extends string> {
11
+ /** The database function under test, as the resource declares it. */
12
+ readonly fn: string;
13
+ /** A client signed in as `who`: the app's own test people (a local stack's seeded logins, say). */
14
+ readonly as: (who: Who) => AccessRuleClient | Promise<AccessRuleClient>;
15
+ /**
16
+ * The arguments for one call by `who`, made fresh for each case (a row of its own to change, so
17
+ * one allowed call never changes what the next case sees).
18
+ */
19
+ readonly args: (who: Who) => Record<string, unknown> | Promise<Record<string, unknown>>;
20
+ /** Who may call it. At least one: a rule that admits no one tests nothing. */
21
+ readonly allowed: readonly Who[];
22
+ /** Who may not. At least one: a rule that refuses no one is not a rule. */
23
+ readonly refused: readonly Who[];
24
+ /**
25
+ * Whether a call's answer shows it acted. Default: anything but `null`, `false` or an empty list,
26
+ * the same answers the provider reads as "no row matched".
27
+ */
28
+ readonly acted?: (data: unknown) => boolean;
29
+ }
30
+ /** One test case: register it as `test(c.name, c.run)`. */
31
+ interface AccessRuleCase<Who extends string = string> {
32
+ readonly name: string;
33
+ readonly who: Who;
34
+ readonly expect: "allowed" | "refused";
35
+ run(): Promise<void>;
36
+ }
37
+ /**
38
+ * The test cases for one function's access rule. An allowed person's call must succeed and act; a
39
+ * refused person's call must be refused (an insufficient-privilege or guard error, 42501 or P0001)
40
+ * or act on nothing. Any other error fails the case, so a wrong name or wrong arguments can't pass
41
+ * as a refusal, and the allowed cases prove the same arguments do work.
42
+ *
43
+ * ```ts
44
+ * for (const c of accessRules({
45
+ * fn: "save_task",
46
+ * as: (who) => signedIn(who),
47
+ * args: async () => ({ p_id: await newTask(), p_values: { title: "Renamed" } }),
48
+ * allowed: ["owner", "admin"],
49
+ * refused: ["member", "stranger"],
50
+ * })) test(c.name, c.run);
51
+ * ```
52
+ */
53
+ declare function accessRules<Who extends string>(spec: AccessRuleSpec<Who>): AccessRuleCase<Who>[];
54
+ /** One database function a Supabase resource declares, read from the provider's options. */
55
+ interface DeclaredFunction {
56
+ /** The resource that declares it, as `resources` names it. */
57
+ readonly resource: string;
58
+ /** Where: a write (`create`, `update`, `delete`), an action (its name), or the read (`source`). */
59
+ readonly use: "create" | "update" | "delete" | "source" | `action:${string}`;
60
+ /** The database function's name. */
61
+ readonly fn: string;
62
+ }
63
+ /**
64
+ * Every database function the provider's resources declare: their `writes`, their `actions` and a
65
+ * `source: { rpc }`. Read from the options themselves, so nothing a resource declares is missed and
66
+ * nothing else is counted.
67
+ */
68
+ declare function declaredFunctions(options: Pick<SupabaseProviderOptions, "resources">): DeclaredFunction[];
69
+ /**
70
+ * Fails, naming each one, when a function the provider declares has no spec among `tested`. It
71
+ * compares names only, so pass it the specs the access-rule cases are registered from, with the
72
+ * options the app's provider is made from:
73
+ *
74
+ * ```ts
75
+ * const specs = [saveTask, createTask, archiveTask];
76
+ * for (const spec of specs) for (const c of accessRules(spec)) test(c.name, c.run);
77
+ * test("every declared function has an access-rule test", () => {
78
+ * expectAccessRulesCover(providerOptions, specs);
79
+ * });
80
+ * ```
81
+ *
82
+ * The doctor's `data/access-rule-tests` rule checks that a test suite calls it.
83
+ */
84
+ declare function expectAccessRulesCover(options: Pick<SupabaseProviderOptions, "resources">, tested: readonly (string | {
85
+ readonly fn: string;
86
+ })[]): void;
3
87
 
4
88
  /** The shared fixture logins, the same ids `genesis_testing.user_id()` uses. */
5
89
  declare const FIXTURE_USERS: {
@@ -97,4 +181,4 @@ declare function expectBinned(args: {
97
181
  inBin: () => Promise<boolean>;
98
182
  }): Promise<void>;
99
183
 
100
- export { ContractError, type ExpectRefusedOptions, FIXTURE_USERS, type FixtureUser, expectAllowed, expectBinned, expectNeverShows, expectPlainMessage, expectRefused, expectSees, expectServerOwned, fixtureAccessToken, isRefusal };
184
+ export { type AccessRuleCase, type AccessRuleClient, type AccessRuleSpec, ContractError, type DeclaredFunction, type ExpectRefusedOptions, FIXTURE_USERS, type FixtureUser, accessRules, declaredFunctions, expectAccessRulesCover, expectAllowed, expectBinned, expectNeverShows, expectPlainMessage, expectRefused, expectSees, expectServerOwned, fixtureAccessToken, isRefusal };
@@ -1,6 +1,93 @@
1
+ import { toDataWriteError } from '../chunk-LYNIHY3F.js';
1
2
  import { isDataReadError } from '../chunk-HUNGCTRA.js';
3
+ import '../chunk-RYEXWQFD.js';
2
4
  import { isDataWriteError } from '../chunk-WLDSIQJ2.js';
3
5
 
6
+ // src/testing/access-rules.ts
7
+ function refusedByRule(error) {
8
+ const mapped = toDataWriteError(error);
9
+ if (mapped.code === "42501" || mapped.code === "P0001") return true;
10
+ return mapped.outcome === "forbidden";
11
+ }
12
+ var answeredSomething = (data) => !(data === null || data === void 0 || data === false || Array.isArray(data) && data.length === 0);
13
+ function accessRules(spec) {
14
+ if (!spec.fn.trim()) throw new ContractError("accessRules needs the function's name (fn).");
15
+ if (spec.allowed.length === 0) {
16
+ throw new ContractError(`accessRules(${spec.fn}): name at least one person who may call it (allowed).`);
17
+ }
18
+ if (spec.refused.length === 0) {
19
+ throw new ContractError(`accessRules(${spec.fn}): name at least one person who may not call it (refused).`);
20
+ }
21
+ const both = spec.allowed.filter((who) => spec.refused.includes(who));
22
+ if (both.length > 0) {
23
+ throw new ContractError(`accessRules(${spec.fn}): ${both.join(", ")} is both allowed and refused.`);
24
+ }
25
+ const acted = spec.acted ?? answeredSomething;
26
+ const call = async (who) => {
27
+ const client = await spec.as(who);
28
+ const args = await spec.args(who);
29
+ try {
30
+ return await client.rpc(spec.fn, args);
31
+ } catch (error) {
32
+ return { data: null, error };
33
+ }
34
+ };
35
+ const describe = (error) => {
36
+ const mapped = toDataWriteError(error);
37
+ return `${mapped.outcome}${mapped.code ? ` (${mapped.code})` : ""}: ${mapped.message}`;
38
+ };
39
+ const allowed = spec.allowed.map(
40
+ (who) => ({
41
+ name: `${spec.fn}: ${who} may call it`,
42
+ who,
43
+ expect: "allowed",
44
+ async run() {
45
+ const { data, error } = await call(who);
46
+ if (error) throw new ContractError(`${spec.fn} refused ${who}, who should be allowed: ${describe(error)}`);
47
+ if (!acted(data)) throw new ContractError(`${spec.fn} acted on nothing for ${who}, who should be allowed.`);
48
+ }
49
+ })
50
+ );
51
+ const refused = spec.refused.map(
52
+ (who) => ({
53
+ name: `${spec.fn}: ${who} is refused`,
54
+ who,
55
+ expect: "refused",
56
+ async run() {
57
+ const { data, error } = await call(who);
58
+ if (error) {
59
+ if (refusedByRule(error)) return;
60
+ throw new ContractError(`${spec.fn} failed for ${who} with an error that isn't a refusal: ${describe(error)}`);
61
+ }
62
+ if (acted(data)) throw new ContractError(`${spec.fn} acted for ${who}, who should be refused.`);
63
+ }
64
+ })
65
+ );
66
+ return [...allowed, ...refused];
67
+ }
68
+ var fnOf = (call) => typeof call === "string" ? call : call.fn;
69
+ function declaredFunctions(options) {
70
+ const out = [];
71
+ for (const [resource, config] of Object.entries(options.resources ?? {})) {
72
+ for (const use of ["create", "update", "delete"]) {
73
+ const call = config.writes?.[use];
74
+ if (call) out.push({ resource, use, fn: fnOf(call) });
75
+ }
76
+ for (const [name, call] of Object.entries(config.actions ?? {})) out.push({ resource, use: `action:${name}`, fn: fnOf(call) });
77
+ if (config.source && typeof config.source === "object") out.push({ resource, use: "source", fn: config.source.rpc });
78
+ }
79
+ return out;
80
+ }
81
+ function expectAccessRulesCover(options, tested) {
82
+ const covered = new Set(tested.map(fnOf));
83
+ const missing = declaredFunctions(options).filter((d) => !covered.has(d.fn));
84
+ if (missing.length === 0) return;
85
+ const list = missing.map((d) => `${d.fn} (${d.resource} ${d.use})`).join(", ");
86
+ throw new ContractError(
87
+ `No access-rule test for ${missing.length === 1 ? "this declared function" : `these ${missing.length} declared functions`}: ${list}. Give each one accessRules({ fn, allowed, refused, \u2026 }) and pass its spec here (docs/DATA-ACCESS.md).`
88
+ );
89
+ }
90
+
4
91
  // src/testing/index.ts
5
92
  var FIXTURE_USERS = {
6
93
  owner: "00000000-0000-4000-8000-000000000001",
@@ -205,6 +292,6 @@ async function expectBinned(args) {
205
292
  throw new ContractError(`${resource} ${String(id)} is still visible after the delete`);
206
293
  }
207
294
 
208
- export { ContractError, FIXTURE_USERS, expectAllowed, expectBinned, expectNeverShows, expectPlainMessage, expectRefused, expectSees, expectServerOwned, fixtureAccessToken, isRefusal };
295
+ export { ContractError, FIXTURE_USERS, accessRules, declaredFunctions, expectAccessRulesCover, expectAllowed, expectBinned, expectNeverShows, expectPlainMessage, expectRefused, expectSees, expectServerOwned, fixtureAccessToken, isRefusal };
209
296
  //# sourceMappingURL=index.js.map
210
297
  //# sourceMappingURL=index.js.map
@@ -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,C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AA,kCAAA,EAAqC,aAAA,CAAc,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC9G;AACA,EAAA,MAAM,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// 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,6C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AAS,KAAA,EAAO;AACd,IAAA,MAAM,IAAI,aAAA,CAAc,CAAA,EAAG,QAAQ,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,kCAAA,EAAqC,aAAA,CAAc,KAAK,CAAC,CAAA,CAAE,CAAA;AAAA,EAC9G;AACA,EAAA,MAAM,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"]}
@@ -638,6 +638,14 @@ interface GetOneParams {
638
638
  id: Identifier;
639
639
  /** Supabase select syntax, e.g. "*, author:profiles(name)". Defaults to "*". */
640
640
  select?: string;
641
+ /**
642
+ * The list's filters, when the record is opened from a list: a resource read from a function
643
+ * whose `args` take its scope from them (`take`) reads in that scope. They never narrow the
644
+ * record itself, and a provider without function sources ignores them. ResourceView's table
645
+ * (a deep-linked record), inbox (an off-page row) and NativeResourceView's peek and edit sheet pass
646
+ * them through `useOne`'s `scope`.
647
+ */
648
+ scope?: FilterParam[];
641
649
  }
642
650
  /** Result of `getOne`. */
643
651
  interface GetOneResult<T> {
@@ -646,6 +654,8 @@ interface GetOneResult<T> {
646
654
  /** Parameters for `getMany`. */
647
655
  interface GetManyParams {
648
656
  ids: Identifier[];
657
+ /** As `GetOneParams.scope`: the list's filters a function source takes its scope from. */
658
+ scope?: FilterParam[];
649
659
  }
650
660
  /** Result of `getMany`. */
651
661
  interface GetManyResult<T> {
@@ -900,4 +910,4 @@ interface DataProvider {
900
910
  invalidates?(event: WriteEvent): InvalidationKey[];
901
911
  }
902
912
 
903
- export { type UpdateParams as $, type AggregateParams as A, type BaseRecord as B, type ControlHint as C, type DataProvider as D, type RangeFilter as E, type FieldSchema as F, type GetManyParams as G, type HistoryParams as H, type InvalidationKey as I, type RecordComment as J, type ResourceAccess as K, type ListResult as L, type ResourceContract as M, type NullFilter as N, type ResourceRelation as O, type ProviderCapabilities as P, type ResourceSchema as Q, type ResourceFormFieldDef as R, type SortParam as S, type ResourceSummary as T, type RowAction as U, type RowFailure as V, type WriteEvent as W, type RowOf 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 AggregateResult as b, type ListParams as c, type Identifier as d, type FieldReference as e, type SubscribeParams as f, type ResourceChangeEvent as g, type AuditEntry as h, type AggregateMetric as i, type DataRow as j, type ArrayFilter as k, type BulkChange as l, type BulkResult as m, type CountMode as n, type CreateParams as o, type CreateResult as p, type DeleteParams as q, type DeleteResult as r, type FieldPermissions as s, type FieldType as t, type FilterOperator as u, type GetManyResult as v, type GetOneParams as w, type GetOneResult as x, type ImportParams as y, type PaginationParam as z };
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 };