@gregale/data 0.0.0-stage → 0.1.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 (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1022 -2
  3. package/dist/bulk.d.ts +61 -0
  4. package/dist/bulk.js +63 -0
  5. package/dist/client-fetch.d.ts +34 -0
  6. package/dist/client-fetch.js +62 -0
  7. package/dist/cursor-token.d.ts +52 -0
  8. package/dist/cursor-token.js +165 -0
  9. package/dist/cursor.d.ts +44 -0
  10. package/dist/cursor.js +75 -0
  11. package/dist/deadline.d.ts +19 -0
  12. package/dist/deadline.js +29 -0
  13. package/dist/errors.d.ts +17 -0
  14. package/dist/errors.js +68 -0
  15. package/dist/index.d.ts +47 -0
  16. package/dist/index.js +35 -0
  17. package/dist/indexeddb-mutation-store.d.ts +12 -0
  18. package/dist/indexeddb-mutation-store.js +139 -0
  19. package/dist/json.d.ts +34 -0
  20. package/dist/json.js +39 -0
  21. package/dist/live/client.d.ts +192 -0
  22. package/dist/live/client.js +508 -0
  23. package/dist/live/index.d.ts +31 -0
  24. package/dist/live/index.js +28 -0
  25. package/dist/live/protocol.d.ts +125 -0
  26. package/dist/live/protocol.js +271 -0
  27. package/dist/live/react.d.ts +22 -0
  28. package/dist/live/react.js +59 -0
  29. package/dist/live/seal.d.ts +38 -0
  30. package/dist/live/seal.js +98 -0
  31. package/dist/live/sql.d.ts +11 -0
  32. package/dist/live/sql.js +58 -0
  33. package/dist/mutation-journal.d.ts +78 -0
  34. package/dist/mutation-journal.js +223 -0
  35. package/dist/numeric.d.ts +8 -0
  36. package/dist/numeric.js +33 -0
  37. package/dist/optimistic.d.ts +24 -0
  38. package/dist/optimistic.js +18 -0
  39. package/dist/reconcile.d.ts +28 -0
  40. package/dist/reconcile.js +28 -0
  41. package/dist/replay-key.d.ts +8 -0
  42. package/dist/replay-key.js +27 -0
  43. package/dist/response.d.ts +33 -0
  44. package/dist/response.js +29 -0
  45. package/dist/rpc.d.ts +20 -0
  46. package/dist/rpc.js +31 -0
  47. package/dist/storage-uploads.d.ts +55 -0
  48. package/dist/storage-uploads.js +78 -0
  49. package/dist/storage.d.ts +74 -0
  50. package/dist/storage.js +89 -0
  51. package/dist/validation.d.ts +26 -0
  52. package/dist/validation.js +40 -0
  53. package/dist/versioned-mutation.d.ts +28 -0
  54. package/dist/versioned-mutation.js +13 -0
  55. package/package.json +19 -4
package/README.md CHANGED
@@ -1,3 +1,1023 @@
1
- # Temporary Holding Version
1
+ # Gregale Data API client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@gregale/data` wraps PostgREST's typed client for Gregale application Data APIs.
4
+ The management SDK and account keys remain separate from application access.
5
+ This package is not published to npm. From an authorized checkout, run
6
+ `npm ci && npm run build && npm pack`, then install the produced tarball in
7
+ your application. The repository's existing SDK license/publication policy applies.
8
+ For a paired CLI/SDK artifact and a clean starter installation, use the
9
+ [Data API bundle workflow](../../docs/data-api-packaging.md).
10
+
11
+ ```ts
12
+ import { createDataClient } from '@gregale/data'
13
+ import type { Database } from './database.types.js'
14
+
15
+ const db = createDataClient<Database>({
16
+ url: 'https://my-data.gregale.dev',
17
+ accessToken: async () => auth.getAccessToken(),
18
+ }).schema('api')
19
+
20
+ const { data, error } = await db.from('notes').select('id,body').range(0, 19)
21
+ await db.from('notes').insert({subject: auth.user.id, body: 'Hello'})
22
+ ```
23
+
24
+ Generate `Database` with `gregale data-api types my-data --output
25
+ src/database.types.ts`. Use `--check` in CI to fail when your file differs
26
+ from the database. Refresh the serving schema cache after migrations with
27
+ `gregale data-api refresh my-data` and verify restart completion.
28
+
29
+ ### Public data without a session
30
+
31
+ When the owner enables [public reads or public RPCs](../../docs/data-api.md#public-reads),
32
+ create the client with `anonymous: true`. Requests then go out without an
33
+ `Authorization` header whenever there is no token:
34
+
35
+ ```ts
36
+ const visitor = createDataClient<Database>({ url: 'https://my-data.gregale.dev', anonymous: true }).schema('api')
37
+ const { data: products } = await visitor.from('products').select('id,name').limit(20)
38
+ const { data: results } = await visitor.rpc('search_products', { q: 'lamp' }, { get: true })
39
+ ```
40
+
41
+ Anonymous callers must call public RPCs with `{ get: true }`; a `POST` returns
42
+ `405 public_rpc_requires_get`. Arguments and results keep their generated
43
+ types.
44
+
45
+ One client can serve signed-in and signed-out visitors: with `anonymous: true`,
46
+ `accessToken` may return `null`, and the request is then anonymous. An empty
47
+ or malformed token still throws before any request is sent. Without
48
+ `anonymous: true`, a missing token always throws, so a broken session never
49
+ silently becomes anonymous access:
50
+
51
+ ```ts
52
+ const db = createDataClient<Database>({
53
+ url: 'https://my-data.gregale.dev',
54
+ anonymous: true,
55
+ accessToken: async () => (await auth.getSession())?.accessToken ?? null,
56
+ }).schema('api')
57
+ ```
58
+
59
+ Anonymous requests through `expectedSchemaFingerprint` reach the API on a
60
+ contract-pinned path, so the Data API does not mark them for the edge cache.
61
+
62
+ ### File storage
63
+
64
+ When the owner turns on [file storage](../../docs/data-api.md#file-storage),
65
+ `createStorageClient` takes the same options as `createDataClient`. The
66
+ owner's policies on `storage_objects` decide each upload, download and
67
+ removal:
68
+
69
+ ```ts
70
+ import { createStorageClient, StorageError } from '@gregale/data'
71
+
72
+ const files = createStorageClient({ url: 'https://my-data.gregale.dev', accessToken: () => session.accessToken }).from('uploads')
73
+ const stored = await files.upload(`${userId}/report.pdf`, file) // { bucket, name, owner, size, content_type, ... }
74
+ const response = await files.download(`${userId}/report.pdf`, { range: { start: 0, end: 1023 } })
75
+ const { url, expiresAt } = await files.signedUrl(`${userId}/report.pdf`)
76
+ await files.remove(`${userId}/report.pdf`)
77
+ ```
78
+
79
+ Refusals throw `StorageError` with the Data API's `code`, such as
80
+ `storage_forbidden` or `storage_not_found`. List files by querying
81
+ `storage_objects` with `createDataClient`, or follow the list with a live
82
+ read.
83
+
84
+ With the optional upload-session SQL installed, use `uploadResumable` to retain
85
+ checksummed progress and a durable completion receipt. Save the session ID from
86
+ `onSession`, then pass `sessionId` with the same file after an interruption.
87
+ `getUpload` reconciles completion; `abortUpload` cancels unfinished work.
88
+ `expectedVersion` accepts the version from `head()` or a previous upload, `null`
89
+ for create-only, or omission for unconditional replacement. A conflict returns
90
+ 412; an unknown commit sets `StorageError.uncertain` and requires reconciliation.
91
+ See [setup, limits and examples](../../docs/data-api/workflows.md#resumable-storage-and-upload-receipts).
92
+
93
+ ### Lossless numeric reads
94
+
95
+ Generate types with `--numeric-mode lossless`, then pass
96
+ `numericMode: 'lossless'` to `createDataClient`. Every JSON number becomes its
97
+ original decimal string, including nested JSON and array elements. `liveRead`
98
+ inherits the same codec. The serving fingerprint stays unchanged; ordinary
99
+ clients retain number decoding. This is a read codec: decoded JSON columns do
100
+ not retain the number-versus-string token distinction for subsequent writes.
101
+ See [numeric examples](../../docs/data-api/workflows.md#exact-numeric-decoding).
102
+
103
+ ### Live reads
104
+
105
+ A live read is a Data API read whose result stays current: it arrives once,
106
+ then changes as rows are written. Row-level security decides each row, as it
107
+ does for REST reads. Set it up once with
108
+ [`gregale data-api live enable`](../../docs/data-api.md#live-reads), which
109
+ prints the WebSocket URL and the database ID:
110
+
111
+ ```ts
112
+ import { LiveConnection, liveRead, liveSocket } from '@gregale/data/live'
113
+
114
+ const connection = new LiveConnection({ connect: liveSocket('wss://my-data.gregale.dev/__gregale/realtime/ENDPOINT_ID') })
115
+ const feed = connection.query({
116
+ database: DATABASE_ID,
117
+ token: () => session.accessToken,
118
+ ...liveRead(db.from('messages').select('id,body,author(name)').eq('channel_id', 7).order('id', { ascending: false }).limit(50)),
119
+ })
120
+ feed.subscribe(() => render(feed.getSnapshot().rows))
121
+ ```
122
+
123
+ `liveRead` takes the read's rows type from the generated contract, and rows
124
+ decode as the REST API returns them. Each read carries exactly one
125
+ credential:
126
+
127
+ - `token`, the signed-in user's token, called again before it expires;
128
+ - `anonymous: true`, for relations in the Data API's public-read allowlist;
129
+ - `serverKey` (with an optional `subject`) for trusted backends. Server keys
130
+ are refused from browsers.
131
+
132
+ React components use the hook from `@gregale/data/live/react` (React 18 or
133
+ later):
134
+
135
+ ```tsx
136
+ import { useLiveRead } from '@gregale/data/live/react'
137
+
138
+ const { rows, status } = useLiveRead(connection, { database: DATABASE_ID, anonymous: true, ...liveRead(visitor.from('products').select('id,name')) })
139
+ ```
140
+
141
+ The connection reconnects with backoff and resumes each read, keeping the
142
+ last rows meanwhile. `status` is `connecting` (also while reconnecting),
143
+ `live`, `stale` (the result could not be kept current, for example after a
144
+ credential expired) or `closed`.
145
+
146
+ For signed-in React reads, pass an `identityScope` that changes on login,
147
+ tenant switches or authorization changes. This closes the old subscription and
148
+ clears its rows immediately, including the render before effects run. Pass null
149
+ options on logout. Token refresh for the same identity does not need a new scope;
150
+ the token provider is called again. Never put a JWT in the scope value.
151
+
152
+ ```tsx
153
+ const options = session ? {
154
+ database: DATABASE_ID,
155
+ identityScope: session.scope,
156
+ token: () => session.accessToken,
157
+ ...liveRead(db.from('notes').select('id,body')),
158
+ } : null
159
+ const { rows } = useLiveRead(connection, options)
160
+ ```
161
+
162
+ ### Pin requests to the generated contract
163
+
164
+ Regenerated TypeScript files also export a runtime `schemaFingerprint` value.
165
+ Opt in to an exact serving-contract guard when a client must fail before data
166
+ access against a different deployment contract:
167
+
168
+ ```ts
169
+ import { schemaFingerprint, type Database } from './database.types.js'
170
+
171
+ const db = createDataClient<Database>({
172
+ url: 'https://my-data.gregale.dev',
173
+ accessToken: () => auth.getAccessToken(),
174
+ expectedSchemaFingerprint: schemaFingerprint,
175
+ }).schema('api')
176
+ ```
177
+
178
+ The SDK requires 64 lowercase hexadecimal characters and uses a guarded route
179
+ for every REST/RPC request. The gateway authenticates the token and rejects a
180
+ mismatch with HTTP 409 and `error.code === 'schema_contract_mismatch'` before
181
+ forwarding to PostgREST. HEAD responses have no error body; inspect their status.
182
+ An unavailable serving fingerprint returns 503. Older runtimes return 404;
183
+ the client never falls back to an unguarded request. Deploy a guard-capable
184
+ runtime before enabling the option. Ordinary clients retain their existing URLs.
185
+
186
+ Exact matching also rejects compatible additive changes. Update client types
187
+ and coordinate deployment using the existing sync/refresh workflow. The guard
188
+ compares the runtime's captured startup contract, not a live database inspection;
189
+ out-of-band DDL or engine-only cache reloads can make that observation stale.
190
+ It does not prove RLS, function-body or data compatibility. Guard failures do
191
+ not automatically replay writes or update the pinned fingerprint.
192
+
193
+ Owners can enable selected older client fingerprints using a serving-bound
194
+ `DATA_API_ACCEPTED_CONTRACTS` policy generated by
195
+ `gregale data-api diff --baseline old.json --current new.json --accept-contract accepted.json`.
196
+ The command requires zero structural breaking changes, including approved breaks.
197
+ Clients keep the same option; authentication and RLS still apply. See the
198
+ [rollout guide](../../docs/data-api.md#accept-older-clients-during-a-compatible-rollout)
199
+ for review, deployment and revocation.
200
+
201
+ Generated files also export `Tables<'notes'>`, `TablesInsert<'notes'>`,
202
+ `TablesUpdate<'notes'>`, and `Enums<'state'>`. `Tables` includes read-only views;
203
+ write helpers accept tables only and preserve generated-column restrictions.
204
+ An optional second parameter selects an exported schema, for example
205
+ `Tables<'items', 'other'>`. The default is `api` when available.
206
+
207
+ ```ts
208
+ import type { TablesInsert } from './database.types.js'
209
+ import type { QueryData, QueryResult, QueryError } from '@gregale/data'
210
+
211
+ const input: TablesInsert<'notes'> = { subject: auth.user.id, body: 'Hello' }
212
+ const query = db.from('notes').select('id,comments(id,body)')
213
+ type Rows = QueryData<typeof query>
214
+ type Response = QueryResult<typeof query>
215
+ type Error = QueryError<typeof query>
216
+ ```
217
+
218
+ `QueryData` removes the nullable error result and preserves nested projection
219
+ inference. `QueryResult` describes the full awaited response. `QueryError`
220
+ describes its non-null error type. The SDK also exports PostgREST single,
221
+ maybe-single and array response types.
222
+
223
+ For an existing application, install an approved bundle without copying starter
224
+ scripts:
225
+
226
+ ```sh
227
+ gregale data-api install --bundle /approved/data-api-bundle.json --directory .
228
+ # Use --client-directory web when package.json is in a project subdirectory.
229
+ gregale data-api install --restore --from /approved --directory .
230
+ ```
231
+
232
+ Commit the artifact pin, client package.json and lockfile together. Restore checks
233
+ both archive checksums and the committed npm integrity before installing locked
234
+ dependencies. This workflow uses approved artifacts; public npm publication
235
+ remains subject to the SDK publishing policy.
236
+
237
+ The token getter runs on each request. Requests omit browser cookies and refuse
238
+ redirects so access tokens stay at the configured API. The client preserves
239
+ PostgREST relation, insert, update, filter, projection and relationship inference.
240
+ Generated view relationships preserve readable, complete key projections,
241
+ including renamed columns and view chains in the same exposed schema. Aliased
242
+ embeds and FK hints use the normal PostgREST select syntax. Cardinality follows
243
+ the underlying key constraint; view column types remain nullable. Expressions
244
+ and partial keys have no inferred path, and ambiguous embeds can fail at runtime.
245
+ Approved same-schema computed relationships use generated `SetofOptions` for
246
+ source, target and cardinality. A `ROWS 1` function embeds an object or null,
247
+ while its direct RPC returns an array. Relation-set RPCs support typed nested
248
+ joins, projections and filters on their result relation. Upgrade the CLI/runtime
249
+ for normalized version 3 contracts; version 1/2 baselines remain readable.
250
+ See [the Data API guide](../../docs/data-api.md).
251
+
252
+ For JSON/JSONB paths, use explicit JSON aliases to preserve SQL nullability:
253
+
254
+ ```ts
255
+ import { selectJson, jsonText, jsonValue } from '@gregale/data'
256
+
257
+ const orders = await selectJson(db.from('orders'), 'id', {
258
+ status: jsonText('metadata', 'status'),
259
+ city: jsonText('metadata', 'delivery', 'city'),
260
+ details: jsonValue('metadata', 'details'),
261
+ first: jsonText('metadata', 'items', 0, 'name'),
262
+ }).eq('metadata->>status', 'paid')
263
+ // id retains its generated type; status/city/first are string | null.
264
+ // details is Json, including null; no arbitrary keys are inferred.
265
+ ```
266
+
267
+ The second argument is a literal normal select string, or `''` for JSON aliases
268
+ only. Keep JSON paths in the third argument: native JSON paths inside the base
269
+ selection retain the upstream SDK's inference, which can omit SQL nullability.
270
+ Alias names must be known to TypeScript and must not duplicate base fields.
271
+ Source columns are checked against the
272
+ generated row contract. Tables, views, write representations and relation-set
273
+ RPC builders work with the usual filters, ordering, `.single()`/`.maybeSingle()`
274
+ and error handling. Select again to replace the projection.
275
+
276
+ Paths accept nonempty string keys and safe integer array indexes, including
277
+ negative indexes. Numeric strings select object keys; numbers select array
278
+ positions. Names are quoted and URL-encoded by the SDK; quotes, backslashes and
279
+ control characters in names are rejected before sending. Missing paths, SQL
280
+ NULL and JSON null all yield null with `jsonText`. `jsonValue` preserves JSON
281
+ values, but HTTP JSON cannot distinguish extracted JSON null from SQL NULL.
282
+ Use database predicates when that distinction matters. See the guide for
283
+ JSONB `eq.null` versus SQL `is.null` and RLS examples.
284
+
285
+ Opted-in PostgreSQL functions appear in the generated `Functions` contract.
286
+ Call `db.rpc('function_name', { named_argument: value }).retry(false)` using an
287
+ application JWT. Gregale permits POST RPC only; omit `get` and `head` options.
288
+ Generated `CompositeTypes<'name'>` helpers describe named PostgreSQL composite
289
+ objects, including nested values and arrays. Approved RPCs use these types for
290
+ arguments and results; a composite result is an object and a SETOF result is an
291
+ array. Composite fields remain nullable, including domain attributes.
292
+ Arguments, defaults and results are inferred from the database. Each call is
293
+ one transaction. See the guide for opt-in comments, execution grants, supported
294
+ signatures, RLS and fresh-restart requirements.
295
+
296
+ For retry-safe note creation, the starter adds `create_note_with_tags_once`.
297
+ Retain one UUID and the same payload for a logical operation, then explicitly
298
+ replay with that key after an uncertain network outcome. Keys are user-scoped;
299
+ changed payloads return 409. The guide describes execution grants, receipt
300
+ retention, snapshot responses and deletion semantics.
301
+
302
+ Capture response diagnostics without wrapping fetch:
303
+
304
+ ```ts
305
+ const db = createDataClient<Database>({
306
+ url: 'https://my-data.gregale.dev',
307
+ accessToken: () => auth.getAccessToken(),
308
+ onResponse: ({ requestId, status, durationMs }) => {
309
+ console.info({ requestId, status, durationMs })
310
+ },
311
+ }).schema('api')
312
+ ```
313
+
314
+ `DataResponseInfo` is a readonly, runtime-frozen object containing only those
315
+ three fields. `requestId` is null when the header is missing, not exposed by CORS,
316
+ or not a UUID v4. No token, URL, query, headers, body or application identity is
317
+ passed to the callback. The SDK emits no logs unless your callback does so.
318
+
319
+ The callback runs once per HTTP response, including errors and individual retry
320
+ attempts, across reads, writes and RPCs. Duration is monotonic client time from
321
+ token lookup until fetch returns response headers; it excludes body consumption
322
+ and is not database execution or platform wake timing. The callback cannot read
323
+ or consume the response body. Network failures, cancellation before headers and
324
+ invalid tokens produce no callback when there is no HTTP response.
325
+
326
+ Callbacks may be synchronous or asynchronous. Exceptions and rejected promises
327
+ are ignored, and asynchronous completion is not awaited. Keep synchronous work
328
+ short; the request does not wait for asynchronous telemetry to finish. The hook
329
+ does not change retries, data, errors, counts or generated schema inference.
330
+
331
+ ### Runtime JSON validation
332
+
333
+ Use `validateJson` after checking the query error to validate selected fields.
334
+ It accepts synchronous objects with a `parse(unknown)` method, including Zod
335
+ schemas, and infers each field's result from the parser output. Validators are
336
+ application-owned; PostgreSQL JSON columns do not describe their internal shape.
337
+
338
+ ```ts
339
+ import { validateJson } from '@gregale/data'
340
+ import { z } from 'zod' // install in your application
341
+
342
+ const { data, error } = await query
343
+ if (error) throw error
344
+ const rows = validateJson(data, {
345
+ details: z.object({ count: z.number() }).nullable(),
346
+ })
347
+ ```
348
+
349
+ Arrays and single rows are supported. A null single-row result stays null; field
350
+ nulls go through the parser, so accept them explicitly with a nullable schema.
351
+ The helper copies rows and preserves unvalidated fields. Nested JSON validation
352
+ belongs inside your parser. Async parsers are unsupported.
353
+
354
+ Failures throw `JsonValidationError` with code `JSON_VALIDATION_FAILED`, the
355
+ selected `field`, and a zero-based `rowIndex` (null for a single row). Original
356
+ parser messages, causes and payloads are omitted. Validation runs locally after
357
+ the request and does not change PostgREST errors or database authorization.
358
+
359
+ ### Reusable cursor pagination
360
+
361
+ ```ts
362
+ import { cursorPage, cursorFrom } from '@gregale/data'
363
+
364
+ const order = [
365
+ { column: 'created_at', ascending: false, nullsFirst: false },
366
+ { column: 'id', ascending: false, unique: true },
367
+ ] as const
368
+ const { data, error } = await cursorPage(
369
+ db.from('notes').select('id,created_at,body'),
370
+ { order, size: 20 },
371
+ )
372
+ if (error) throw error
373
+ const after = data.length ? cursorFrom(data.at(-1)!, order) : undefined
374
+ // Supply after with the same order and filters on a fresh query for the next page.
375
+ ```
376
+
377
+ `cursorPage` preserves the selected result type and supports table/view reads,
378
+ filters, cancellation and native errors. Use a fresh array-returning select
379
+ builder without existing ordering, range or limits. Include every ordering
380
+ column in the selected row to extract its cursor. Ordering columns must be
381
+ simple names with scalar string, finite number, boolean or null values; JSON,
382
+ embedded fields and expression ordering are unsupported. Dates use their wire
383
+ strings. Defaults are ascending and nulls last, explicitly applied at every key.
384
+
385
+ The final ordering column must be non-null and unique within the filtered
386
+ result. Mark it `unique: true`; the application is responsible for this database
387
+ invariant. The helper cannot infer constraints from client types. Cursor values
388
+ are validated and quoted for PostgREST filter syntax, including commas, quotes
389
+ and backslashes. Cursor tuples are neither signed nor authorization tokens.
390
+
391
+ Keep filters, ordering and identity consistent across pages. RLS runs on every
392
+ request. Deleting the cursor row does not invalidate continuation; newer rows
393
+ before the cursor do not shift subsequent pages. This is not a snapshot across
394
+ requests: inserts after the cursor can appear, deleted rows disappear, and
395
+ changing ordering values can move rows. Stop when a page is empty. Large integer
396
+ keys must be represented without JavaScript precision loss by your application.
397
+ Existing server row caps can return fewer rows than the requested page size.
398
+
399
+ To fetch the previous page, use `before` with the cursor of the first displayed
400
+ row and keep the original ordering and filters:
401
+
402
+ ```ts
403
+ const previous = await cursorPage(
404
+ db.from('notes').select('id,body').eq('subject', 'alice'),
405
+ { order, size: 20, before: cursorFrom(firstDisplayedRow, order) },
406
+ )
407
+ if (previous.error) throw previous.error
408
+ const displayRows = [...previous.data].reverse()
409
+ ```
410
+
411
+ `before` returns the nearest preceding rows in reverse traversal order. Reverse
412
+ the returned array to display it in the original order. Use the same declared
413
+ `order` to extract each cursor; for another backward request, use the last row
414
+ of the raw response. `after` and `before` are mutually exclusive and invalid
415
+ cursors fail before the query builder is changed. Neither direction changes
416
+ RLS authorization or provides a snapshot across requests.
417
+
418
+ ### Request deadlines and cancellation
419
+
420
+ ```ts
421
+ import { dataRequest } from '@gregale/data'
422
+
423
+ const controller = new AbortController()
424
+ const result = await dataRequest(db.from('notes').select('id,body'), {
425
+ timeoutMs: 5000,
426
+ signal: controller.signal,
427
+ })
428
+ // Call controller.abort() when the screen closes or the filters change.
429
+ if (result.error?.code === 'request_timeout') { /* deadline exceeded */ }
430
+ if (result.error?.code === 'request_cancelled') { /* caller cancelled */ }
431
+ ```
432
+
433
+ `dataRequest` preserves the query's selected types and normal result shape.
434
+ The deadline covers asynchronous token lookup, transport and response-body
435
+ consumption. It disables automatic retries, clears its timer and removes its
436
+ caller-signal listener after completion. Server responses retain their original
437
+ status and error code. Cancellation and deadline failures have status `0` and
438
+ null data; use the normal result-returning query mode with this helper.
439
+
440
+ A client deadline stops waiting for a response. PostgREST does not guarantee
441
+ immediate SQL cancellation when the connection closes. Gregale's restricted SQL
442
+ role enforces a 15-second statement timeout; an already running query can occupy
443
+ a database connection until that limit. Cancelling a mutation does not prove it
444
+ rolled back: reconcile its outcome before retrying. The integration gate checks
445
+ that concurrent cancelled RPCs release their connections within the server
446
+ statement timeout and that subsequent reads succeed.
447
+
448
+ ### Optimistic concurrency
449
+
450
+ Use a database-managed version column to prevent stale edits from overwriting a
451
+ newer value. The [concurrent document example](../../examples/data-api-concurrency/README.md)
452
+ contains a trigger that increments the version for every update and a typed
453
+ edit/delete client.
454
+
455
+ ```ts
456
+ import { optimisticMutation } from '@gregale/data'
457
+
458
+ const result = await optimisticMutation(
459
+ db.from('documents').update({ body: editedBody })
460
+ .eq('id', document.id).eq('version', document.version)
461
+ .select('id,body,version'),
462
+ )
463
+ if (result.outcome === 'applied') {
464
+ document = result.row
465
+ } else if (result.outcome === 'conflict') {
466
+ // Reload the visible row and let the user review their edits.
467
+ } else {
468
+ // Preserve result.error and result.status; reconcile uncertain writes.
469
+ }
470
+ ```
471
+
472
+ The helper preserves selected row types and disables automatic retries. Use
473
+ `delete()` with the same primary-key/version filters for conditional deletion.
474
+ A stale, missing, deleted or RLS-hidden row produces the same `conflict` outcome;
475
+ a transport/server error remains an `error`. Include all primary-key columns,
476
+ and always call `select()` with an array result. The helper classifies the
477
+ response; the SQL predicate and version trigger enforce concurrency. It cannot
478
+ undo a mutation that targeted multiple rows. Use normal result-returning queries
479
+ rather than `single()` or `throwOnError()` with this helper.
480
+
481
+ ### Retrying uncertain writes safely
482
+
483
+ The [idempotent order example](../../examples/data-api-idempotency/README.md)
484
+ provides a typed `create_order_once` RPC backed by a subject/tenant/key unique
485
+ constraint and immutable stored response. Persist a UUID and the complete
486
+ operation payload before sending the first request, and reuse both after a
487
+ transport failure or deadline. Identical retries return the original row;
488
+ a changed total returns HTTP 409 with `PT409` and
489
+ `idempotency_payload_conflict`. A new key starts a new operation.
490
+
491
+ The example's typed client composes generated RPC arguments with `dataRequest`;
492
+ no generic retry wrapper or HTTP header can make arbitrary mutations idempotent.
493
+ The database transaction enforces the guarantee. See the example for permissions,
494
+ receipt retention and limitations on external side effects.
495
+
496
+ ### Read-only mutation recovery
497
+
498
+ Use an application's receipt lookup RPC to check a pending operation before
499
+ deciding whether to retry its write. The starter's append-only
500
+ `0011_note_receipt_lookup.sql` migration installs `read_note_create_receipt`;
501
+ apply the normal owner RPC permission workflow, refresh the API and regenerate
502
+ types. The idempotent-order example similarly adds `read_order_receipt`.
503
+ These authenticated RPCs derive identity from request claims, compare the original
504
+ key and payload, and return the stored original response without executing a write.
505
+
506
+ Given a pending note saved before the first attempt, use the same API and signed-in
507
+ identity and retain its original key, body and tag array:
508
+
509
+ ```ts
510
+ import { dataRequest, reconcileMutation } from '@gregale/data'
511
+
512
+ const response = await dataRequest(
513
+ db.rpc('read_note_create_receipt', {
514
+ idempotency_key: pending.key,
515
+ note_body: pending.body,
516
+ tag_names: pending.tags,
517
+ }).select('id,body,subject'),
518
+ { timeoutMs: 5000, signal },
519
+ )
520
+ const recovery = reconcileMutation(response, row =>
521
+ row.subject === pending.subject && row.body === pending.body,
522
+ )
523
+ if (recovery.outcome === 'confirmed') {
524
+ showSavedNote(recovery.row.id)
525
+ } else {
526
+ // Keep the pending key/payload. Review conflicts or check again explicitly.
527
+ }
528
+ ```
529
+
530
+ `reconcileMutation` classifies a completed lookup; it executes no query, polling
531
+ or retry. Its synchronous predicate binds the returned receipt to the original
532
+ operation and preserves projected row types. Confirm only the same API, subject,
533
+ tenant where applicable, key and full payload. The SQL lookup compares payload
534
+ fields that are not part of the returned projection. Use `validateRpcResponse`
535
+ first when the application also requires runtime response validation.
536
+
537
+ Results are `confirmed` with `row`, `payload_conflict` with the original error,
538
+ or `unresolved` with `reason` (`not_found`, `request_failed`, `invalid_receipt`,
539
+ `replay_expired`).
540
+ Status is preserved, as are request errors on unresolved failures. Malformed,
541
+ multiple or mismatched rows and predicate exceptions cannot confirm the write;
542
+ rejected data and predicate exceptions are omitted. Conflict classification
543
+ requires HTTP 409, `PT409` and `idempotency_payload_conflict` exactly.
544
+
545
+ No visible receipt can mean uncommitted work, a hidden operation or a purged
546
+ receipt. It never proves rollback and does not authorize a new write. Keep retry
547
+ explicit. For legacy contracts, purging ends the guarantee for that key and a
548
+ replay can create a duplicate. Confirmation describes the original committed
549
+ response, even if the business row was subsequently edited or deleted.
550
+
551
+ ### Opt-in v2 replay expiry
552
+
553
+ The starter's `0012_note_replay_expiry.sql` adds
554
+ `create_note_with_tags_once_v2` and `read_note_create_receipt_v2`. Apply the
555
+ migration, owner RPC grants and schema refresh, then regenerate types before
556
+ using these functions. Legacy functions keep their original retention contract.
557
+
558
+ ```ts
559
+ import { createReplayKeyV2, classifyDataError, dataRequest } from '@gregale/data'
560
+
561
+ // Save this entire operation under its original API and identity before sending.
562
+ const pending = {
563
+ contract: 'v2', subject: session.subject,
564
+ key: createReplayKeyV2(), body: 'hello', tags: ['work'],
565
+ }
566
+ const result = await dataRequest(db.rpc('create_note_with_tags_once_v2', {
567
+ idempotency_key: pending.key, note_body: pending.body, tag_names: pending.tags,
568
+ }), { timeoutMs: 5000 })
569
+ if (classifyDataError(result.error, { status: result.status })?.category === 'replay_expired') {
570
+ // Keep pending. Check the original receipt or resolve through business review.
571
+ // Never generate a replacement key automatically.
572
+ }
573
+ ```
574
+
575
+ Keys are UUIDv7 values using the client clock and Web Crypto randomness. V2 uses
576
+ the key's embedded timestamp plus **24 hours**, allowing at most **five minutes**
577
+ of future clock skew. Server wall time decides expiry, including after lock
578
+ waits; a slow client clock shortens the available window. Client timestamps are
579
+ not trusted to assert when an operation actually began. Preserve the exact key:
580
+ changing its timestamp or contract version creates another operation namespace.
581
+
582
+ Expired writes return HTTP 410, `PT410`, `idempotency_key_expired`, even after
583
+ receipt cleanup. `classifyDataError` exposes `replay_expired` with `reconcile`
584
+ guidance. The v2 lookup can still confirm a retained expired receipt; if missing,
585
+ the exact expiry response becomes `unresolved` / `replay_expired`. Expiry cannot
586
+ prove whether an earlier attempt committed. No helper retries or replaces keys.
587
+ Invalid UUID versions/variants return `PT400` / `idempotency_key_invalid`, and
588
+ timestamps beyond the clock allowance return `PT400` / `idempotency_key_in_future`.
589
+
590
+ The migration cleanup tool accepts `--contract v2` and deletes only receipts whose
591
+ key deadline has closed. Keep the fixed v2 window unchanged; a longer policy needs
592
+ a new version to avoid reviving purged keys. The guarantee covers this SQL
593
+ contract under an accurate database clock and retained database history. Owner
594
+ schema changes, restores that lose receipts and external effects need separate
595
+ recovery policies.
596
+
597
+ ### Versioned updates and deletes
598
+
599
+ The starter's `0013_note_mutation_receipts.sql` adds opt-in conditional writes
600
+ `update_note_once_v2` and `delete_note_once_v2`. Both require a UUIDv7 operation
601
+ key, note ID and expected version. Update additionally accepts `note_patch` with
602
+ only non-null `body` text and/or integer `priority`. Apply migrations and owner
603
+ RPC permissions, refresh the API, regenerate types and install the paired SDK.
604
+
605
+ ```ts
606
+ import { classifyVersionedMutation, createReplayKeyV2, dataRequest, reconcileMutation } from '@gregale/data'
607
+
608
+ // Persist args and original API/identity/contract/action before the first send.
609
+ const subject = session.subject
610
+ const args = {
611
+ idempotency_key: createReplayKeyV2(), note_id: note.id,
612
+ expected_version: note.version, note_patch: { body: 'edited' },
613
+ }
614
+ const matches = (row: { id: number; subject: string; version: number; body: string }) =>
615
+ row.id === args.note_id && row.subject === subject &&
616
+ row.version === args.expected_version + 1 && row.body === args.note_patch.body
617
+ const response = await dataRequest(
618
+ db.rpc('update_note_once_v2', args).select('id,subject,version,body'),
619
+ { timeoutMs: 5000 },
620
+ )
621
+ const outcome = classifyVersionedMutation(response, matches)
622
+
623
+ // For an uncertain write, check the original receipt explicitly.
624
+ const read = await dataRequest(
625
+ db.rpc('read_note_update_receipt_v2', args).select('id,subject,version,body'),
626
+ { timeoutMs: 5000 },
627
+ )
628
+ const recovery = reconcileMutation(read, matches)
629
+ ```
630
+
631
+ `classifyVersionedMutation` classifies a completed write result, without executing
632
+ or retrying anything. Its synchronous predicate preserves selected types and
633
+ binds the snapshot to the original operation. Outcomes are `applied` with the
634
+ original row, `version_conflict`, `payload_conflict`, or `unresolved` with the
635
+ existing reconciliation reasons. Only HTTP 409 / `PT409` /
636
+ `idempotency_version_conflict` becomes `version_conflict`; generic conflicts do
637
+ not acquire this meaning. Original errors/status are preserved. An empty success
638
+ result stays unresolved. Expiry remains unresolved with reason `replay_expired`.
639
+
640
+ For delete, call `delete_note_once_v2` and recover with
641
+ `read_note_delete_receipt_v2`, using key, note ID and expected version. Its receipt
642
+ contains the deleted snapshot with that same version. Update returns the stored
643
+ post-update version. Both lookups are read-only and remain useful after subsequent
644
+ edits/deletion; replay returns the saved response without reapplying the mutation.
645
+
646
+ Stale, absent and RLS-hidden rows share the version-conflict response. Failed
647
+ mutations leave no success receipt and reserve no key. A conflict alone cannot
648
+ confirm an earlier uncertain write. Preserve the original operation and never
649
+ automatically replace its key or expected version. Updates/deletes share a key
650
+ namespace, independent of creation; changing action, target, version or patch for
651
+ a successful key returns a payload conflict. The fixed v2 expiry/cleanup contract
652
+ also applies. Full setup and maintenance are documented in
653
+ [Data API recovery](../../docs/data-api.md#versioned-update-and-delete-recovery).
654
+
655
+ ### Bulk mutations with partial results
656
+
657
+ ```ts
658
+ import { bulkMutations } from '@gregale/data'
659
+
660
+ const results = await bulkMutations(edits, edit =>
661
+ db.from('documents').update({ body: edit.body })
662
+ .eq('id', edit.id).eq('version', edit.version).select('id,body,version'),
663
+ { batchSize: 100, concurrency: 2, timeoutMs: 5000, signal, onProgress },
664
+ )
665
+ ```
666
+
667
+ Each item runs once in its own transaction. `batchSize` is a scheduling window,
668
+ not an atomic database batch. Results preserve input order and selected row
669
+ types, distinguishing `applied`, `conflict`, `error`, `uncertain`, `skipped`, and
670
+ `invalid`. Cancellation skips queued items and aborts active requests. Progress
671
+ contains aggregate counts only; observer failures do not interrupt execution.
672
+
673
+ Reconcile uncertain writes before retrying. Use idempotent RPCs or versioned
674
+ conditional mutations where needed. A single normal `insert([...])` request
675
+ retains its existing atomic semantics. See the
676
+ [bulk document example](../../examples/data-api-bulk/README.md) for full outcomes,
677
+ transaction boundaries and retry guidance.
678
+
679
+ ### Classify errors for application recovery
680
+
681
+ ```ts
682
+ import { classifyDataError } from '@gregale/data'
683
+
684
+ const result = await db.from('notes').insert(input).retry(false)
685
+ const failure = classifyDataError(result.error, { status: result.status })
686
+ if (failure?.category === 'unique_violation') {
687
+ showValidationMessage('That value is already in use.')
688
+ }
689
+ ```
690
+
691
+ The helper returns `null` for a null/undefined error. Otherwise it returns frozen
692
+ metadata with `category`, `recovery`, `code`, `status`, and the unchanged, typed
693
+ `original` error. It also accepts errors caught from `throwOnError()`; omit status
694
+ when no response status is available. It never executes a request or changes
695
+ retry settings. `.retry(false)` in this example disables the underlying client's
696
+ retries explicitly.
697
+
698
+ | Category | Recognized code or fallback | Recovery guidance |
699
+ | --- | --- | --- |
700
+ | `unique_violation` | SQLSTATE `23505` | `change_input` |
701
+ | `foreign_key_violation` | SQLSTATE `23503` | `change_input` |
702
+ | `lock_conflict` | SQLSTATE `55P03` | `wait` |
703
+ | `deadlock` | SQLSTATE `40P01` | `wait` |
704
+ | `authentication` | `token_required`, `token_invalid`, `PGRST301`–`PGRST303`, HTTP 401 | `authenticate` |
705
+ | `permission_denied` | SQLSTATE `42501`, `origin_not_allowed`, HTTP 403 | `check_permissions` |
706
+ | `contract_mismatch` | `schema_contract_mismatch` | `refresh_contract` |
707
+ | `timeout` | `request_timeout`, `query_timeout`, `request_deadline_exceeded`, `data_api_sql_deadline_exceeded`, HTTP 504 | `reconcile` |
708
+ | `cancelled` | `request_cancelled`, SQLSTATE `57014` | `reconcile` |
709
+ | `response_too_large` | `response_too_large` | `reconcile` |
710
+ | `rate_limited` | `data_api_rate_limited`, HTTP 429 | `wait` |
711
+ | `concurrency_limited` | `data_api_concurrency_limited` | `wait` |
712
+ | `unavailable` | `data_api_unavailable`, `data_api_overloaded`, `serving_contract_unavailable`, `data_api_refresh_unavailable`, HTTP 503 | `check_service` |
713
+ | `no_response` | Status 0 with no recognized code | `reconcile` |
714
+ | `unknown` | Other errors | `inspect` |
715
+
716
+ Recognized codes take precedence over HTTP fallback. Messages, details and hints
717
+ never determine the category. Generic 409/`PT409` errors do not establish a
718
+ contract mismatch; SQLSTATE `57014` establishes cancellation, not its cause.
719
+ Pass the response status to classify SQL `PT503` maintenance errors as unavailable.
720
+ Native exceptions without a recognized code or supplied status remain unknown;
721
+ use `dataRequest()` for stable deadline/cancellation codes.
722
+
723
+ Recovery values are suggestions, not instructions to retry. Timeouts,
724
+ cancellation, response-size limits, missing responses, and service failures do not prove a mutation
725
+ rolled back. Reconcile writes or use an application-owned idempotency contract
726
+ before replaying them. `refresh_contract` means review the rollout and regenerate
727
+ appropriate client types; it does not automatically change a pinned fingerprint.
728
+ An empty RLS-filtered result is not a permission error. The preserved original
729
+ error and its code can contain application or database information: use curated
730
+ UI messages and do not blindly log or display the classification object.
731
+
732
+ New managed Data API logins default to a five-second lock timeout and retain the
733
+ 15-second statement timeout. `55P03` also covers NOWAIT refusal, so the category
734
+ does not prove which lock policy fired. An uncaught contention error rolls back
735
+ the failing request's transaction, including earlier transactional RPC writes;
736
+ sequences and external effects are excluded. It cannot establish whether an
737
+ earlier attempt committed. Wait and review the whole operation before explicit
738
+ retry, using its idempotency/receipt contract when needed. Normal and throwing
739
+ CRUD/RPC errors keep their original code and private details; neither category
740
+ causes automatic replay. Existing roles and open pools require the documented
741
+ credential-policy upgrade and reconnect workflow; an SDK update does not alter
742
+ SQL defaults. Pinned PostgREST 14.3 already retries deadlocks and serialization
743
+ failures within its SQL transaction machinery. A deadlock may resolve and return
744
+ success from a single HTTP request; the SDK classification applies if `40P01`
745
+ actually reaches the caller and does not disable or extend engine retries.
746
+
747
+ An owner can opt the updated runtime into SQL deadlines across internal transaction
748
+ retries after installing the matching database hooks. The fixed gateway expiry
749
+ caps each attempt's remaining SQL budget. A hook that observes expiry returns
750
+ `data_api_sql_deadline_exceeded`, classified as `timeout` / `reconcile`, including
751
+ `throwOnError()` errors. A main statement interrupted by PostgreSQL can instead
752
+ return `57014`; its category remains `cancelled`. An invalid/missing hook contract
753
+ is a server setup failure, not evidence of mutation success. The SDK adds no retry
754
+ or database installation behavior. Review the original operation/receipt before
755
+ explicit replay; HTTP cancellation alone cannot establish SQL completion.
756
+
757
+ The updated runtime limits normal REST/RPC bodies to 16 MiB, independently of
758
+ row count. Known oversized lengths return `502 response_too_large`; overflow
759
+ after headers closes the incomplete body and can instead produce status 0 /
760
+ `no_response`. Generic HTTP 502 errors remain `unknown`. Use `onResponse` to
761
+ retain the header request ID before body consumption and correlate gateway logs.
762
+ Reduce future projections/page sizes or RPC output, and reconcile writes before
763
+ replay: SQL can commit before the result is rejected. The SDK adds no retries.
764
+
765
+ Optional gateway user-rate limits return `429 data_api_rate_limited` with
766
+ `Retry-After: 1`. Budgets follow verified subjects across token rotation and
767
+ routes, and are local to each runtime. The stable gateway code establishes a
768
+ rejection before SQL dispatch; generic HTTP 429 alone does not. Recovery `wait`
769
+ means defer the next request decision; it adds no timers or automatic retries,
770
+ including for ordinary GET/POST queries and `throwOnError()`. Preserve uncertain
771
+ write reconciliation when the error comes from another service or SQL.
772
+
773
+ Optional `DATA_API_USER_CONCURRENCY` limits concurrent authenticated requests per
774
+ verified subject within one runtime. Rejections use
775
+ `429 data_api_concurrency_limited`, classified as `concurrency_limited` / `wait`.
776
+ Their `Retry-After` is advisory (one second for active work, up to 15 for uncertain
777
+ dispatch cooldown). The rejected call did not reach SQL, but an earlier call may
778
+ still be running or may have committed after cancellation. Review that earlier
779
+ outcome separately. The SDK adds no retries, timers or automatic mutation replay;
780
+ generic HTTP 429 continues to fall back to `rate_limited`.
781
+
782
+ ### Validate RPC arguments at runtime
783
+
784
+ Use `validatedRpc()` when inputs come from forms, JSON or JavaScript. Supply a
785
+ synchronous application-owned parser that returns the generated RPC argument
786
+ object, then construct the typed query in the callback:
787
+
788
+ ```ts
789
+ import { validatedRpc, classifyDataError } from '@gregale/data'
790
+
791
+ // Example approved RPC: create_note({ body: string }) -> note ID.
792
+ const noteArgs = {
793
+ parse(value: unknown): { body: string } {
794
+ if (!value || typeof value !== 'object' || !('body' in value) ||
795
+ typeof value.body !== 'string' || !value.body.trim()) {
796
+ throw new Error('Body is required')
797
+ }
798
+ return { body: value.body.trim() }
799
+ },
800
+ }
801
+
802
+ const outcome = await validatedRpc(formInput, noteArgs,
803
+ args => db.rpc('create_note', args).retry(false))
804
+ if (outcome.outcome === 'validation_failed') {
805
+ showValidationMessage('Enter a note body.')
806
+ } else {
807
+ const { data, error, status } = outcome.result
808
+ const failure = classifyDataError(error, { status })
809
+ // data retains the generated create_note return type.
810
+ }
811
+ ```
812
+
813
+ A compatible schema's `.parse()` method, such as a synchronous Zod parser, can
814
+ replace `noteArgs`. The parser owns required fields, unknown-key policy, defaults,
815
+ transformations and field-level UI validation. It must return an argument object;
816
+ null, arrays, primitives and asynchronous outputs are rejected. Empty objects
817
+ support zero-argument RPCs. Generated types check parser output against the chosen
818
+ RPC, including required arguments and value types. Select the appropriate schema
819
+ on `db` before calling the helper.
820
+
821
+ Invalid input returns `{ outcome: 'validation_failed', error }` with a
822
+ `RpcValidationError` and code `RPC_ARGUMENT_VALIDATION_FAILED`. No query callback,
823
+ token lookup or request runs. The error excludes input values and original parser
824
+ exceptions; obtain field feedback separately through your application's parser,
825
+ using its own disclosure policy.
826
+
827
+ Valid input returns `{ outcome: 'completed', result }`. Completed means the
828
+ callback was awaited, not that the database operation succeeded: inspect
829
+ `result.error` as usual. The helper preserves the original result by reference,
830
+ including null results and server/transport errors. `throwOnError()` and callback
831
+ exceptions propagate unchanged. The callback can apply projections, filters,
832
+ `.single()`, abort signals or `dataRequest()` without losing result inference.
833
+
834
+ The helper does not change retry settings. `.retry(false)` above explicitly
835
+ prevents automatic retries; write reconciliation and idempotency remain
836
+ application responsibilities. PostgreSQL constraints and RLS remain authoritative.
837
+ The helper does not clone parser input or output; application parsers own any
838
+ mutation they perform.
839
+
840
+ ### Validate entire RPC responses
841
+
842
+ Generated declarations describe expected responses; they do not validate received
843
+ JSON. Use `validateRpcResponse()` with a synchronous application-owned parser
844
+ after awaiting a direct RPC or a completed `validatedRpc()` result:
845
+
846
+ ```ts
847
+ import { validateRpcResponse, classifyDataError } from '@gregale/data'
848
+
849
+ // Example approved scalar RPC: count_notes() -> integer.
850
+ const result = await db.rpc('count_notes', {}).retry(false)
851
+ const checked = validateRpcResponse(result, {
852
+ parse(value: unknown): number {
853
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {
854
+ throw new Error('Invalid count')
855
+ }
856
+ return value
857
+ },
858
+ })
859
+
860
+ if (checked.outcome === 'validated') {
861
+ const count: number = checked.result.data
862
+ } else if (checked.outcome === 'request_failed') {
863
+ const failure = classifyDataError(checked.result.error, {
864
+ status: checked.result.status,
865
+ })
866
+ } else {
867
+ // RPC_RESPONSE_VALIDATION_FAILED; the original HTTP status is retained.
868
+ showValidationMessage('The server returned an unexpected result.')
869
+ }
870
+ ```
871
+
872
+ The parser checks the entire `data` value: a scalar, JSON object, projected row or
873
+ row array. It owns validation, transformations, nullable handling and cloning.
874
+ Synchronous schema parsers such as Zod's `.parse()` are compatible. Null or
875
+ undefined successful data is passed through the parser, not silently skipped.
876
+ Async parser outputs are rejected. To validate individual JSON fields in an
877
+ already checked row result, the existing `validateJson()` remains available.
878
+
879
+ `validated` returns a shallow copy of the response with parser output in `data`
880
+ and `error: null`. The parser output determines the new data type; status, count
881
+ and other response metadata retain their original types and values.
882
+ `request_failed` returns the original response by reference without parsing when
883
+ it has an error or a non-2xx status, including transport/deadline failures.
884
+ `validation_failed` returns a `RpcResponseValidationError` with code
885
+ `RPC_RESPONSE_VALIDATION_FAILED` and the original HTTP status. It excludes rejected
886
+ data and the original parser exception. Its HTTP status can still be 200.
887
+
888
+ This helper executes no requests and changes no retry settings. A response
889
+ validation failure does not imply rollback: a mutation may already have committed.
890
+ Reconcile through reads or a reviewed idempotency contract before considering
891
+ another write; never automatically replay on a validation failure. Raw request
892
+ failure results may still contain private database errors. Use curated UI messages.
893
+ The helper does not mutate the original response itself, but parsers receive its
894
+ data by reference and are responsible for any mutation they perform.
895
+
896
+ ### Encrypted continuation tokens for server routes
897
+
898
+ Existing `cursorPage`/`cursorFrom` helpers use raw ordering values. For routes that
899
+ accept an untrusted continuation token, use `createCursorPager` on the server:
900
+
901
+ ```ts
902
+ import { createCursorPager } from '@gregale/data'
903
+
904
+ // Load a stable 32-byte random key from server-side configuration. Never send it
905
+ // to a browser or commit it. Reuse the pager across requests on this server.
906
+ const pager = await createCursorPager({ key: cursorKeyBytes, ttlMs: 15 * 60_000, maxPageSize: 100 })
907
+ const order = [
908
+ { column: 'created_at' },
909
+ { column: 'id', unique: true },
910
+ ] as const
911
+
912
+ // Derive scope from verified application identity/tenant/permission claims.
913
+ const page = await pager.page(
914
+ db.from('orders').select('id,created_at,total').eq('team_id', authenticatedTeamId),
915
+ {
916
+ order, size: 50,
917
+ scope: { identity: trustedIdentityScope, schemaFingerprint: currentSchemaFingerprint },
918
+ after: incomingContinuation,
919
+ },
920
+ )
921
+ // Return page.result and page.nextCursor to the caller. API errors remain in result.
922
+ ```
923
+
924
+ Ordering columns must appear in the selected projection and have scalar types.
925
+ A single primary key works with `[{ column: 'id', unique: true }]`; timestamp-plus-ID
926
+ ordering uses the example above. The final column must actually be non-null and
927
+ unique within the filtered result. The helper validates the declaration and values,
928
+ but does not inspect database constraints. Use a fresh GET array query with no root
929
+ order, limit, offset or range applied beforehand. Nested projection types are preserved.
930
+
931
+ Tokens use authenticated AES-GCM encryption with fresh random nonces. They bind the
932
+ actual query endpoint, schema, filter/projection parameters, ordering, page size,
933
+ identity scope and schema fingerprint. Refreshing a JWT need not change the scope;
934
+ include tenant and relevant permission/version claims in a server-derived scope.
935
+ Create the data client with `expectedSchemaFingerprint` matching the scope so the
936
+ gateway also rejects schema changes before executing a read. The scope alone does
937
+ not detect an unannounced gateway migration. The helper does not authenticate callers,
938
+ read claims from JWTs or replace RLS.
939
+ Keep the key exclusively on trusted servers. A browser should submit issued tokens
940
+ to your route; browser-only clients can continue using the raw keyset helpers.
941
+
942
+ The default TTL is 15 minutes (maximum one day), and default maximum page size is
943
+ 999. One additional row is fetched to determine continuation within Gregale's
944
+ 1,000-row response cap. Each page returns at most the requested size, with
945
+ `nextCursor`, `previousCursor`, `hasMore` and `direction`. `hasMore` describes the
946
+ current traversal direction. `before` returns nearest preceding rows in reverse
947
+ order, as with `cursorPage`; use `previousCursor` to continue backward and reverse
948
+ rows for normal display. Empty/error results return no continuations. First forward
949
+ pages have no previous cursor. Continuations describe boundaries, not guaranteed
950
+ nonempty pages if records are subsequently deleted.
951
+
952
+ Malformed/tampered tokens fail with `CursorPaginationError.code = 'invalid_cursor'`.
953
+ Expired tokens use `expired_cursor`; changed query, scope, ordering, page size or
954
+ schema uses `incompatible_cursor`. These failures occur before query execution.
955
+ Invalid options or malformed successful responses have separate codes. Key rotation
956
+ invalidates existing tokens; restart pagination rather than attempting an automatic
957
+ fallback. Tokens are bounded to 16 KiB and ordering to 16 columns. Cursor values
958
+ and filters are not exposed in plaintext tokens. Pagination does not provide a
959
+ snapshot across requests, and changing ordered values can still move rows between
960
+ pages. Index the filter and ordering columns and review plans with representative data.
961
+
962
+ ### Validating atomic batch receipts
963
+
964
+ For the starter's opt-in v2 batch RPC, use its `prepareNoteBatch` and
965
+ `noteBatchMatches` helpers with the paired generated types. `classifyVersionedMutation`
966
+ and `reconcileMutation` accept synchronous type guards, so validating the entire
967
+ one-row envelope narrows its nested JSON to typed ordered snapshots. Every item
968
+ must match before the result becomes `applied` or `confirmed`; classify completed
969
+ responses only. These helpers send no requests or retries.
970
+
971
+ The explicit RPC commits 1–100 distinct note updates/deletes atomically and
972
+ stores one receipt; SDK `bulkMutations` retains its separate-request semantics.
973
+ Retain the original API, identity, key, contract and ordered operation array for
974
+ read-only recovery. Expiry, absence and conflicts cannot alone resolve an earlier
975
+ uncertain request. See the [batch contract and example](../../docs/data-api.md#atomic-note-batch-recovery).
976
+
977
+ ### Durable mutation journals
978
+
979
+ `createMutationJournal` optionally saves an original prepared operation through
980
+ an application-supplied atomic store and synchronous lossless parser. Provide
981
+ its exact API URL, optional schema fingerprint, subject, tenant (or null), and
982
+ contract. Operations must include that context, one canonical UUIDv7 `key` and
983
+ the complete captured payload. The parser must return identical canonical JSON;
984
+ restoration cannot silently drop fields or replace a key. The generated v2
985
+ transaction client supplies this parser and an easier persistent wrapper.
986
+
987
+ Use `createIndexedDBMutationStore({databaseName:'my-app-data-mutations'})` in a
988
+ browser to opt into a dedicated, bounded store with strict transaction durability.
989
+ It opens lazily. `journal.prepare(slot,operation)` inserts only into an empty
990
+ stable slot. `journal.load(slot)` validates and freezes saved data without a
991
+ request. `journal.dispatch(entry,send)` commits uncertainty before invoking the
992
+ explicit callback once, returning its new `entry` and original `response`.
993
+ Competing tabs cannot claim the same prepared revision. Storage failures prevent
994
+ sending; callback errors leave the uncertain operation available through load.
995
+
996
+ `journal.reconcile(entry,response,matches)` classifies a completed response using
997
+ the existing receipt contract/type guard. `journal.recover(entry,lookup,matches)`
998
+ explicitly calls a receipt-read callback and classifies it. Neither performs
999
+ retries or key replacement. They return `result`, `entry` and `persistence`:
1000
+ `saved`, `unchanged`, `conflict` or `storage_failed`. Proven server success remains
1001
+ in `result` even if a local confirmation marker cannot be committed. Empty,
1002
+ expired, conflicting and malformed receipts keep the original operation.
1003
+
1004
+ Only `journal.removeConfirmed(entry)` explicitly removes local records, with
1005
+ an atomic revision check. It cannot clear uncertainty or delete newer work from
1006
+ a reused slot. Handles belong to one journal instance; load new ones after
1007
+ restart. API/identity/tenant/contract/fingerprint mismatches and invalid records
1008
+ fail closed without returning or changing the saved operation.
1009
+
1010
+ Default bounds: 100 IndexedDB records, 8 MiB stored values, 1 MiB per record,
1011
+ 256 UTF-8 bytes per slot/database name and JSON depth 64. Count/byte budgets may
1012
+ be lowered. No automatic pruning, background polling or fallback storage is
1013
+ introduced. Applications intentionally persist payloads; their parser should
1014
+ allow only the prepared operation and exclude credentials/request options.
1015
+ Origin storage must remain available for recovery; clearing/evicting it or losing
1016
+ the device removes that local copy. A custom `MutationJournalStore` must implement
1017
+ durable atomic `compareExchange(slot,expected,next)` across its users; separate
1018
+ localStorage reads/writes do not provide that guarantee.
1019
+
1020
+ Errors use `MutationJournalError.code` with curated messages: storage_unavailable,
1021
+ storage_full, conflict, invalid_record, invalid_operation, context_mismatch,
1022
+ invalid_entry, not_prepared and not_confirmed. Original storage/parser exceptions
1023
+ and rejected payloads are omitted. See the [generated v2 integration](../../docs/data-api.md#durable-pending-operation-recovery).