@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.
- package/LICENSE +202 -0
- package/README.md +1022 -2
- package/dist/bulk.d.ts +61 -0
- package/dist/bulk.js +63 -0
- package/dist/client-fetch.d.ts +34 -0
- package/dist/client-fetch.js +62 -0
- package/dist/cursor-token.d.ts +52 -0
- package/dist/cursor-token.js +165 -0
- package/dist/cursor.d.ts +44 -0
- package/dist/cursor.js +75 -0
- package/dist/deadline.d.ts +19 -0
- package/dist/deadline.js +29 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +68 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.js +35 -0
- package/dist/indexeddb-mutation-store.d.ts +12 -0
- package/dist/indexeddb-mutation-store.js +139 -0
- package/dist/json.d.ts +34 -0
- package/dist/json.js +39 -0
- package/dist/live/client.d.ts +192 -0
- package/dist/live/client.js +508 -0
- package/dist/live/index.d.ts +31 -0
- package/dist/live/index.js +28 -0
- package/dist/live/protocol.d.ts +125 -0
- package/dist/live/protocol.js +271 -0
- package/dist/live/react.d.ts +22 -0
- package/dist/live/react.js +59 -0
- package/dist/live/seal.d.ts +38 -0
- package/dist/live/seal.js +98 -0
- package/dist/live/sql.d.ts +11 -0
- package/dist/live/sql.js +58 -0
- package/dist/mutation-journal.d.ts +78 -0
- package/dist/mutation-journal.js +223 -0
- package/dist/numeric.d.ts +8 -0
- package/dist/numeric.js +33 -0
- package/dist/optimistic.d.ts +24 -0
- package/dist/optimistic.js +18 -0
- package/dist/reconcile.d.ts +28 -0
- package/dist/reconcile.js +28 -0
- package/dist/replay-key.d.ts +8 -0
- package/dist/replay-key.js +27 -0
- package/dist/response.d.ts +33 -0
- package/dist/response.js +29 -0
- package/dist/rpc.d.ts +20 -0
- package/dist/rpc.js +31 -0
- package/dist/storage-uploads.d.ts +55 -0
- package/dist/storage-uploads.js +78 -0
- package/dist/storage.d.ts +74 -0
- package/dist/storage.js +89 -0
- package/dist/validation.d.ts +26 -0
- package/dist/validation.js +40 -0
- package/dist/versioned-mutation.d.ts +28 -0
- package/dist/versioned-mutation.js +13 -0
- package/package.json +19 -4
package/dist/errors.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { isReplayExpired } from './replay-key.js';
|
|
2
|
+
const categories = Object.freeze({
|
|
3
|
+
'23505': 'unique_violation',
|
|
4
|
+
'23503': 'foreign_key_violation',
|
|
5
|
+
'42501': 'permission_denied',
|
|
6
|
+
'55P03': 'lock_conflict',
|
|
7
|
+
'40P01': 'deadlock',
|
|
8
|
+
token_required: 'authentication',
|
|
9
|
+
token_invalid: 'authentication',
|
|
10
|
+
PGRST301: 'authentication',
|
|
11
|
+
PGRST302: 'authentication',
|
|
12
|
+
PGRST303: 'authentication',
|
|
13
|
+
origin_not_allowed: 'permission_denied',
|
|
14
|
+
schema_contract_mismatch: 'contract_mismatch',
|
|
15
|
+
query_timeout: 'timeout',
|
|
16
|
+
request_deadline_exceeded: 'timeout',
|
|
17
|
+
data_api_sql_deadline_exceeded: 'timeout',
|
|
18
|
+
response_too_large: 'response_too_large',
|
|
19
|
+
request_timeout: 'timeout',
|
|
20
|
+
request_cancelled: 'cancelled',
|
|
21
|
+
'57014': 'cancelled',
|
|
22
|
+
data_api_unavailable: 'unavailable',
|
|
23
|
+
data_api_shared_budget_unavailable: 'unavailable',
|
|
24
|
+
data_api_budget_identity_required: 'permission_denied',
|
|
25
|
+
data_api_overloaded: 'unavailable',
|
|
26
|
+
data_api_rate_limited: 'rate_limited',
|
|
27
|
+
data_api_concurrency_limited: 'concurrency_limited',
|
|
28
|
+
serving_contract_unavailable: 'unavailable',
|
|
29
|
+
data_api_refresh_unavailable: 'unavailable',
|
|
30
|
+
});
|
|
31
|
+
const recoveries = {
|
|
32
|
+
unique_violation: 'change_input', foreign_key_violation: 'change_input',
|
|
33
|
+
authentication: 'authenticate', permission_denied: 'check_permissions',
|
|
34
|
+
contract_mismatch: 'refresh_contract', timeout: 'reconcile', cancelled: 'reconcile',
|
|
35
|
+
unavailable: 'check_service', no_response: 'reconcile', response_too_large: 'reconcile', rate_limited: 'wait', concurrency_limited: 'wait', lock_conflict: 'wait', deadlock: 'wait', replay_expired: 'reconcile', unknown: 'inspect',
|
|
36
|
+
};
|
|
37
|
+
/** Classify without executing, retrying or changing an error. HTTP status is
|
|
38
|
+
* optional because throwOnError() exceptions do not retain response status.
|
|
39
|
+
* Recovery is guidance, never permission to replay a mutation.
|
|
40
|
+
*/
|
|
41
|
+
export function classifyDataError(error, options = {}) {
|
|
42
|
+
if (error === null || error === undefined)
|
|
43
|
+
return null;
|
|
44
|
+
const rawCode = typeof error === 'object' && 'code' in error ? error.code : undefined;
|
|
45
|
+
const code = typeof rawCode === 'string' ? rawCode : null;
|
|
46
|
+
const status = Number.isInteger(options.status) && (options.status === 0 || (options.status >= 100 && options.status <= 599)) ? options.status : null;
|
|
47
|
+
// Own-property lookup prevents arbitrary codes such as "constructor" from
|
|
48
|
+
// acquiring a category. The v2 expiry contract needs its exact SQLSTATE/message
|
|
49
|
+
// pair because PT410 is also available to unrelated customer RPCs.
|
|
50
|
+
let category = code !== null && Object.hasOwn(categories, code) ? categories[code] : 'unknown';
|
|
51
|
+
if (isReplayExpired(error) && (status === null || status === 410))
|
|
52
|
+
category = 'replay_expired';
|
|
53
|
+
if (category === 'unknown') {
|
|
54
|
+
if (status === 401)
|
|
55
|
+
category = 'authentication';
|
|
56
|
+
else if (status === 403)
|
|
57
|
+
category = 'permission_denied';
|
|
58
|
+
else if (status === 429)
|
|
59
|
+
category = 'rate_limited';
|
|
60
|
+
else if (status === 503)
|
|
61
|
+
category = 'unavailable';
|
|
62
|
+
else if (status === 504)
|
|
63
|
+
category = 'timeout';
|
|
64
|
+
else if (status === 0)
|
|
65
|
+
category = 'no_response';
|
|
66
|
+
}
|
|
67
|
+
return Object.freeze({ category, recovery: recoveries[category], code, status, original: error });
|
|
68
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { PostgrestClient } from '@supabase/postgrest-js';
|
|
2
|
+
import { type DataClientOptions } from './client-fetch.js';
|
|
3
|
+
export type { DataClientOptions, DataResponseInfo } from './client-fetch.js';
|
|
4
|
+
/** Application tokens authenticate data access; account-management keys do not. */
|
|
5
|
+
export declare function createDataClient<Database>(options: DataClientOptions): PostgrestClient<Database>;
|
|
6
|
+
export { PostgrestError } from '@supabase/postgrest-js';
|
|
7
|
+
export { parseLosslessJSON } from './numeric.js';
|
|
8
|
+
export type { NumericMode } from './numeric.js';
|
|
9
|
+
export { createStorageClient, StorageError } from './storage.js';
|
|
10
|
+
export type { StorageBucket, StorageClient, StorageObject, StorageUploadBody } from './storage.js';
|
|
11
|
+
export type { UploadSession, ResumableUploadOptions, StorageUploads } from './storage-uploads.js';
|
|
12
|
+
export { classifyDataError } from './errors.js';
|
|
13
|
+
export type { ClassifiedDataError, DataErrorCategory, DataErrorRecovery } from './errors.js';
|
|
14
|
+
export { validatedRpc, RpcValidationError } from './rpc.js';
|
|
15
|
+
export type { ValidatedRpcResult } from './rpc.js';
|
|
16
|
+
export { validateRpcResponse, RpcResponseValidationError } from './response.js';
|
|
17
|
+
export type { ValidatedRpcResponse } from './response.js';
|
|
18
|
+
export { jsonText, jsonValue, selectJson } from './json.js';
|
|
19
|
+
export type { Json, JsonPath, JsonProjection } from './json.js';
|
|
20
|
+
export { validateJson, JsonValidationError } from './validation.js';
|
|
21
|
+
export type { JsonParser, ValidatedJson } from './validation.js';
|
|
22
|
+
/** Preserve the exact projection and nested relationship types of a query. */
|
|
23
|
+
export type QueryResult<Query> = Query extends PromiseLike<infer Result> ? Result : never;
|
|
24
|
+
export type QueryData<Query> = QueryResult<Query> extends {
|
|
25
|
+
data: infer Data;
|
|
26
|
+
} ? NonNullable<Data> : never;
|
|
27
|
+
export type QueryError<Query> = QueryResult<Query> extends {
|
|
28
|
+
error: infer Error;
|
|
29
|
+
} ? NonNullable<Error> : never;
|
|
30
|
+
export type { PostgrestResponse, PostgrestSingleResponse, PostgrestMaybeSingleResponse } from '@supabase/postgrest-js';
|
|
31
|
+
export { cursorPage, cursorFrom } from './cursor.js';
|
|
32
|
+
export type { Cursor, CursorOrder } from './cursor.js';
|
|
33
|
+
export { dataRequest } from './deadline.js';
|
|
34
|
+
export { optimisticMutation } from './optimistic.js';
|
|
35
|
+
export type { OptimisticResult } from './optimistic.js';
|
|
36
|
+
export { bulkMutations } from './bulk.js';
|
|
37
|
+
export type { BulkOutcome, BulkProgress, BulkOptions } from './bulk.js';
|
|
38
|
+
export { reconcileMutation } from './reconcile.js';
|
|
39
|
+
export type { MutationReconciliation } from './reconcile.js';
|
|
40
|
+
export { createReplayKeyV2 } from './replay-key.js';
|
|
41
|
+
export { classifyVersionedMutation } from './versioned-mutation.js';
|
|
42
|
+
export type { VersionedMutationResult } from './versioned-mutation.js';
|
|
43
|
+
export { createCursorPager, CursorPaginationError } from './cursor-token.js';
|
|
44
|
+
export type { CursorScope, CursorPagerOptions, CursorPageResult } from './cursor-token.js';
|
|
45
|
+
export { createMutationJournal, MutationJournalError, MUTATION_JOURNAL_LIMITS } from './mutation-journal.js';
|
|
46
|
+
export type { MutationJournalContext, JournalOperation, MutationJournalState, MutationJournalEntry, MutationJournalStore, MutationJournalErrorCode, JournalReconciliation } from './mutation-journal.js';
|
|
47
|
+
export { createIndexedDBMutationStore } from './indexeddb-mutation-store.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { PostgrestClient } from '@supabase/postgrest-js';
|
|
2
|
+
import { authenticatedFetch, dataAPIBase } from './client-fetch.js';
|
|
3
|
+
import { numericFetch } from './numeric.js';
|
|
4
|
+
/** Application tokens authenticate data access; account-management keys do not. */
|
|
5
|
+
export function createDataClient(options) {
|
|
6
|
+
const send = numericFetch(authenticatedFetch(options), options.numericMode);
|
|
7
|
+
const restEndpoint = `${dataAPIBase(options.url)}/rest/v1`;
|
|
8
|
+
const expectedFingerprint = options.expectedSchemaFingerprint;
|
|
9
|
+
if (expectedFingerprint !== undefined && (typeof expectedFingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(expectedFingerprint)))
|
|
10
|
+
throw new Error('Expected schema fingerprint must be 64 lowercase hexadecimal characters');
|
|
11
|
+
// A distinct route fails closed on runtimes that predate the guard. A header
|
|
12
|
+
// alone could be ignored by an older gateway before executing a mutation.
|
|
13
|
+
const endpoint = expectedFingerprint === undefined ? restEndpoint : `${restEndpoint.slice(0, -'/rest/v1'.length)}/__gregale/contract/${expectedFingerprint}/rest/v1`;
|
|
14
|
+
// The generated contract retains the PostgREST schema shape and supports
|
|
15
|
+
// .schema('api'), typed inserts, filters, relationships and projections.
|
|
16
|
+
return new PostgrestClient(endpoint, { fetch: send });
|
|
17
|
+
}
|
|
18
|
+
export { PostgrestError } from '@supabase/postgrest-js';
|
|
19
|
+
export { parseLosslessJSON } from './numeric.js';
|
|
20
|
+
export { createStorageClient, StorageError } from './storage.js';
|
|
21
|
+
export { classifyDataError } from './errors.js';
|
|
22
|
+
export { validatedRpc, RpcValidationError } from './rpc.js';
|
|
23
|
+
export { validateRpcResponse, RpcResponseValidationError } from './response.js';
|
|
24
|
+
export { jsonText, jsonValue, selectJson } from './json.js';
|
|
25
|
+
export { validateJson, JsonValidationError } from './validation.js';
|
|
26
|
+
export { cursorPage, cursorFrom } from './cursor.js';
|
|
27
|
+
export { dataRequest } from './deadline.js';
|
|
28
|
+
export { optimisticMutation } from './optimistic.js';
|
|
29
|
+
export { bulkMutations } from './bulk.js';
|
|
30
|
+
export { reconcileMutation } from './reconcile.js';
|
|
31
|
+
export { createReplayKeyV2 } from './replay-key.js';
|
|
32
|
+
export { classifyVersionedMutation } from './versioned-mutation.js';
|
|
33
|
+
export { createCursorPager, CursorPaginationError } from './cursor-token.js';
|
|
34
|
+
export { createMutationJournal, MutationJournalError, MUTATION_JOURNAL_LIMITS } from './mutation-journal.js';
|
|
35
|
+
export { createIndexedDBMutationStore } from './indexeddb-mutation-store.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type MutationJournalStore } from './mutation-journal.js';
|
|
2
|
+
/** A dedicated, explicitly selected IndexedDB database. Read/write transactions
|
|
3
|
+
* serialize CAS and aggregate limits across tabs. Strict durability is required;
|
|
4
|
+
* storage errors never fall back to an in-memory or localStorage write.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createIndexedDBMutationStore(options: {
|
|
7
|
+
databaseName: string;
|
|
8
|
+
maxRecords?: number;
|
|
9
|
+
maxBytes?: number;
|
|
10
|
+
}): MutationJournalStore & {
|
|
11
|
+
close(): void;
|
|
12
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { MutationJournalError, MUTATION_JOURNAL_LIMITS, journalByteLength, journalSlot } from './mutation-journal.js';
|
|
2
|
+
/** A dedicated, explicitly selected IndexedDB database. Read/write transactions
|
|
3
|
+
* serialize CAS and aggregate limits across tabs. Strict durability is required;
|
|
4
|
+
* storage errors never fall back to an in-memory or localStorage write.
|
|
5
|
+
*/
|
|
6
|
+
export function createIndexedDBMutationStore(options) {
|
|
7
|
+
const databaseName = options.databaseName;
|
|
8
|
+
journalSlot(databaseName);
|
|
9
|
+
const maxRecords = options.maxRecords ?? MUTATION_JOURNAL_LIMITS.maxRecords;
|
|
10
|
+
const maxBytes = options.maxBytes ?? MUTATION_JOURNAL_LIMITS.maxBytes;
|
|
11
|
+
if (!Number.isSafeInteger(maxRecords) || maxRecords < 1 || maxRecords > MUTATION_JOURNAL_LIMITS.maxRecords ||
|
|
12
|
+
!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MUTATION_JOURNAL_LIMITS.maxBytes)
|
|
13
|
+
throw new MutationJournalError('invalid_entry');
|
|
14
|
+
let connection, closed = false;
|
|
15
|
+
const open = () => {
|
|
16
|
+
if (closed)
|
|
17
|
+
return Promise.reject(new MutationJournalError('storage_unavailable'));
|
|
18
|
+
return connection ??= new Promise((resolve, reject) => {
|
|
19
|
+
let failed = false;
|
|
20
|
+
try {
|
|
21
|
+
const factory = globalThis.indexedDB;
|
|
22
|
+
if (!factory)
|
|
23
|
+
throw new Error();
|
|
24
|
+
const request = factory.open(databaseName, 1);
|
|
25
|
+
request.onupgradeneeded = () => { request.result.createObjectStore('entries'); };
|
|
26
|
+
request.onerror = request.onblocked = () => { failed = true; reject(new MutationJournalError('storage_unavailable')); };
|
|
27
|
+
request.onsuccess = () => {
|
|
28
|
+
const db = request.result;
|
|
29
|
+
if (closed || failed) {
|
|
30
|
+
db.close();
|
|
31
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
db.onversionchange = () => { closed = true; db.close(); };
|
|
35
|
+
resolve(db);
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
async function get(slot) {
|
|
44
|
+
journalSlot(slot);
|
|
45
|
+
const db = await open();
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
try {
|
|
48
|
+
const transaction = db.transaction('entries', 'readonly');
|
|
49
|
+
const request = transaction.objectStore('entries').openCursor(slot);
|
|
50
|
+
let value = null, invalid = false;
|
|
51
|
+
request.onsuccess = () => {
|
|
52
|
+
if (request.result) {
|
|
53
|
+
value = request.result.value;
|
|
54
|
+
if (typeof value !== 'string') {
|
|
55
|
+
invalid = true;
|
|
56
|
+
transaction.abort();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
transaction.oncomplete = () => resolve(value);
|
|
61
|
+
transaction.onabort = () => reject(new MutationJournalError(invalid ? 'invalid_record' : 'storage_unavailable'));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async function compareExchange(slot, expected, next) {
|
|
69
|
+
journalSlot(slot);
|
|
70
|
+
for (const value of [expected, next])
|
|
71
|
+
if (value !== null && (typeof value !== 'string' || journalByteLength(value) > MUTATION_JOURNAL_LIMITS.maxEntryBytes))
|
|
72
|
+
throw new MutationJournalError('invalid_record');
|
|
73
|
+
const db = await open();
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
try {
|
|
76
|
+
const transaction = db.transaction('entries', 'readwrite', { durability: 'strict' });
|
|
77
|
+
if (transaction.durability !== 'strict') {
|
|
78
|
+
transaction.abort();
|
|
79
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const store = transaction.objectStore('entries');
|
|
83
|
+
let matched = false, failure;
|
|
84
|
+
const abort = (code) => { failure = new MutationJournalError(code); transaction.abort(); };
|
|
85
|
+
transaction.oncomplete = () => resolve(matched);
|
|
86
|
+
transaction.onabort = () => reject(failure ?? new MutationJournalError(transaction.error?.name === 'QuotaExceededError' ? 'storage_full' : 'storage_unavailable'));
|
|
87
|
+
const current = store.openCursor(slot);
|
|
88
|
+
current.onsuccess = () => {
|
|
89
|
+
const saved = current.result ? current.result.value : null;
|
|
90
|
+
if (current.result && typeof saved !== 'string') {
|
|
91
|
+
abort('invalid_record');
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (saved !== expected)
|
|
95
|
+
return;
|
|
96
|
+
matched = true;
|
|
97
|
+
let count = 0, bytes = 0;
|
|
98
|
+
const scan = store.openCursor();
|
|
99
|
+
scan.onsuccess = () => {
|
|
100
|
+
const cursor = scan.result;
|
|
101
|
+
if (cursor) {
|
|
102
|
+
if (typeof cursor.key !== 'string' || typeof cursor.value !== 'string' || cursor.value.length > MUTATION_JOURNAL_LIMITS.maxEntryBytes) {
|
|
103
|
+
abort('invalid_record');
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
count++;
|
|
107
|
+
bytes += journalByteLength(cursor.value);
|
|
108
|
+
if (count > MUTATION_JOURNAL_LIMITS.maxRecords || bytes > MUTATION_JOURNAL_LIMITS.maxBytes) {
|
|
109
|
+
abort('storage_full');
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
cursor.continue();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (next === null) {
|
|
116
|
+
store.delete(slot);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const nextCount = count + (expected === null ? 1 : 0);
|
|
120
|
+
const nextBytes = bytes - (expected === null ? 0 : journalByteLength(expected)) + journalByteLength(next);
|
|
121
|
+
if (nextCount > maxRecords || nextBytes > maxBytes) {
|
|
122
|
+
abort('storage_full');
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
store.put(next, slot);
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
reject(new MutationJournalError('storage_unavailable'));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
function close() {
|
|
135
|
+
closed = true;
|
|
136
|
+
void connection?.then(db => db.close()).catch(() => { });
|
|
137
|
+
}
|
|
138
|
+
return { get, compareExchange, close };
|
|
139
|
+
}
|
package/dist/json.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { PostgrestQueryBuilder, PostgrestFilterBuilder, UnstableGetResult } from '@supabase/postgrest-js';
|
|
2
|
+
/** JSON columns have no inferred key schema. JSON null is a valid value. */
|
|
3
|
+
export type Json = string | number | boolean | null | {
|
|
4
|
+
[key: string]: Json | undefined;
|
|
5
|
+
} | Json[];
|
|
6
|
+
export type JsonPath = readonly [string | number, ...(string | number)[]];
|
|
7
|
+
export type JsonProjection<Column extends string = string, Text extends boolean = boolean> = Readonly<{
|
|
8
|
+
column: Column;
|
|
9
|
+
path: JsonPath;
|
|
10
|
+
text: Text;
|
|
11
|
+
}>;
|
|
12
|
+
/** Extract text; missing paths, SQL NULL and JSON null yield null. */
|
|
13
|
+
export declare function jsonText<Column extends string>(column: Column, ...path: JsonPath): JsonProjection<Column, true>;
|
|
14
|
+
/** Extract arbitrary JSON; missing paths and SQL NULL also yield null. */
|
|
15
|
+
export declare function jsonValue<Column extends string>(column: Column, ...path: JsonPath): JsonProjection<Column, false>;
|
|
16
|
+
type SourceRow<Source> = Source extends PostgrestQueryBuilder<infer _C, infer _S, infer R, infer _N, infer _F> ? R['Row'] : Source extends PostgrestFilterBuilder<infer _C, infer _S, infer R, infer _D, infer _N, infer _F, infer _M, infer _T> ? R : never;
|
|
17
|
+
type BaseResult<Source, Base extends string> = Base extends '' ? {} : Source extends PostgrestQueryBuilder<infer C, infer S, infer R, infer N, infer F> ? UnstableGetResult<S, R['Row'], N, F, Base, C> : Source extends PostgrestFilterBuilder<infer C, infer S, infer R, infer _D, infer N, infer F, infer _M, infer _T> ? UnstableGetResult<S, R, N, F, Base, C> : never;
|
|
18
|
+
type CheckedFields<Source, Base extends string, Fields extends Record<string, JsonProjection>> = {
|
|
19
|
+
[Key in keyof Fields]: Fields[Key]['column'] extends keyof SourceRow<Source> ? Key extends string | number ? `${Key}` extends keyof BaseResult<Source, Base> ? never : Fields[Key] : never : never;
|
|
20
|
+
};
|
|
21
|
+
type Result<Base, Fields extends Record<string, JsonProjection>> = Base extends {
|
|
22
|
+
error: true;
|
|
23
|
+
} ? Base : Base & {
|
|
24
|
+
-readonly [Key in keyof Fields as Key extends string | number ? Key : never]: Fields[Key]['text'] extends true ? string | null : Json;
|
|
25
|
+
};
|
|
26
|
+
type Selection<Source, Base extends string, Fields extends Record<string, JsonProjection>> = Source extends PostgrestQueryBuilder<infer C, infer S, infer R, infer N, infer F> ? PostgrestFilterBuilder<C, S, R['Row'], Result<BaseResult<Source, Base>, Fields>[], N, F, 'GET'> : Source extends PostgrestFilterBuilder<infer C, infer S, infer R, infer D, infer N, infer F, infer M, infer T> ? PostgrestFilterBuilder<C, S, R, M extends 'RPC' ? D extends unknown[] ? Result<BaseResult<Source, Base>, Fields>[] : Result<BaseResult<Source, Base>, Fields> : Result<BaseResult<Source, Base>, Fields>[], N, F, M, T> : never;
|
|
27
|
+
/** Add nullable JSON aliases to a table/view, write or relation-set RPC projection.
|
|
28
|
+
* Base is the usual literal PostgREST select string; use '' for JSON aliases only.
|
|
29
|
+
* JSON aliases must not duplicate fields selected by Base.
|
|
30
|
+
*/
|
|
31
|
+
export declare function selectJson<Source extends {
|
|
32
|
+
select(columns: string): unknown;
|
|
33
|
+
}, const Base extends string, const Fields extends Record<string, JsonProjection>>(source: Source, base: Base & (string extends Base ? never : unknown), fields: Fields & CheckedFields<Source, Base, Fields> & (string extends keyof Fields ? never : number extends keyof Fields ? never : unknown)): Selection<Source, Base, Fields>;
|
|
34
|
+
export {};
|
package/dist/json.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
function identifier(value) {
|
|
2
|
+
if (!value || /["\\\u0000-\u001f\u007f]/.test(value))
|
|
3
|
+
throw new Error('JSON projection names must be nonempty and cannot contain quotes, backslashes or control characters');
|
|
4
|
+
return `"${value}"`;
|
|
5
|
+
}
|
|
6
|
+
function expression(projection) {
|
|
7
|
+
if (!projection || typeof projection.column !== 'string' || typeof projection.text !== 'boolean' || !Array.isArray(projection.path) || !projection.path.length)
|
|
8
|
+
throw new Error('Invalid JSON projection');
|
|
9
|
+
return identifier(projection.column) + projection.path.map((part, i) => {
|
|
10
|
+
if (typeof part !== 'string' && (typeof part !== 'number' || !Number.isSafeInteger(part)))
|
|
11
|
+
throw new Error('JSON array indexes must be safe integers');
|
|
12
|
+
const key = typeof part === 'string' ? identifier(part) : String(part);
|
|
13
|
+
return `${projection.text && i === projection.path.length - 1 ? '->>' : '->'}${key}`;
|
|
14
|
+
}).join('');
|
|
15
|
+
}
|
|
16
|
+
function projection(column, path, text) {
|
|
17
|
+
const result = Object.freeze({ column, path: Object.freeze([...path]), text });
|
|
18
|
+
expression(result);
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
/** Extract text; missing paths, SQL NULL and JSON null yield null. */
|
|
22
|
+
export function jsonText(column, ...path) {
|
|
23
|
+
return projection(column, path, true);
|
|
24
|
+
}
|
|
25
|
+
/** Extract arbitrary JSON; missing paths and SQL NULL also yield null. */
|
|
26
|
+
export function jsonValue(column, ...path) {
|
|
27
|
+
return projection(column, path, false);
|
|
28
|
+
}
|
|
29
|
+
/** Add nullable JSON aliases to a table/view, write or relation-set RPC projection.
|
|
30
|
+
* Base is the usual literal PostgREST select string; use '' for JSON aliases only.
|
|
31
|
+
* JSON aliases must not duplicate fields selected by Base.
|
|
32
|
+
*/
|
|
33
|
+
export function selectJson(source, base, fields) {
|
|
34
|
+
const aliases = Object.entries(fields).map(([alias, field]) => `${identifier(alias)}:${expression(field)}`);
|
|
35
|
+
if (!aliases.length)
|
|
36
|
+
throw new Error('At least one JSON projection is required');
|
|
37
|
+
// The SDK handles URL encoding, credentials, filters, cardinality and errors.
|
|
38
|
+
return source.select([...(base.trim() ? [base] : []), ...aliases].join(','));
|
|
39
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { type LiveColumn, type LiveErrorFrame } from './protocol.js';
|
|
2
|
+
/** The socket a live connection runs over: an app's realtime endpoint. */
|
|
3
|
+
export interface LiveSocket {
|
|
4
|
+
readonly readyState: number;
|
|
5
|
+
addEventListener(type: 'open' | 'message' | 'close' | 'error', listener: (event: unknown) => void): void;
|
|
6
|
+
removeEventListener(type: 'open' | 'message' | 'close' | 'error', listener: (event: unknown) => void): void;
|
|
7
|
+
send(data: string): void;
|
|
8
|
+
close(): void;
|
|
9
|
+
}
|
|
10
|
+
/** The realtime subprotocol that carries live frames. */
|
|
11
|
+
export declare const LIVE_SUBPROTOCOL = "gregale.realtime.v2";
|
|
12
|
+
type LiveSocketConstructor = new (url: string, protocols: string[]) => LiveSocket;
|
|
13
|
+
/**
|
|
14
|
+
* Opens sockets to a realtime endpoint for LiveConnection's connect option.
|
|
15
|
+
* Live frames carry their own credential, so the socket carries none. Pass a
|
|
16
|
+
* WebSocket class where there is no global one.
|
|
17
|
+
*/
|
|
18
|
+
export declare function liveSocket(url: string, WebSocketClass?: LiveSocketConstructor): () => LiveSocket;
|
|
19
|
+
export type LiveStatus = 'connecting' | 'live' | 'stale' | 'closed';
|
|
20
|
+
export type LiveQueryState<Row> = Readonly<{
|
|
21
|
+
status: LiveStatus;
|
|
22
|
+
/** Rows in the query's order when it has ORDER BY, otherwise in a stable order. */
|
|
23
|
+
rows: ReadonlyArray<Row>;
|
|
24
|
+
/** Stable row identities, aligned with rows (for list keys). */
|
|
25
|
+
keys: ReadonlyArray<string>;
|
|
26
|
+
columns: ReadonlyArray<LiveColumn>;
|
|
27
|
+
/** The snapshot the rows reflect (pg_snapshot text), once live. */
|
|
28
|
+
snapshot: string | null;
|
|
29
|
+
error: LiveErrorFrame | undefined;
|
|
30
|
+
}>;
|
|
31
|
+
type LiveRowOptions<Row> = {
|
|
32
|
+
/** Rows rendered on the server, shown until the live result arrives. */
|
|
33
|
+
initialRows?: ReadonlyArray<Row>;
|
|
34
|
+
/** Turns a row's PostgreSQL text values into a row; defaults to parseLiveRow. */
|
|
35
|
+
parse?: (values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>) => Row;
|
|
36
|
+
};
|
|
37
|
+
/** Sealed mode: a query the app's backend sealed. */
|
|
38
|
+
export type LiveSealedOptions<Row> = LiveRowOptions<Row> & {
|
|
39
|
+
/** A sealed query from the app's backend. */
|
|
40
|
+
sealed: string;
|
|
41
|
+
/** Fetches a fresh seal for the same query: before expiry, and to resume after a reconnect. */
|
|
42
|
+
refresh?: () => Promise<string>;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Who a live Data API read runs as. Row-level security decides every row in
|
|
46
|
+
* each case, as for the Data API itself.
|
|
47
|
+
*/
|
|
48
|
+
export type LiveReadCredential =
|
|
49
|
+
/** The signed-in user: called to subscribe, again before it expires, and after a reconnect. */
|
|
50
|
+
{
|
|
51
|
+
token: () => string | Promise<string>;
|
|
52
|
+
anonymous?: never;
|
|
53
|
+
serverKey?: never;
|
|
54
|
+
subject?: never;
|
|
55
|
+
}
|
|
56
|
+
/** A visitor without a session: only relations the Data API makes public, embedded ones included. */
|
|
57
|
+
| {
|
|
58
|
+
anonymous: true;
|
|
59
|
+
token?: never;
|
|
60
|
+
serverKey?: never;
|
|
61
|
+
subject?: never;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A Data API server key, for trusted backends only. realtimed refuses it on
|
|
65
|
+
* browser connections. subject acts for one application user.
|
|
66
|
+
*/
|
|
67
|
+
| {
|
|
68
|
+
serverKey: string;
|
|
69
|
+
subject?: string;
|
|
70
|
+
token?: never;
|
|
71
|
+
anonymous?: never;
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* RLS mode: a Data API read. The realtime endpoint verifies the user's token
|
|
75
|
+
* (or admits an anonymous or server-key read against the Data API's rules),
|
|
76
|
+
* and the database's row-level security decides every row.
|
|
77
|
+
*/
|
|
78
|
+
export type LiveReadOptions<Row> = LiveRowOptions<Row> & LiveReadCredential & {
|
|
79
|
+
/** The database the read is from, as bound to the app. */
|
|
80
|
+
database: string;
|
|
81
|
+
/** The PostgREST read ("messages?select=id,body&order=id.desc&limit=50"); see liveRead for a query builder. */
|
|
82
|
+
read: string;
|
|
83
|
+
/** The schema the read is in; defaults to the Data API's first exposed schema. */
|
|
84
|
+
schema?: string;
|
|
85
|
+
};
|
|
86
|
+
export type LiveQueryOptions<Row> = LiveSealedOptions<Row> | LiveReadOptions<Row>;
|
|
87
|
+
/**
|
|
88
|
+
* The row a postgrest-js query resolves to: a typed query from the generated
|
|
89
|
+
* contract gives a typed live row, anything else a plain record.
|
|
90
|
+
*/
|
|
91
|
+
export type LiveReadRow<Query> = Query extends PromiseLike<infer Response> ? LiveDataRow<Response extends {
|
|
92
|
+
data: infer Data;
|
|
93
|
+
} ? Data : never> : Record<string, unknown>;
|
|
94
|
+
type LiveDataRow<Data> = [Data] extends [never] ? Record<string, unknown> : Data extends null ? never : Data extends ReadonlyArray<infer Row> ? Row : Data;
|
|
95
|
+
/**
|
|
96
|
+
* The Data API read a postgrest-js query (from createDataClient) would send,
|
|
97
|
+
* for a live query in RLS mode, with a parser that decodes rows as the Data
|
|
98
|
+
* API returns them, so the query's generated row type holds:
|
|
99
|
+
* connection.query({ database, token, ...liveRead(data.from('messages').select('id, body').eq('channel_id', 1)) })
|
|
100
|
+
*/
|
|
101
|
+
export declare function liveRead<Query>(query: Query): {
|
|
102
|
+
read: string;
|
|
103
|
+
schema?: string;
|
|
104
|
+
parse: (values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>) => LiveReadRow<Query>;
|
|
105
|
+
};
|
|
106
|
+
export type LiveConnectionOptions = {
|
|
107
|
+
/** Opens an authenticated socket to the app's realtime endpoint (called again on every reconnect). */
|
|
108
|
+
connect: () => LiveSocket | Promise<LiveSocket>;
|
|
109
|
+
/** Delay before reconnect attempt n (from 1); default capped exponential backoff with jitter. */
|
|
110
|
+
reconnectDelayMs?: (attempt: number) => number;
|
|
111
|
+
/** Renew this long before a seal expires; default 15 seconds or a fifth of its lifetime. */
|
|
112
|
+
renewEarlyMs?: number;
|
|
113
|
+
/** Clock and timers, for tests. */
|
|
114
|
+
clock?: {
|
|
115
|
+
now(): number;
|
|
116
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
117
|
+
clearTimeout(handle: unknown): void;
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
export declare class LiveQueryClosedError extends Error {
|
|
121
|
+
readonly frame: LiveErrorFrame | undefined;
|
|
122
|
+
constructor(frame: LiveErrorFrame | undefined);
|
|
123
|
+
}
|
|
124
|
+
/** Parses common PostgreSQL types; everything else stays text. */
|
|
125
|
+
export declare function parseLiveRow(values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>): Record<string, unknown>;
|
|
126
|
+
export declare function parseLiveValue(value: string | null, type: string): unknown;
|
|
127
|
+
/** Decodes a live row as the Data API (PostgREST) returns it in JSON. */
|
|
128
|
+
export declare function parseDataAPIRow(values: ReadonlyArray<string | null>, columns: ReadonlyArray<LiveColumn>, lossless?: boolean): Record<string, unknown>;
|
|
129
|
+
/**
|
|
130
|
+
* Decodes one PostgreSQL text value as PostgREST encodes it in JSON: numbers
|
|
131
|
+
* for integer, numeric and float types (non-finite values stay strings, as
|
|
132
|
+
* JSON has none), ISO 8601 timestamps, arrays element by element, and JSON.
|
|
133
|
+
* Embedded resources already arrive as JSON. Composite columns stay text.
|
|
134
|
+
*/
|
|
135
|
+
export declare function parseDataAPIValue(value: string | null, type: string, lossless?: boolean): unknown;
|
|
136
|
+
/**
|
|
137
|
+
* One connection to an app's realtime endpoint, carrying any number of live
|
|
138
|
+
* queries. It reconnects with backoff and resumes each query from the
|
|
139
|
+
* version it holds.
|
|
140
|
+
*/
|
|
141
|
+
export declare class LiveConnection {
|
|
142
|
+
private readonly options;
|
|
143
|
+
private readonly clock;
|
|
144
|
+
private readonly queries;
|
|
145
|
+
private socket;
|
|
146
|
+
private open;
|
|
147
|
+
private closed;
|
|
148
|
+
private attempt;
|
|
149
|
+
private reconnectTimer;
|
|
150
|
+
private readonly listeners;
|
|
151
|
+
constructor(options: LiveConnectionOptions);
|
|
152
|
+
/** Subscribes to a sealed query, or (RLS mode) a Data API read as the user. */
|
|
153
|
+
query<Row = Record<string, unknown>>(options: LiveQueryOptions<Row>): LiveQuery<Row>;
|
|
154
|
+
/** Closes every query and the socket. */
|
|
155
|
+
close(): void;
|
|
156
|
+
/** @internal */
|
|
157
|
+
send(frame: Record<string, unknown>): void;
|
|
158
|
+
/** @internal */
|
|
159
|
+
forget(id: string): void;
|
|
160
|
+
/** @internal */
|
|
161
|
+
get timers(): {
|
|
162
|
+
now(): number;
|
|
163
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
164
|
+
clearTimeout(handle: unknown): void;
|
|
165
|
+
};
|
|
166
|
+
/** @internal */
|
|
167
|
+
get renewEarlyMs(): number | undefined;
|
|
168
|
+
/** @internal */
|
|
169
|
+
get isOpen(): boolean;
|
|
170
|
+
private connect;
|
|
171
|
+
private detach;
|
|
172
|
+
private onOpen;
|
|
173
|
+
private onClose;
|
|
174
|
+
private scheduleReconnect;
|
|
175
|
+
private onMessage;
|
|
176
|
+
}
|
|
177
|
+
/** A live query's state, for useSyncExternalStore and other stores. */
|
|
178
|
+
export interface LiveQuery<Row> {
|
|
179
|
+
readonly id: string;
|
|
180
|
+
getSnapshot(): LiveQueryState<Row>;
|
|
181
|
+
subscribe(listener: () => void): () => void;
|
|
182
|
+
/**
|
|
183
|
+
* Resolves once the result reflects a committed transaction, such as the
|
|
184
|
+
* one that wrote the data (SELECT pg_current_xact_id()), whether or not
|
|
185
|
+
* the write changed these rows.
|
|
186
|
+
*/
|
|
187
|
+
awaitTxId(xid: bigint | number | string, options?: {
|
|
188
|
+
signal?: AbortSignal;
|
|
189
|
+
}): Promise<void>;
|
|
190
|
+
close(): void;
|
|
191
|
+
}
|
|
192
|
+
export {};
|