@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.
Files changed (80) hide show
  1. package/dist/{aggregate-v_r-nZbH.d.ts → aggregate-CUirs7ka.d.ts} +1 -1
  2. package/dist/{chunk-UNEZF3ZP.js → chunk-5PCGMSDX.js} +209 -28
  3. package/dist/chunk-5PCGMSDX.js.map +1 -0
  4. package/dist/{chunk-JNWTHDGF.js → chunk-AOIVTOHX.js} +3 -3
  5. package/dist/{chunk-JNWTHDGF.js.map → chunk-AOIVTOHX.js.map} +1 -1
  6. package/dist/{chunk-FBMKI22S.js → chunk-ATVK3VYS.js} +3 -3
  7. package/dist/{chunk-FBMKI22S.js.map → chunk-ATVK3VYS.js.map} +1 -1
  8. package/dist/{chunk-NOPS5EIH.js → chunk-CJ5V6JES.js} +5 -114
  9. package/dist/chunk-CJ5V6JES.js.map +1 -0
  10. package/dist/{chunk-TWLPC4S3.js → chunk-DJRT4DUF.js} +3 -3
  11. package/dist/{chunk-TWLPC4S3.js.map → chunk-DJRT4DUF.js.map} +1 -1
  12. package/dist/{chunk-WNOCPV4A.js → chunk-DTVYCATJ.js} +3 -3
  13. package/dist/{chunk-WNOCPV4A.js.map → chunk-DTVYCATJ.js.map} +1 -1
  14. package/dist/chunk-LYNIHY3F.js +115 -0
  15. package/dist/chunk-LYNIHY3F.js.map +1 -0
  16. package/dist/{chunk-6B4CN2TC.js → chunk-OCMYW2YE.js} +3 -3
  17. package/dist/{chunk-6B4CN2TC.js.map → chunk-OCMYW2YE.js.map} +1 -1
  18. package/dist/{chunk-AQX5HQD6.js → chunk-OTUTSAZD.js} +3 -3
  19. package/dist/{chunk-AQX5HQD6.js.map → chunk-OTUTSAZD.js.map} +1 -1
  20. package/dist/{chunk-KRRESUXT.js → chunk-PH25HOAL.js} +6 -6
  21. package/dist/{chunk-KRRESUXT.js.map → chunk-PH25HOAL.js.map} +1 -1
  22. package/dist/{chunk-XIBQ5BTZ.js → chunk-RZVLUUMY.js} +4 -4
  23. package/dist/{chunk-XIBQ5BTZ.js.map → chunk-RZVLUUMY.js.map} +1 -1
  24. package/dist/{chunk-2ORQLYVW.js → chunk-SMEG63MO.js} +4 -4
  25. package/dist/{chunk-2ORQLYVW.js.map → chunk-SMEG63MO.js.map} +1 -1
  26. package/dist/{chunk-YMFJLBIZ.js → chunk-UKJCF2CM.js} +3 -3
  27. package/dist/{chunk-YMFJLBIZ.js.map → chunk-UKJCF2CM.js.map} +1 -1
  28. package/dist/{chunk-K33LWVUF.js → chunk-UKWM32CG.js} +3 -3
  29. package/dist/{chunk-K33LWVUF.js.map → chunk-UKWM32CG.js.map} +1 -1
  30. package/dist/csv.d.ts +1 -1
  31. package/dist/errors.js +2 -1
  32. package/dist/form-types.d.ts +1 -1
  33. package/dist/headless/index.d.ts +1 -1
  34. package/dist/hooks/index.d.ts +4 -4
  35. package/dist/hooks/index.js +13 -12
  36. package/dist/hooks/mutation-mode.d.ts +1 -1
  37. package/dist/hooks/mutation-mode.js +3 -2
  38. package/dist/hooks/related-keys.d.ts +1 -1
  39. package/dist/hooks/use-aggregate.d.ts +2 -2
  40. package/dist/hooks/use-board-columns.d.ts +1 -1
  41. package/dist/hooks/use-capabilities.d.ts +1 -1
  42. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  43. package/dist/hooks/use-link-options.d.ts +1 -1
  44. package/dist/hooks/use-list-state.d.ts +3 -3
  45. package/dist/hooks/use-list-state.js +5 -4
  46. package/dist/hooks/use-live.d.ts +1 -1
  47. package/dist/hooks/use-one.d.ts +1 -1
  48. package/dist/hooks/use-relation-label.d.ts +1 -1
  49. package/dist/hooks/use-resource-form.d.ts +1 -1
  50. package/dist/hooks/use-resource-form.js +4 -3
  51. package/dist/hooks/use-resource.d.ts +1 -1
  52. package/dist/hooks/use-resource.js +4 -3
  53. package/dist/hooks/use-segment-counts.d.ts +2 -2
  54. package/dist/hooks/use-segment-counts.js +5 -4
  55. package/dist/hooks/use-view-board.d.ts +2 -2
  56. package/dist/hooks/use-view-board.js +8 -7
  57. package/dist/hooks/use-view-calendar-range.d.ts +2 -2
  58. package/dist/hooks/use-view-calendar-range.js +6 -5
  59. package/dist/hooks/use-write.d.ts +1 -1
  60. package/dist/index.d.ts +8 -8
  61. package/dist/index.js +15 -14
  62. package/dist/index.js.map +1 -1
  63. package/dist/provider/index.d.ts +7 -378
  64. package/dist/provider/index.js +3 -2
  65. package/dist/{write-outcome-DuwfsnyO.d.ts → read-outcome-Cq0h2oAG.d.ts} +31 -2
  66. package/dist/resource-view/index.d.ts +4 -4
  67. package/dist/resource-view/index.js +5 -4
  68. package/dist/resource-view/index.js.map +1 -1
  69. package/dist/{saved-views-C45lRm7i.d.ts → saved-views-Bcox3blZ.d.ts} +2 -2
  70. package/dist/schema/index.d.ts +3 -4
  71. package/dist/supabase-provider-D5ditkHi.d.ts +465 -0
  72. package/dist/testing/index.d.ts +87 -3
  73. package/dist/testing/index.js +88 -1
  74. package/dist/testing/index.js.map +1 -1
  75. package/dist/{types-CiQY6hUy.d.ts → types-BnOCVJzm.d.ts} +1 -1
  76. package/dist/{types-BAhcze_-.d.ts → types-CBtBvGw0.d.ts} +1 -1
  77. package/package.json +1 -1
  78. package/dist/chunk-NOPS5EIH.js.map +0 -1
  79. package/dist/chunk-UNEZF3ZP.js.map +0 -1
  80. package/dist/read-outcome-BnboMYOV.d.ts +0 -30
