@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
@@ -0,0 +1,271 @@
1
+ /**
2
+ * The live-query frame contract (ADR-20261016151947), mirroring the Go reference client
3
+ * in pkg/livequery/liveproto. Both run the shared session fixtures.
4
+ */
5
+ export const LIVE_TYPES = {
6
+ subscribe: 'live.subscribe',
7
+ renew: 'live.renew',
8
+ unsubscribe: 'live.unsubscribe',
9
+ rows: 'live.rows',
10
+ changes: 'live.changes',
11
+ progress: 'live.progress',
12
+ renewed: 'live.renewed',
13
+ error: 'live.error',
14
+ };
15
+ export class LiveProtocolError extends Error {
16
+ constructor(message) { super(`live protocol violation: ${message}`); this.name = 'LiveProtocolError'; }
17
+ }
18
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
19
+ const isVersion = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
20
+ const isValues = (v) => Array.isArray(v) && v.every((x) => x === null || typeof x === 'string');
21
+ /** Decodes and shape-checks a server frame. */
22
+ export function parseLiveServerFrame(data) {
23
+ let f;
24
+ try {
25
+ f = JSON.parse(data);
26
+ }
27
+ catch {
28
+ throw new LiveProtocolError('frame is not JSON');
29
+ }
30
+ if (!isObject(f) || typeof f.type !== 'string')
31
+ throw new LiveProtocolError('frame has no type');
32
+ const str = (k) => typeof f[k] === 'string';
33
+ const ok = (() => {
34
+ switch (f.type) {
35
+ case LIVE_TYPES.rows:
36
+ return str('subscription') && str('database') && isVersion(f.version) && str('snapshot') && typeof f.expires === 'number'
37
+ && Array.isArray(f.columns) && f.columns.every((c) => isObject(c) && typeof c.name === 'string' && typeof c.type === 'string')
38
+ && Array.isArray(f.rows) && f.rows.every((r) => isObject(r) && typeof r.id === 'string' && isValues(r.values))
39
+ && typeof f.complete === 'boolean' && (f.ordered === undefined || typeof f.ordered === 'boolean');
40
+ case LIVE_TYPES.changes:
41
+ return str('subscription') && isVersion(f.base) && isVersion(f.version) && str('snapshot')
42
+ && Array.isArray(f.xids) && f.xids.every((x) => typeof x === 'string')
43
+ && Array.isArray(f.changes) && f.changes.every((c) => isObject(c) && typeof c.id === 'string'
44
+ && (c.op === 'remove' || (c.op === 'upsert' && isValues(c.values))))
45
+ && (f.order === undefined || (Array.isArray(f.order) && f.order.every((x) => typeof x === 'string')));
46
+ case LIVE_TYPES.progress:
47
+ return str('database') && str('snapshot');
48
+ case LIVE_TYPES.renewed:
49
+ return str('subscription') && typeof f.expires === 'number';
50
+ case LIVE_TYPES.error:
51
+ return str('code') && str('message') && typeof f.closed === 'boolean';
52
+ default:
53
+ return false;
54
+ }
55
+ })();
56
+ if (!ok)
57
+ throw new LiveProtocolError(`malformed ${String(f.type)} frame`);
58
+ return f;
59
+ }
60
+ /** A parsed pg_snapshot ("xmin:xmax:xip,..."): the transactions a result reflects. */
61
+ export class LiveSnapshot {
62
+ xmin;
63
+ xmax;
64
+ xip;
65
+ text;
66
+ constructor(xmin, xmax, xip, text) {
67
+ this.xmin = xmin;
68
+ this.xmax = xmax;
69
+ this.xip = xip;
70
+ this.text = text;
71
+ }
72
+ static parse(text) {
73
+ const parts = text.split(':');
74
+ const digits = /^(0|[1-9][0-9]*)$/;
75
+ if (parts.length !== 3 || !digits.test(parts[0]) || !digits.test(parts[1]))
76
+ throw new LiveProtocolError(`bad snapshot ${text}`);
77
+ const xmin = BigInt(parts[0]);
78
+ const xmax = BigInt(parts[1]);
79
+ if (xmin > xmax)
80
+ throw new LiveProtocolError(`bad snapshot ${text}`);
81
+ const xip = new Set();
82
+ if (parts[2] !== '') {
83
+ for (const raw of parts[2].split(',')) {
84
+ if (!digits.test(raw))
85
+ throw new LiveProtocolError(`bad snapshot ${text}`);
86
+ const x = BigInt(raw);
87
+ if (x < xmin || x >= xmax)
88
+ throw new LiveProtocolError(`bad snapshot ${text}`);
89
+ xip.add(x);
90
+ }
91
+ }
92
+ return new LiveSnapshot(xmin, xmax, xip, text);
93
+ }
94
+ static zero = LiveSnapshot.parse('0:0:');
95
+ /** Whether a committed transaction is visible, as pg_visible_in_snapshot decides. */
96
+ visible(xid) {
97
+ if (xid < this.xmin)
98
+ return true;
99
+ if (xid >= this.xmax)
100
+ return false;
101
+ return !this.xip.has(xid);
102
+ }
103
+ /** Whether every transaction visible in o is visible here: this is not older than o. */
104
+ covers(o) {
105
+ for (const x of this.xip)
106
+ if (o.visible(x))
107
+ return false;
108
+ if (this.xmax >= o.xmax)
109
+ return true;
110
+ if (o.xmax - this.xmax > BigInt(o.xip.size))
111
+ return false;
112
+ for (let x = this.xmax; x < o.xmax; x++)
113
+ if (o.visible(x))
114
+ return false;
115
+ return true;
116
+ }
117
+ }
118
+ /**
119
+ * One subscription's result as the client holds it. apply() refuses frames
120
+ * that break the contract; the caller then resubscribes.
121
+ */
122
+ export class LiveResult {
123
+ database = '';
124
+ columns = [];
125
+ ordered = false;
126
+ version = 0;
127
+ snapshot = LiveSnapshot.zero;
128
+ expires = 0;
129
+ stale = false;
130
+ closed = false;
131
+ error;
132
+ isReady = false;
133
+ rows = new Map();
134
+ order = [];
135
+ pending;
136
+ resyncing = false;
137
+ get ready() { return this.isReady; }
138
+ /** After a (re)subscribe, the next live.rows may start a new version sequence. */
139
+ resubscribe() { this.resyncing = true; this.pending = undefined; }
140
+ apply(frame) {
141
+ if (this.closed)
142
+ throw new LiveProtocolError('frame after the subscription closed');
143
+ switch (frame.type) {
144
+ case 'live.rows': return this.applyRows(frame);
145
+ case 'live.changes': return this.applyChanges(frame);
146
+ case 'live.progress':
147
+ if (frame.database !== this.database || !this.isReady || this.stale)
148
+ return;
149
+ this.snapshot = this.advance(frame.snapshot);
150
+ return;
151
+ case 'live.renewed':
152
+ this.expires = frame.expires;
153
+ this.stale = false;
154
+ return;
155
+ case 'live.error':
156
+ this.error = frame;
157
+ if (frame.closed)
158
+ this.closed = true;
159
+ else
160
+ this.stale = true;
161
+ }
162
+ }
163
+ applyRows(f) {
164
+ const p = this.pending;
165
+ if (p && (p.version !== f.version || p.snapshot !== f.snapshot)) {
166
+ throw new LiveProtocolError(`live.rows for version ${f.version} interleaved with version ${p.version}`);
167
+ }
168
+ const acc = p ?? { ...f, rows: [] };
169
+ acc.rows = [...acc.rows, ...f.rows];
170
+ if (!f.complete) {
171
+ this.pending = acc;
172
+ return;
173
+ }
174
+ this.pending = undefined;
175
+ const snap = LiveSnapshot.parse(acc.snapshot);
176
+ if (this.isReady && !this.resyncing && acc.version <= this.version) {
177
+ throw new LiveProtocolError(`live.rows version ${acc.version} does not advance ${this.version}`);
178
+ }
179
+ const rows = new Map();
180
+ const order = [];
181
+ for (const r of acc.rows) {
182
+ if (rows.has(r.id))
183
+ throw new LiveProtocolError(`row ${r.id} twice`);
184
+ if (r.values.length !== acc.columns.length)
185
+ throw new LiveProtocolError(`row ${r.id} has ${r.values.length} values for ${acc.columns.length} columns`);
186
+ rows.set(r.id, r.values);
187
+ if (acc.ordered)
188
+ order.push(r.id);
189
+ }
190
+ this.database = acc.database;
191
+ this.columns = acc.columns;
192
+ this.ordered = acc.ordered === true;
193
+ this.version = acc.version;
194
+ this.snapshot = snap;
195
+ this.expires = acc.expires;
196
+ this.rows = rows;
197
+ this.order = order;
198
+ this.isReady = true;
199
+ this.stale = false;
200
+ this.resyncing = false;
201
+ }
202
+ applyChanges(f) {
203
+ if (!this.isReady || this.pending)
204
+ throw new LiveProtocolError('live.changes before a complete live.rows');
205
+ if (f.base !== this.version)
206
+ throw new LiveProtocolError(`live.changes from version ${f.base}, client holds ${this.version}`);
207
+ if (f.version <= f.base)
208
+ throw new LiveProtocolError(`live.changes version ${f.version} does not advance ${f.base}`);
209
+ if (this.stale)
210
+ throw new LiveProtocolError('live.changes for a stale subscription');
211
+ const snap = this.advance(f.snapshot);
212
+ for (const x of f.xids) {
213
+ if (!/^(0|[1-9][0-9]*)$/.test(x) || !snap.visible(BigInt(x)))
214
+ throw new LiveProtocolError(`transaction ${x} is not visible in ${f.snapshot}`);
215
+ }
216
+ const rows = new Map(this.rows);
217
+ let added = false;
218
+ for (const c of f.changes) {
219
+ if (c.op === 'upsert') {
220
+ if (c.values.length !== this.columns.length)
221
+ throw new LiveProtocolError(`row ${c.id} has ${c.values.length} values for ${this.columns.length} columns`);
222
+ if (!rows.has(c.id))
223
+ added = true;
224
+ rows.set(c.id, c.values);
225
+ }
226
+ else {
227
+ if (!rows.delete(c.id))
228
+ throw new LiveProtocolError(`remove of unknown row ${c.id}`);
229
+ }
230
+ }
231
+ let order = this.order;
232
+ if (f.order !== undefined) {
233
+ if (!this.ordered)
234
+ throw new LiveProtocolError('order for an unordered result');
235
+ if (f.order.length !== rows.size)
236
+ throw new LiveProtocolError(`order lists ${f.order.length} rows, result has ${rows.size}`);
237
+ const seen = new Set();
238
+ for (const id of f.order) {
239
+ if (!rows.has(id) || seen.has(id))
240
+ throw new LiveProtocolError('order is not a permutation of the result');
241
+ seen.add(id);
242
+ }
243
+ order = [...f.order];
244
+ }
245
+ else if (this.ordered && added) {
246
+ throw new LiveProtocolError('rows added to an ordered result without an order');
247
+ }
248
+ else if (this.ordered) {
249
+ order = order.filter((id) => rows.has(id));
250
+ }
251
+ this.rows = rows;
252
+ this.order = order;
253
+ this.version = f.version;
254
+ this.snapshot = snap;
255
+ this.resyncing = false; // the server resumed the sequence the client held
256
+ }
257
+ advance(text) {
258
+ const snap = LiveSnapshot.parse(text);
259
+ if (!snap.covers(this.snapshot))
260
+ throw new LiveProtocolError(`snapshot ${text} is older than ${this.snapshot.text}`);
261
+ return snap;
262
+ }
263
+ /** The rows: in the query's order when it has one, by row ID otherwise. */
264
+ entries() {
265
+ if (this.ordered)
266
+ return this.order.map((id) => ({ id, values: this.rows.get(id) }));
267
+ return [...this.rows.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([id, values]) => ({ id, values }));
268
+ }
269
+ /** Whether the result reflects a committed transaction: the check behind awaitTxId. */
270
+ sees(xid) { return this.isReady && this.snapshot.visible(xid); }
271
+ }
@@ -0,0 +1,22 @@
1
+ import type { LiveConnection, LiveQueryState, LiveReadOptions, LiveSealedOptions } from './client.js';
2
+ export type UseLiveQueryOptions<Row> = Omit<LiveSealedOptions<Row>, 'sealed'>;
3
+ export type UseLiveQueryResult<Row> = LiveQueryState<Row> & {
4
+ /** Resolves once the rows reflect a committed transaction (pg_current_xact_id() of a write). */
5
+ awaitTxId(xid: bigint | number | string, options?: {
6
+ signal?: AbortSignal;
7
+ }): Promise<void>;
8
+ };
9
+ /**
10
+ * Subscribes a component to a sealed live query. Server rendering and the
11
+ * first client render show initialRows; the live result replaces them.
12
+ * A new seal string subscribes again; renewals go through refresh.
13
+ */
14
+ export declare function useLiveQuery<Row = Record<string, unknown>>(connection: LiveConnection | null | undefined, sealed: string | null | undefined, options?: UseLiveQueryOptions<Row>): UseLiveQueryResult<Row>;
15
+ /**
16
+ * Subscribes a component to a Data API read as the signed-in user (RLS
17
+ * mode). A different database, read or schema subscribes again; token is
18
+ * called whenever a fresh one is needed.
19
+ */
20
+ export declare function useLiveRead<Row = Record<string, unknown>>(connection: LiveConnection | null | undefined, options: (LiveReadOptions<Row> & {
21
+ identityScope?: string;
22
+ }) | null | undefined): UseLiveQueryResult<Row>;
@@ -0,0 +1,59 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
2
+ import { LiveQueryClosedError } from './client.js';
3
+ const noSubscription = () => () => { };
4
+ /**
5
+ * Subscribes a component to a sealed live query. Server rendering and the
6
+ * first client render show initialRows; the live result replaces them.
7
+ * A new seal string subscribes again; renewals go through refresh.
8
+ */
9
+ export function useLiveQuery(connection, sealed, options = {}) {
10
+ const latest = useRef(options);
11
+ latest.current = options;
12
+ return useLive(connection, sealed ?? null, options.initialRows, (conn) => {
13
+ const { refresh, parse, initialRows } = latest.current;
14
+ return conn.query({ sealed: sealed, initialRows, parse, refresh: refresh && (() => latest.current.refresh()) });
15
+ });
16
+ }
17
+ /**
18
+ * Subscribes a component to a Data API read as the signed-in user (RLS
19
+ * mode). A different database, read or schema subscribes again; token is
20
+ * called whenever a fresh one is needed.
21
+ */
22
+ export function useLiveRead(connection, options) {
23
+ const latest = useRef(options);
24
+ latest.current = options;
25
+ const key = options ? JSON.stringify([options.database, options.schema ?? '', options.read, options.identityScope ?? '', options.anonymous === true ? 'anonymous' : 'serverKey' in options ? 'server' : 'user', 'subject' in options ? options.subject : '']) : null;
26
+ return useLive(connection, key, options?.initialRows, (conn) => {
27
+ const o = latest.current;
28
+ const read = { database: o.database, read: o.read, schema: o.schema, initialRows: o.initialRows, parse: o.parse };
29
+ if (o.anonymous === true)
30
+ return conn.query({ ...read, anonymous: true });
31
+ if (typeof o.serverKey === 'string')
32
+ return conn.query({ ...read, serverKey: o.serverKey, subject: o.subject });
33
+ return conn.query({ ...read, token: () => latest.current.token() });
34
+ });
35
+ }
36
+ function useLive(connection, key, initialRows, open) {
37
+ const opener = useRef(open);
38
+ opener.current = open;
39
+ const [opened, setOpened] = useState(null);
40
+ // Do not render the previous identity's rows while the effect catches up.
41
+ const query = opened?.key === key && opened.connection === connection ? opened.query : null;
42
+ useEffect(() => {
43
+ if (!connection || key === null)
44
+ return;
45
+ const q = opener.current(connection);
46
+ setOpened({ key, connection, query: q });
47
+ return () => {
48
+ q.close();
49
+ setOpened(null);
50
+ };
51
+ }, [connection, key]);
52
+ const initial = useMemo(() => Object.freeze({
53
+ status: 'connecting', rows: initialRows ?? [], keys: [], columns: [], snapshot: null, error: undefined,
54
+ }), [key, connection]); // identity changes discard the previous subscription's rows
55
+ const getInitial = useCallback(() => initial, [initial]);
56
+ const state = useSyncExternalStore(query ? query.subscribe : noSubscription, query ? query.getSnapshot : getInitial, getInitial);
57
+ const awaitTxId = useCallback((xid, o) => (query ? query.awaitTxId(xid, o) : Promise.reject(new LiveQueryClosedError(undefined))), [query]);
58
+ return useMemo(() => ({ ...state, awaitTxId }), [state, awaitTxId]);
59
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Sealed live queries (ADR-20261016151947). A backend seals a query, its parameters and
3
+ * its database with the per-database live secret; the browser presents the
4
+ * seal to subscribe. Sealing is local Web Crypto (Node 22, browsers, edge
5
+ * runtimes) and makes no network call. The format matches pkg/livequery/seal
6
+ * byte for byte (testdata/vector.json there).
7
+ */
8
+ export declare const LIVE_SEAL_DEFAULT_TTL_SECONDS = 60;
9
+ export declare const LIVE_SEAL_MAX_TTL_SECONDS = 300;
10
+ export declare class LiveSealError extends Error {
11
+ constructor(message: string);
12
+ }
13
+ /** A query with PostgreSQL text parameters, as the sql tag produces. */
14
+ export type LiveQueryText = Readonly<{
15
+ text: string;
16
+ params: ReadonlyArray<string | null>;
17
+ }>;
18
+ export type LiveSealOptions = {
19
+ /** Seal lifetime; default 60 seconds, at most 300. */
20
+ ttlSeconds?: number;
21
+ /** Overrides the clock (seconds since the epoch), for tests. */
22
+ now?: number;
23
+ };
24
+ export type LiveSealer = Readonly<{
25
+ /** The key ID the secret seals under. */
26
+ kid: string;
27
+ seal(query: LiveQueryText, options?: LiveSealOptions): Promise<string>;
28
+ }>;
29
+ /**
30
+ * Seals with the database's live secret (GREGALE_LIVE_SECRET) for that
31
+ * database (GREGALE_LIVE_DATABASE). Keep the secret on the server.
32
+ */
33
+ export declare function createLiveSealer(options: {
34
+ secret: string;
35
+ database: string;
36
+ }): Promise<LiveSealer>;
37
+ /** Test hook: the known-answer vector seals with a fixed nonce. */
38
+ export declare function sealWithFixedNonceForTest(secretText: string, plaintext: string, nonce: Uint8Array): Promise<string>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Sealed live queries (ADR-20261016151947). A backend seals a query, its parameters and
3
+ * its database with the per-database live secret; the browser presents the
4
+ * seal to subscribe. Sealing is local Web Crypto (Node 22, browsers, edge
5
+ * runtimes) and makes no network call. The format matches pkg/livequery/seal
6
+ * byte for byte (testdata/vector.json there).
7
+ */
8
+ export const LIVE_SEAL_DEFAULT_TTL_SECONDS = 60;
9
+ export const LIVE_SEAL_MAX_TTL_SECONDS = 300;
10
+ const SQL_MAX_BYTES = 32 << 10;
11
+ const PARAMS_MAX = 256;
12
+ const PARAM_MAX_BYTES = 16 << 10;
13
+ const PAYLOAD_MAX_BYTES = 48 << 10;
14
+ const DATABASE_MAX_BYTES = 128;
15
+ export class LiveSealError extends Error {
16
+ constructor(message) { super(message); this.name = 'LiveSealError'; }
17
+ }
18
+ const encoder = new TextEncoder();
19
+ function base64url(bytes) {
20
+ let binary = '';
21
+ for (const b of bytes)
22
+ binary += String.fromCharCode(b);
23
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
24
+ }
25
+ function fromBase64url(text) {
26
+ if (!/^[A-Za-z0-9_-]*$/.test(text))
27
+ return undefined;
28
+ const padded = text.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (text.length % 4)) % 4);
29
+ try {
30
+ return Uint8Array.from(atob(padded), (c) => c.charCodeAt(0));
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
36
+ async function parseSecret(secret) {
37
+ const match = /^glsk1_([0-9a-f]{16})_([A-Za-z0-9_-]+)$/.exec(secret);
38
+ const material = match ? fromBase64url(match[2]) : undefined;
39
+ if (!match || !material || material.length !== 32)
40
+ throw new LiveSealError('invalid live secret');
41
+ const ikm = await crypto.subtle.importKey('raw', material, 'HKDF', false, ['deriveKey']);
42
+ const key = await crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(), info: encoder.encode('gregale live seal v1') }, ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
43
+ return { kid: match[1], key };
44
+ }
45
+ function checkText(what, value, limit) {
46
+ const bytes = encoder.encode(value).length;
47
+ if (bytes > limit)
48
+ throw new LiveSealError(`${what} is ${bytes} bytes, limit ${limit}`);
49
+ if (value.includes('\u0000'))
50
+ throw new LiveSealError(`${what} contains a NUL character`);
51
+ if (/[\uD800-\uDFFF]/.test(value.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '')))
52
+ throw new LiveSealError(`${what} is not valid Unicode`);
53
+ }
54
+ /**
55
+ * Seals with the database's live secret (GREGALE_LIVE_SECRET) for that
56
+ * database (GREGALE_LIVE_DATABASE). Keep the secret on the server.
57
+ */
58
+ export async function createLiveSealer(options) {
59
+ const secret = await parseSecret(options.secret);
60
+ const database = options.database;
61
+ if (typeof database !== 'string' || database === '')
62
+ throw new LiveSealError('a database is required');
63
+ checkText('database', database, DATABASE_MAX_BYTES);
64
+ return Object.freeze({
65
+ kid: secret.kid,
66
+ async seal(query, sealOptions = {}) {
67
+ const ttl = sealOptions.ttlSeconds ?? LIVE_SEAL_DEFAULT_TTL_SECONDS;
68
+ if (!Number.isInteger(ttl) || ttl < 1 || ttl > LIVE_SEAL_MAX_TTL_SECONDS)
69
+ throw new LiveSealError(`seal lifetime ${ttl} s, limit ${LIVE_SEAL_MAX_TTL_SECONDS} s`);
70
+ if (typeof query.text !== 'string' || query.text.trim() === '')
71
+ throw new LiveSealError('SQL is required');
72
+ checkText('SQL', query.text, SQL_MAX_BYTES);
73
+ if (query.params.length > PARAMS_MAX)
74
+ throw new LiveSealError(`${query.params.length} parameters, limit ${PARAMS_MAX}`);
75
+ query.params.forEach((p, i) => { if (p !== null)
76
+ checkText(`parameter ${i + 1}`, p, PARAM_MAX_BYTES); });
77
+ const iat = Math.floor(sealOptions.now ?? Date.now() / 1000);
78
+ const plaintext = JSON.stringify({ db: database, sql: query.text, params: [...query.params], iat, exp: iat + ttl });
79
+ const plain = encoder.encode(plaintext);
80
+ if (plain.length > PAYLOAD_MAX_BYTES)
81
+ throw new LiveSealError(`sealed query is ${plain.length} bytes, limit ${PAYLOAD_MAX_BYTES}`);
82
+ const nonce = crypto.getRandomValues(new Uint8Array(12));
83
+ return sealWithNonce(secret, plain, nonce);
84
+ },
85
+ });
86
+ }
87
+ async function sealWithNonce(secret, plain, nonce) {
88
+ const header = `gls1.${secret.kid}`;
89
+ const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, additionalData: encoder.encode(header) }, secret.key, plain));
90
+ const body = new Uint8Array(nonce.length + sealed.length);
91
+ body.set(nonce);
92
+ body.set(sealed, nonce.length);
93
+ return `${header}.${base64url(body)}`;
94
+ }
95
+ /** Test hook: the known-answer vector seals with a fixed nonce. */
96
+ export async function sealWithFixedNonceForTest(secretText, plaintext, nonce) {
97
+ return sealWithNonce(await parseSecret(secretText), encoder.encode(plaintext), nonce);
98
+ }
@@ -0,0 +1,11 @@
1
+ import type { LiveQueryText } from './seal.js';
2
+ /**
3
+ * Builds a parameterised query: each interpolated value becomes $n and
4
+ * travels as PostgreSQL text, which the database parses as the parameter's
5
+ * type. Values never become SQL.
6
+ *
7
+ * sql`SELECT id, body FROM messages WHERE channel_id = ${id} ORDER BY id DESC LIMIT ${50}`
8
+ */
9
+ export declare function sql(strings: TemplateStringsArray, ...values: unknown[]): LiveQueryText;
10
+ /** PostgreSQL text form of a JavaScript value. */
11
+ export declare function toPostgresText(value: unknown): string | null;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Builds a parameterised query: each interpolated value becomes $n and
3
+ * travels as PostgreSQL text, which the database parses as the parameter's
4
+ * type. Values never become SQL.
5
+ *
6
+ * sql`SELECT id, body FROM messages WHERE channel_id = ${id} ORDER BY id DESC LIMIT ${50}`
7
+ */
8
+ export function sql(strings, ...values) {
9
+ let text = strings[0];
10
+ const params = [];
11
+ values.forEach((value, i) => {
12
+ params.push(toPostgresText(value));
13
+ text += `$${params.length}` + strings[i + 1];
14
+ });
15
+ return Object.freeze({ text, params: Object.freeze(params) });
16
+ }
17
+ /** PostgreSQL text form of a JavaScript value. */
18
+ export function toPostgresText(value) {
19
+ if (value === null || value === undefined)
20
+ return null;
21
+ switch (typeof value) {
22
+ case 'string':
23
+ return value;
24
+ case 'number':
25
+ if (!Number.isFinite(value))
26
+ throw new TypeError('live query parameters must be finite numbers');
27
+ return String(value);
28
+ case 'bigint':
29
+ return value.toString();
30
+ case 'boolean':
31
+ return value ? 'true' : 'false';
32
+ }
33
+ if (value instanceof Date) {
34
+ if (Number.isNaN(value.getTime()))
35
+ throw new TypeError('invalid Date parameter');
36
+ return value.toISOString();
37
+ }
38
+ if (value instanceof Uint8Array) {
39
+ return '\\x' + Array.from(value, (b) => b.toString(16).padStart(2, '0')).join('');
40
+ }
41
+ if (Array.isArray(value))
42
+ return arrayLiteral(value);
43
+ if (typeof value === 'object')
44
+ return JSON.stringify(value);
45
+ throw new TypeError(`unsupported live query parameter of type ${typeof value}`);
46
+ }
47
+ // A PostgreSQL array literal; elements are quoted unless NULL.
48
+ function arrayLiteral(values) {
49
+ const items = values.map((v) => {
50
+ if (Array.isArray(v))
51
+ return arrayLiteral(v);
52
+ const text = toPostgresText(v);
53
+ if (text === null)
54
+ return 'NULL';
55
+ return '"' + text.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
56
+ });
57
+ return '{' + items.join(',') + '}';
58
+ }
@@ -0,0 +1,78 @@
1
+ import type { JsonParser } from './validation.js';
2
+ import { type MutationReconciliation } from './reconcile.js';
3
+ export declare const MUTATION_JOURNAL_LIMITS: Readonly<{
4
+ maxRecords: 100;
5
+ maxBytes: 8388608;
6
+ maxEntryBytes: 1048576;
7
+ maxSlotBytes: 256;
8
+ maxDepth: 64;
9
+ }>;
10
+ export type MutationJournalErrorCode = 'storage_unavailable' | 'storage_full' | 'conflict' | 'invalid_record' | 'invalid_operation' | 'context_mismatch' | 'invalid_entry' | 'not_prepared' | 'not_confirmed';
11
+ export declare class MutationJournalError extends Error {
12
+ readonly code: MutationJournalErrorCode;
13
+ constructor(code: MutationJournalErrorCode);
14
+ }
15
+ export type MutationJournalContext = Readonly<{
16
+ apiURL: string;
17
+ schemaFingerprint: string | null;
18
+ subject: string;
19
+ tenant: string | null;
20
+ contract: string;
21
+ }>;
22
+ export type JournalOperation = MutationJournalContext & Readonly<{
23
+ key: string;
24
+ }>;
25
+ export type MutationJournalState = 'prepared' | 'uncertain' | 'confirmed';
26
+ export type MutationJournalEntry<Operation extends JournalOperation> = Readonly<{
27
+ slot: string;
28
+ revision: string;
29
+ state: MutationJournalState;
30
+ operation: Operation;
31
+ }>;
32
+ /** compareExchange must atomically compare exact bytes and commit across all
33
+ * users of this store before resolving true. A localStorage read/write pair
34
+ * does not satisfy this contract. get returns untrusted serialized data.
35
+ */
36
+ export type MutationJournalStore = {
37
+ get(slot: string): Promise<unknown>;
38
+ compareExchange(slot: string, expected: string | null, next: string | null): Promise<boolean>;
39
+ };
40
+ export type JournalReconciliation<Operation extends JournalOperation, Row, Error> = {
41
+ result: MutationReconciliation<Row, Error>;
42
+ entry: MutationJournalEntry<Operation>;
43
+ persistence: 'unchanged' | 'saved' | 'conflict' | 'storage_failed';
44
+ };
45
+ type Response<Row, Error> = {
46
+ data: Row[] | null;
47
+ error: Error | null;
48
+ status: number;
49
+ };
50
+ export declare const journalByteLength: (value: string) => number;
51
+ export declare function journalSlot(slot: string): void;
52
+ /** Opt-in durable bookkeeping. Loading never sends requests. Only dispatch
53
+ * claims a prepared entry, and it commits uncertainty before calling send.
54
+ * Recovery callbacks must perform receipt reads. Nothing retries or expires
55
+ * an entry automatically; the database is authoritative about key expiry.
56
+ */
57
+ export declare function createMutationJournal<Operation extends JournalOperation>(options: {
58
+ store: MutationJournalStore;
59
+ context: MutationJournalContext;
60
+ parser: JsonParser<Operation>;
61
+ }): {
62
+ prepare: (slot: string, operation: Operation) => Promise<MutationJournalEntry<Operation>>;
63
+ load: (slot: string) => Promise<MutationJournalEntry<Operation> | null>;
64
+ dispatch: <Result>(entry: MutationJournalEntry<Operation>, send: (operation: Operation) => PromiseLike<Result>) => Promise<{
65
+ entry: MutationJournalEntry<Operation>;
66
+ response: Awaited<Result>;
67
+ }>;
68
+ reconcile: {
69
+ <Row, Error, Matched extends Row>(entry: MutationJournalEntry<Operation>, response: Response<Row, Error>, matches: (row: Row) => row is Matched): Promise<JournalReconciliation<Operation, Matched, Error>>;
70
+ <Row, Error>(entry: MutationJournalEntry<Operation>, response: Response<Row, Error>, matches: (row: Row) => boolean): Promise<JournalReconciliation<Operation, Row, Error>>;
71
+ };
72
+ recover: {
73
+ <Row, Error, Matched extends Row>(entry: MutationJournalEntry<Operation>, lookup: (operation: Operation) => PromiseLike<Response<Row, Error>>, matches: (row: Row) => row is Matched): Promise<JournalReconciliation<Operation, Matched, Error>>;
74
+ <Row, Error>(entry: MutationJournalEntry<Operation>, lookup: (operation: Operation) => PromiseLike<Response<Row, Error>>, matches: (row: Row) => boolean): Promise<JournalReconciliation<Operation, Row, Error>>;
75
+ };
76
+ removeConfirmed: (entry: MutationJournalEntry<Operation>) => Promise<void>;
77
+ };
78
+ export {};