@@ -0,0 +1,465 @@
1
+ import { c as Identifier, a as FilterParam, B as BaseRecord, I as InvalidationKey, W as WriteEvent, C as CountMode, D as DataProvider } from './types-BnOCVJzm.js';
2
+ import { D as DataReadError } from './read-outcome-Cq0h2oAG.js';
3
+
4
+ /** A chainable query builder returned by `client.from(table)`. */
5
+ interface SupabaseQueryBuilder {
6
+ select(columns?: string, options?: {
7
+ count?: "exact" | "planned" | "estimated";
8
+ }): SupabaseQueryBuilder;
9
+ insert(data: Record<string, unknown> | Record<string, unknown>[]): SupabaseQueryBuilder;
10
+ update(data: Record<string, unknown>): SupabaseQueryBuilder;
11
+ delete(): SupabaseQueryBuilder;
12
+ eq(column: string, value: unknown): SupabaseQueryBuilder;
13
+ neq(column: string, value: unknown): SupabaseQueryBuilder;
14
+ gt(column: string, value: unknown): SupabaseQueryBuilder;
15
+ lt(column: string, value: unknown): SupabaseQueryBuilder;
16
+ gte(column: string, value: unknown): SupabaseQueryBuilder;
17
+ lte(column: string, value: unknown): SupabaseQueryBuilder;
18
+ ilike(column: string, value: string): SupabaseQueryBuilder;
19
+ in(column: string, values: unknown[]): SupabaseQueryBuilder;
20
+ is(column: string, value: null): SupabaseQueryBuilder;
21
+ not(column: string, operator: string, value: unknown): SupabaseQueryBuilder;
22
+ or(filters: string): SupabaseQueryBuilder;
23
+ order(column: string, options?: {
24
+ ascending?: boolean;
25
+ nullsFirst?: boolean;
26
+ }): SupabaseQueryBuilder;
27
+ range(from: number, to: number): SupabaseQueryBuilder;
28
+ single(): SupabaseQueryBuilder;
29
+ then: Promise<{
30
+ data: unknown;
31
+ error: unknown;
32
+ count?: number | null;
33
+ }>["then"];
34
+ }
35
+ /**
36
+ * Minimal Supabase client interface — the public shape this package has
37
+ * always exposed for a caller that wants to type its own client or a
38
+ * wrapper around one. Unchanged: `from()` still returns `SupabaseQueryBuilder`
39
+ * so existing consumers that annotate a variable with this type and chain
40
+ * off it keep type-checking exactly as before.
41
+ */
42
+ interface SupabaseClient {
43
+ from(table: string): SupabaseQueryBuilder;
44
+ /** Another schema's tables, for a resource named `schema.table` outside `public`. */
45
+ schema?(name: string): {
46
+ from(table: string): SupabaseQueryBuilder;
47
+ };
48
+ /** Supabase Realtime; needed only for `subscribe` (see `SupabaseProviderOptions.realtime`). */
49
+ channel?(name: string): SupabaseRealtimeChannel;
50
+ /** Releases a channel made by `channel()`. */
51
+ removeChannel?(channel: SupabaseRealtimeChannel): unknown;
52
+ }
53
+ /**
54
+ * One `postgres_changes` message, as Supabase Realtime sends it. Only the
55
+ * fields the provider reads; a real payload has more.
56
+ */
57
+ interface SupabaseRealtimePayload {
58
+ eventType: "INSERT" | "UPDATE" | "DELETE";
59
+ /** The row after an insert or update (empty for a delete). */
60
+ new?: Record<string, unknown>;
61
+ /** For a delete or update: the old row's key (all of it with `REPLICA IDENTITY FULL`). */
62
+ old?: Record<string, unknown>;
63
+ }
64
+ /**
65
+ * The part of a Supabase `RealtimeChannel` the provider uses. A real
66
+ * `@supabase/supabase-js` channel satisfies it.
67
+ */
68
+ interface SupabaseRealtimeChannel {
69
+ on(type: "postgres_changes", filter: {
70
+ event: "*" | "INSERT" | "UPDATE" | "DELETE";
71
+ schema: string;
72
+ table: string;
73
+ filter?: string;
74
+ }, callback: (payload: SupabaseRealtimePayload) => void): SupabaseRealtimeChannel;
75
+ subscribe(callback?: (status: string, error?: unknown) => void): SupabaseRealtimeChannel;
76
+ unsubscribe?(): unknown;
77
+ }
78
+ /**
79
+ * What `createSupabaseProvider` actually requires from its `client` argument
80
+ * — deliberately looser than the public `SupabaseClient` above, and used
81
+ * ONLY for that one parameter. A real `@supabase/supabase-js` client's
82
+ * `from()` returns a generic, table-typed `PostgrestQueryBuilder` whose chain
83
+ * methods don't structurally match `SupabaseQueryBuilder`, which used to
84
+ * force callers to pass their client through `as never`. Since `unknown` is
85
+ * a supertype of everything, any real client's `from(table: string)`
86
+ * satisfies THIS shape without a cast; `createSupabaseProvider` narrows to
87
+ * `SupabaseQueryBuilder` internally, once, right after each `from()` call.
88
+ * Loosening only the input here — rather than `SupabaseClient` itself —
89
+ * means a caller relying on `SupabaseClient`'s stricter return type for
90
+ * their own chaining is unaffected.
91
+ */
92
+ interface SupabaseClientInput {
93
+ from(table: string): unknown;
94
+ /** Another schema's tables, for a resource named `schema.table` outside `public`. Any real client's `schema` fits. */
95
+ schema?(name: string): {
96
+ from(table: string): unknown;
97
+ };
98
+ /** Database functions, for a resource whose `source` is an `rpc`. Any real client's `rpc` fits. */
99
+ rpc?(fn: string, args?: Record<string, unknown>, options?: {
100
+ count?: "exact" | "planned" | "estimated";
101
+ }): unknown;
102
+ /** Supabase Realtime, for `subscribe`. Any real client's `channel` fits. */
103
+ channel?(name: string): unknown;
104
+ removeChannel?(channel: unknown): unknown;
105
+ }
106
+ /** What a write hook is told about the write it is part of. */
107
+ interface SupabaseWriteContext {
108
+ resource: string;
109
+ action: "create" | "update";
110
+ /** The row's id, for an update. */
111
+ id?: Identifier;
112
+ }
113
+ /** What an `update` override is told besides the row. */
114
+ interface SupabaseUpdateContext {
115
+ /**
116
+ * With a `version` rule and an `expectedVersion` from the caller: the
117
+ * version the row must still be at. The override must apply the change
118
+ * only at that version (e.g. `... where id = $1 and version = $2`) and
119
+ * return nothing when no row matched; the provider then tells a
120
+ * `conflict` from `forbidden` and `gone`.
121
+ */
122
+ expectedVersion?: string;
123
+ }
124
+ /**
125
+ * A function source that pages itself (`SupabaseResourceConfig.source`'s `pages`): the order its
126
+ * rows come in, and the column that carries the whole result's count. A count alone asks the
127
+ * function for `page_limit: 0`, which it answers with one row that carries the count (and builds
128
+ * no other row).
129
+ *
130
+ * @stability Beta
131
+ */
132
+ interface SourcePages {
133
+ readonly order?: readonly {
134
+ field: string;
135
+ order: "asc" | "desc";
136
+ }[];
137
+ readonly total?: string;
138
+ }
139
+ /** Per-resource rules for `createSupabaseProvider`. Every field is optional. */
140
+ /**
141
+ * What a function source's `args` gets (`SupabaseResourceConfig.source`): the list's filters,
142
+ * which carry the viewer's scope, and `take`, which reads one equality filter's value (`null` for
143
+ * "is empty") and keeps that filter out of the query.
144
+ *
145
+ * @stability Beta
146
+ */
147
+ interface SourceArgsContext {
148
+ readonly resource: string;
149
+ readonly filters: readonly FilterParam[];
150
+ take(field: string): string | number | boolean | null | undefined;
151
+ /**
152
+ * The values of a filter on `field` that an `in` (or an `eq`, as one value) gives, taken out of
153
+ * the query like `take`; undefined when there's none. For a function that filters by a list.
154
+ */
155
+ takeIn(field: string): readonly unknown[] | undefined;
156
+ }
157
+ interface SupabaseResourceConfig {
158
+ /** Singular noun for failure messages, e.g. "project". Defaults to "record". */
159
+ noun?: string;
160
+ /** Plural for list messages, when it isn't `noun` + "s" ("categories"). */
161
+ nounPlural?: string;
162
+ /**
163
+ * The columns a search covers. `[]` means the resource can't be searched,
164
+ * and `capabilities(resource).search` reports false so a UI hides the box.
165
+ * Set, they replace the caller's `search.fields`; omitted, those are used
166
+ * as given.
167
+ */
168
+ searchFields?: readonly string[];
169
+ /**
170
+ * The column a sorted list orders by last, so rows with equal sort values
171
+ * keep one order from page to page (none repeats, none is skipped).
172
+ * Default `"id"`; `false` for a table or view without one. With the
173
+ * default, a view that turns out to have no `id` column is read as before
174
+ * (without the key order) and a development warning suggests setting this.
175
+ */
176
+ orderKey?: string | false;
177
+ /**
178
+ * `"bin"` for a table whose delete trigger moves the row to a recycle bin
179
+ * instead of removing it (see `SupabaseProviderOptions.binTables`).
180
+ * `"hard"` forces a plain delete even when `binTables` lists the table.
181
+ */
182
+ deleteMode?: "hard" | "bin";
183
+ /**
184
+ * Turns submitted values into the row to write: trim, drop read-only keys,
185
+ * validate. Runs before every create and update, including the `create`
186
+ * and `update` overrides. Throw (ideally `DataWriteError("invalid", ...)`)
187
+ * to refuse the write; nothing is sent.
188
+ */
189
+ prepare?: (values: Record<string, unknown>, context: SupabaseWriteContext) => Record<string, unknown> | Promise<Record<string, unknown>>;
190
+ /**
191
+ * Creates the row some other way than an insert, e.g. a security-definer
192
+ * RPC. Return the new row, or its id and the provider reads the row back
193
+ * (if the read-back fails, the create is still reported as saved, with
194
+ * just the id, so the user does not retry and make a second one). Throw to
195
+ * fail; a Supabase `{ message, code }` error is mapped like any other.
196
+ */
197
+ create?: (row: Record<string, unknown>) => Promise<BaseRecord | Identifier>;
198
+ /**
199
+ * Updates the row some other way than an update, e.g. an RPC. Return the
200
+ * updated row, or its id (or `true`) and the provider reads it back.
201
+ * Returning nothing (`undefined`/`null`/`false`) means no row changed: the provider then reads the
202
+ * row to say why (`forbidden` or `gone`), exactly as for a plain update,
203
+ * so a function that silently skips a row never reports a save.
204
+ */
205
+ update?: (id: Identifier, row: Record<string, unknown>, context?: SupabaseUpdateContext) => Promise<BaseRecord | Identifier | boolean | null | undefined | void>;
206
+ /**
207
+ * The column every update and delete of this resource is checked against,
208
+ * so an edit made on a stale copy is refused as a `conflict` instead of
209
+ * overwriting someone else's (`UpdateParams.expectedVersion`).
210
+ *
211
+ * The database must advance it on every update, or it detects nothing:
212
+ * `integer` with genesis-supabase's `genesis_version_bump` trigger
213
+ * (migration 0019), or `timestamp` with a trigger that sets it to `now()`
214
+ * on update (`moddatetime`). The provider never writes it: a submitted
215
+ * value is dropped. Writes without an `expectedVersion` are not checked,
216
+ * so turning this on changes nothing for callers that don't send one.
217
+ */
218
+ version?: {
219
+ field: string;
220
+ kind: "integer" | "timestamp";
221
+ };
222
+ /** Maps a stored row to edit-form values; see `DataProvider.toFormValues`. */
223
+ toFormValues?: (record: Record<string, unknown>) => Record<string, unknown>;
224
+ /**
225
+ * Other cache keys a committed write to this resource makes stale, e.g.
226
+ * `[["staff"], ["me"]]`. Served through `DataProvider.invalidates`, which
227
+ * `useResource` and `useResourceForm` invalidate after their writes.
228
+ */
229
+ invalidates?: InvalidationKey[] | ((event: WriteEvent) => InvalidationKey[]);
230
+ /**
231
+ * Serve `subscribe` for this resource through Supabase Realtime
232
+ * (`postgres_changes`), so `live` lists and records refresh when the table
233
+ * changes. The table must be in the `supabase_realtime` publication, with
234
+ * RLS on. `false` turns it off even when `SupabaseProviderOptions.realtime`
235
+ * covers the resource.
236
+ */
237
+ realtime?: boolean;
238
+ /**
239
+ * Read this resource from somewhere else than its table: a view (joins,
240
+ * counts, aggregations) or a database function that returns rows. Writes
241
+ * still go to the table. Lists keep paging, filters, search, sort, totals
242
+ * and cursors, because PostgREST filters a view or a set-returning function
243
+ * like a table. Realtime still watches the table.
244
+ *
245
+ * Row-level security: a plain view runs as its owner and a SECURITY DEFINER
246
+ * function as its definer, so either one reads past RLS. Create the view
247
+ * `with (security_invoker = true)` and the function `security invoker` (or
248
+ * have it filter by `auth.uid()` itself), or this exposes every row.
249
+ *
250
+ * ```ts
251
+ * resources: {
252
+ * tasks: { source: "tasks_with_people" },
253
+ * course_progress: { source: { rpc: "group_progress", args: ({ take }) => ({ group_id: take("group_id") }) } },
254
+ * }
255
+ * ```
256
+ *
257
+ * A function's `args` gets the list's filters (`context.filters`), which hold the viewer's scope
258
+ * as ResourceView applies it (a view's `scope: ["group_id"]` filters `group_id`), so a function
259
+ * that takes its scope as an argument reads it there rather than from a module variable.
260
+ * `context.take(field)` returns an equality filter's value and leaves that filter out of the
261
+ * query, for a scope the function takes as an argument and doesn't return as a column. A record
262
+ * read (`getOne`, `getMany`) gets the list's filters from `scope` (less a text search's
263
+ * `contains`, which `useOne` leaves out) when the caller passes them
264
+ * (`useOne`'s `scope`, which ResourceView's table, inbox and NativeResourceView's peek and
265
+ * edit sheet pass for a record off the loaded page), else none, and
266
+ * the function's own default scope applies.
267
+ *
268
+ * A function that pages itself declares `pages`: it takes `page_limit` and `page_offset`
269
+ * arguments, returns its rows in `pages.order` (newest first, say) and carries the whole
270
+ * result's count on each row (`pages.total`, default `total_count`). A list page whose filters
271
+ * the function all took, with no search and no sort other than `pages.order`, then passes the
272
+ * page to the function instead of a `range`, and reads its total from that column, so the
273
+ * function never builds rows outside the page. A count alone (a segment's) sends
274
+ * `page_limit: 0`: the function returns one row carrying the count, and builds no other. Any other list reads every row, as without
275
+ * `pages`, since PostgREST can only filter, search or sort what the function returned.
276
+ */
277
+ source?: string | {
278
+ rpc: string;
279
+ args?: (context: SourceArgsContext) => Record<string, unknown>;
280
+ pages?: SourcePages;
281
+ };
282
+ /**
283
+ * How lists of this resource count their total (default `exact`). Use
284
+ * `estimated` for large tables, or `none` when no screen shows a count.
285
+ */
286
+ count?: CountMode;
287
+ /** The columns read when the caller names none, e.g. embedded joins: `"*, person:people(full_name)"`. Default `"*"`. */
288
+ select?: string;
289
+ /**
290
+ * With a `source` (or a `select` that embeds other tables), the table's own
291
+ * columns: creates and updates write only these, so a form built from the
292
+ * richer read row never sends its joined or computed columns to the table.
293
+ * Without it, an update writes only the columns the table's row has, read from the table. On a
294
+ * provider with `access: "declared"` that read needs `table.read`: without it and without
295
+ * `writeColumns`, a table update over a `source` is refused, and an app `update` rule gets the
296
+ * values as sent. Write functions (`writes`) always get the values as sent: they decide what
297
+ * to write.
298
+ */
299
+ writeColumns?: readonly string[];
300
+ /**
301
+ * The named database functions this resource writes through: the default pattern
302
+ * (docs/DATA-ACCESS.md). Each is a function name, called with the default arguments, or
303
+ * `{ fn, args }` to name the arguments yourself:
304
+ *
305
+ * - `create`: `{ p_values }` (the prepared row, as jsonb). Returns the new id, or the new row.
306
+ * - `update`: `{ p_id, p_values }`, plus `p_expected_version` when the caller sent a version
307
+ * for a resource with a `version` rule. Returns the id (or `true`, or the row) when a row
308
+ * changed and nothing (null) when none did; the provider then reads the row to say why
309
+ * (`conflict`, `forbidden` or `gone`).
310
+ * - `delete`: `{ p_id }`, plus `p_expected_version` as for `update`. Returns the id (or `true`)
311
+ * when a row went, nothing when none did.
312
+ *
313
+ * The function holds the access rule (who may do this), so each one gets an access-rule test
314
+ * (`accessRules` from `@marktiderman/genesis-core/testing`). After a create or update the
315
+ * provider reads the record back through the resource's read (`source`), never `select *` on the
316
+ * table, so a write never asks for a column the client may not read.
317
+ *
318
+ * ```ts
319
+ * resources: {
320
+ * tasks: {
321
+ * source: "tasks_with_people",
322
+ * writes: { create: "create_task", update: "save_task", delete: "delete_task" },
323
+ * },
324
+ * }
325
+ * ```
326
+ *
327
+ * A `create` or `update` rule (above) wins over the matching `writes` entry.
328
+ */
329
+ writes?: ResourceWrites;
330
+ /**
331
+ * Named row actions, served by `runAction`: each a database function called with `{ p_id }`
332
+ * (plus `p_expected_version` as for `writes.update`), or `{ fn, args }`. It returns the changed
333
+ * row, its id or `true` when it acted, and nothing when no row matched.
334
+ */
335
+ actions?: Readonly<Record<string, FunctionCall<[id: Identifier, context: SupabaseUpdateContext]>>>;
336
+ /**
337
+ * Raw table access, declared: the reads or writes this resource does on its table itself
338
+ * instead of through a view or a named function, and why. With the provider's
339
+ * `access: "declared"`, a read with no `source` and a write with no `writes` entry (nor a
340
+ * `create`/`update` rule) is refused unless this covers it. The doctor's `data/declared-access`
341
+ * rule reports a provider that doesn't declare its access.
342
+ */
343
+ table?: TableAccess;
344
+ }
345
+ /**
346
+ * A database function a resource calls: its name (called with the documented default arguments),
347
+ * or `{ fn, args }` naming the arguments yourself.
348
+ *
349
+ * @stability Beta
350
+ */
351
+ type FunctionCall<A extends unknown[]> = string | {
352
+ readonly fn: string;
353
+ readonly args?: (...input: A) => Record<string, unknown>;
354
+ };
355
+ /**
356
+ * The named functions a resource writes through (`SupabaseResourceConfig.writes`).
357
+ *
358
+ * @stability Beta
359
+ */
360
+ interface ResourceWrites {
361
+ readonly create?: FunctionCall<[values: Record<string, unknown>]>;
362
+ readonly update?: FunctionCall<[id: Identifier, values: Record<string, unknown>, context: SupabaseUpdateContext]>;
363
+ readonly delete?: FunctionCall<[id: Identifier, context: SupabaseUpdateContext]>;
364
+ }
365
+ /**
366
+ * A declared opt-in to raw table access (`SupabaseResourceConfig.table`). `why` is required: it is
367
+ * what a reviewer reads to accept the exception.
368
+ *
369
+ * @stability Beta
370
+ */
371
+ interface TableAccess {
372
+ /** Read the table itself (the resource has no `source`). */
373
+ readonly read?: boolean;
374
+ /** Write the table itself: every write (`true`) or the ones listed. */
375
+ readonly write?: boolean | readonly ("create" | "update" | "delete")[];
376
+ /** Why this resource goes to its table rather than a view or a named function. */
377
+ readonly why: string;
378
+ }
379
+ /** Options for `createSupabaseProvider`. All optional; none changes reads. */
380
+ interface SupabaseProviderOptions {
381
+ /**
382
+ * Recycle-bin tables: their delete trigger turns a delete into a "binned"
383
+ * mark and the binned row drops out of the caller's view (RLS or a view
384
+ * filter). The database reports such a delete as zero rows, so for these
385
+ * the provider checks the row is visible, deletes it, and reads it back:
386
+ * gone from view is success, still visible is `forbidden`. A row that was
387
+ * not visible beforehand is `gone`. A list matches a `public` table under
388
+ * either spelling; a test is asked once, with the name as the caller gives it.
389
+ */
390
+ binTables?: readonly string[] | ((resource: string) => boolean);
391
+ /**
392
+ * Per-resource rules, keyed by resource name. A `public` resource may be keyed either way
393
+ * (`goals` or `public.goals`). The key spelled exactly as the caller names the resource wins;
394
+ * the other spelling is used only when that key is absent. Rules are never merged.
395
+ */
396
+ resources?: Record<string, SupabaseResourceConfig>;
397
+ /**
398
+ * Called after every committed create, update and delete, e.g. to
399
+ * invalidate caches the Genesis hooks don't know about. Awaited, but a
400
+ * failure is logged and never turns a committed write into a failed one.
401
+ */
402
+ onWrite?: (event: WriteEvent) => void | Promise<void>;
403
+ /**
404
+ * The most rows one list page may ask for (PostgREST's `max-rows` caps
405
+ * reads anyway; default 1000). A larger request is refused with an
406
+ * `invalid` `DataReadError` (its `cause` says why) rather than cut short,
407
+ * so page boundaries never disagree with the caller's `perPage`.
408
+ * `capabilities().maxPerPage` reports it.
409
+ */
410
+ maxPerPage?: number;
411
+ /**
412
+ * Called with every failed read, before it is thrown. The thrown
413
+ * `DataReadError` carries a plain message for users; the store's own
414
+ * error (its raw text and code) is its `cause`, for logging here.
415
+ */
416
+ onReadError?: (error: DataReadError, context: {
417
+ resource: string;
418
+ operation: "getList" | "getOne" | "getMany";
419
+ }) => void | Promise<void>;
420
+ /**
421
+ * Which resources `subscribe` serves through Supabase Realtime: `true` for
422
+ * all, a list of names, or a test. Off by default; a resource's own
423
+ * `resources[name].realtime` wins. Needs a client with `channel()` (any
424
+ * `@supabase/supabase-js` client). A list matches a `public` resource
425
+ * under either spelling; a test is asked once, with the name as the caller
426
+ * gives it.
427
+ */
428
+ realtime?: boolean | readonly string[] | ((resource: string) => boolean);
429
+ /**
430
+ * Work out `sum`, `avg`, `min` and `max` in the database with PostgREST's aggregate functions
431
+ * (`amount.sum()`), which a project turns on with `pgrst.db_aggregates_enabled`. Off by
432
+ * default: `aggregate` then counts in the database and totals the other metrics from the
433
+ * rows, paged (`resolveAggregate`, up to 10 000 rows). A count is always the database's.
434
+ */
435
+ aggregateFunctions?: boolean;
436
+ /**
437
+ * `"declared"`: every resource says how it is read and written (docs/DATA-ACCESS.md). Reads go
438
+ * through its `source` (a view or a function) and writes through its `writes` functions (or a
439
+ * `create`/`update` rule); touching the table itself needs a declared `table` opt-in. Anything
440
+ * else, a resource missing from `resources` included, is refused with a message that names what
441
+ * to declare. `"open"` (the default): an undeclared resource reads and writes its table, as
442
+ * before. The doctor's `data/declared-access` rule reports a provider left open.
443
+ */
444
+ access?: "declared" | "open";
445
+ }
446
+ /**
447
+ * The Supabase data provider. Reads and writes go through the client you
448
+ * pass, under that client's session and RLS.
449
+ *
450
+ * Writes never report a save that did not happen:
451
+ * - `update` and `deleteOne` ask for the affected rows. Zero rows is a
452
+ * `DataWriteError`: the row is read back, and still visible means
453
+ * `forbidden` (RLS or a trigger refused the change), no longer visible
454
+ * means `gone`.
455
+ * - Database errors on writes are thrown as `DataWriteError` with the
456
+ * outcome their code means (`writeOutcomeFromCode`) and the code kept on
457
+ * `error.code`.
458
+ * - Recycle-bin tables (`binTables`) succeed when the row leaves the
459
+ * caller's view.
460
+ *
461
+ * Reads are unchanged: errors are thrown as an `Error` carrying `code`.
462
+ */
463
+ declare function createSupabaseProvider(client: SupabaseClientInput, options?: SupabaseProviderOptions): DataProvider;
464
+
465
+ export { type FunctionCall as F, type ResourceWrites as R, type SourceArgsContext as S, type TableAccess as T, type SourcePages as a, type SupabaseClient as b, type SupabaseClientInput as c, type SupabaseProviderOptions as d, type SupabaseRealtimeChannel as e, type SupabaseRealtimePayload as f, type SupabaseResourceConfig as g, type SupabaseUpdateContext as h, type SupabaseWriteContext as i, createSupabaseProvider as j };
@@ -1,5 +1,89 @@
1
- import { D as DataProvider, c as Identifier } from '../types-CiQY6hUy.js';
2
- import { D as DataWriteError } from '../write-outcome-DuwfsnyO.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