@supatype/client 0.3.5 → 0.7.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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/realtime.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
|
|
2
|
-
import {
|
|
2
|
+
import { coerceRecordKinds, type ExactFields } from "./exact-values.js"
|
|
3
|
+
import { isArrayOf, isJsonObject, isOneOf, isRecordOf, isShape, isString, nullable, optional, type Guard } from "./json.js"
|
|
3
4
|
|
|
4
5
|
export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
|
|
5
6
|
|
|
@@ -65,7 +66,28 @@ function coerceRecord(
|
|
|
65
66
|
exact: ExactFields,
|
|
66
67
|
): Record<string, unknown> | null {
|
|
67
68
|
if (record === null) return null
|
|
68
|
-
return
|
|
69
|
+
return coerceRecordKinds(record, exact)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The boundary between a change's records and the row type the caller named for the channel.
|
|
74
|
+
*
|
|
75
|
+
* The frame guard below has already checked each record is a JSON object or null. That an object
|
|
76
|
+
* holds `TRow`'s columns is the caller's claim about the table behind the channel (usually the
|
|
77
|
+
* generated schema's), which nothing on the client can check.
|
|
78
|
+
*/
|
|
79
|
+
function isCallerRow<TRow>(record: unknown): record is TRow {
|
|
80
|
+
return isJsonObject(record)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A listener for the channel's row type, registered as one for the plain records the frame holds. */
|
|
84
|
+
function forCallerRows<TRow>(callback: RealtimeCallback<TRow>): RealtimeCallback<Record<string, unknown>> {
|
|
85
|
+
return (payload) =>
|
|
86
|
+
callback({
|
|
87
|
+
...payload,
|
|
88
|
+
new: isCallerRow<TRow>(payload.new) ? payload.new : null,
|
|
89
|
+
old: isCallerRow<TRow>(payload.old) ? payload.old : null,
|
|
90
|
+
})
|
|
69
91
|
}
|
|
70
92
|
|
|
71
93
|
/**
|
|
@@ -119,6 +141,44 @@ interface ServerSystemMessage {
|
|
|
119
141
|
|
|
120
142
|
type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadcastMessage | ServerSystemMessage
|
|
121
143
|
|
|
144
|
+
// Each guard is declared as the interface it checks, so the compiler holds the two to the same shape.
|
|
145
|
+
const isRecordOrNull = nullable(isJsonObject)
|
|
146
|
+
const isPresenceEntries: Guard<PresenceEntry[]> = isArrayOf(isShape({ user_id: isString }))
|
|
147
|
+
|
|
148
|
+
const isChangeMessage: Guard<ServerChangeMessage> = isShape({
|
|
149
|
+
type: isOneOf(["change"]),
|
|
150
|
+
channel: isString,
|
|
151
|
+
event: isOneOf(["INSERT", "UPDATE", "DELETE"]),
|
|
152
|
+
payload: isShape({ old: isRecordOrNull, new: isRecordOrNull }),
|
|
153
|
+
exactColumns: optional(isRecordOf(isOneOf(["bigint", "numeric"]))),
|
|
154
|
+
timestamp: isString,
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
const isPresenceMessage: Guard<ServerPresenceMessage> = isShape({
|
|
158
|
+
type: isOneOf(["presence"]),
|
|
159
|
+
channel: isString,
|
|
160
|
+
joins: isPresenceEntries,
|
|
161
|
+
leaves: isPresenceEntries,
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
const isBroadcastMessage: Guard<ServerBroadcastMessage> = isShape({
|
|
165
|
+
type: isOneOf(["broadcast"]),
|
|
166
|
+
channel: isString,
|
|
167
|
+
event: isString,
|
|
168
|
+
payload: isJsonObject,
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
const isSystemMessage: Guard<ServerSystemMessage> = isShape({
|
|
172
|
+
type: isOneOf(["system"]),
|
|
173
|
+
status: isOneOf(["ok", "error"]),
|
|
174
|
+
message: isString,
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
/** A frame from the realtime service (packages/realtime/src/types.ts) in one of the four shapes. */
|
|
178
|
+
function isServerMessage(value: unknown): value is ServerMessage {
|
|
179
|
+
return isChangeMessage(value) || isPresenceMessage(value) || isBroadcastMessage(value) || isSystemMessage(value)
|
|
180
|
+
}
|
|
181
|
+
|
|
122
182
|
// ─── Realtime client ─────────────────────────────────────────────────────────
|
|
123
183
|
|
|
124
184
|
export class RealtimeClient {
|
|
@@ -185,12 +245,26 @@ export class RealtimeClient {
|
|
|
185
245
|
this.cycleConnection(token)
|
|
186
246
|
}
|
|
187
247
|
|
|
188
|
-
/**
|
|
248
|
+
/**
|
|
249
|
+
* Abandon the current socket and immediately open a replacement, keeping every channel.
|
|
250
|
+
*
|
|
251
|
+
* Every channel's join went with the old socket, so each one says it is subscribing again until
|
|
252
|
+
* the replacement acknowledges it. Without this a channel kept reading SUBSCRIBED through the
|
|
253
|
+
* swap, while it had no join anywhere and a change committed in the gap could not arrive.
|
|
254
|
+
*/
|
|
189
255
|
private cycleConnection(token: string | undefined): void {
|
|
190
256
|
this.abandonSocket("reauthenticating")
|
|
257
|
+
this.notifyChannels("SUBSCRIBING")
|
|
191
258
|
this.ensureConnection(token)
|
|
192
259
|
}
|
|
193
260
|
|
|
261
|
+
/** Tell every channel's status callback the same thing. */
|
|
262
|
+
private notifyChannels(status: ChannelStatus): void {
|
|
263
|
+
for (const state of this.channels.values()) {
|
|
264
|
+
state.statusCallback?.(status)
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
194
268
|
/**
|
|
195
269
|
* Drop the socket and any connect in flight, without deciding what happens next.
|
|
196
270
|
*
|
|
@@ -219,14 +293,28 @@ export class RealtimeClient {
|
|
|
219
293
|
this.forgetJoins()
|
|
220
294
|
}
|
|
221
295
|
|
|
222
|
-
/**
|
|
296
|
+
/**
|
|
297
|
+
* Every join belonged to the socket that just went away; the next one has to make its own.
|
|
298
|
+
*
|
|
299
|
+
* So did everything that socket said about presence. The next join is told who is there all
|
|
300
|
+
* over again, so the members known now leave first: a page counting joins minus leaves would
|
|
301
|
+
* otherwise count each of them twice.
|
|
302
|
+
*/
|
|
223
303
|
private forgetJoins(): void {
|
|
224
304
|
for (const state of this.channels.values()) {
|
|
225
305
|
state.subscribed = false
|
|
226
306
|
state.joinSent = false
|
|
307
|
+
this.forgetMembers(state)
|
|
227
308
|
}
|
|
228
309
|
}
|
|
229
310
|
|
|
311
|
+
private forgetMembers(state: ChannelState): void {
|
|
312
|
+
if (state.members.length === 0) return
|
|
313
|
+
const leaves = state.members
|
|
314
|
+
state.members = []
|
|
315
|
+
for (const listener of state.presenceListeners) listener({ joins: [], leaves })
|
|
316
|
+
}
|
|
317
|
+
|
|
230
318
|
channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
|
|
231
319
|
const state = this.getOrCreateChannel(name)
|
|
232
320
|
|
|
@@ -241,7 +329,7 @@ export class RealtimeClient {
|
|
|
241
329
|
schema: opts.schema ?? named.schema,
|
|
242
330
|
table: opts.table ?? named.table,
|
|
243
331
|
filter: opts.filter,
|
|
244
|
-
callback: callback
|
|
332
|
+
callback: forCallerRows(callback),
|
|
245
333
|
})
|
|
246
334
|
return sub
|
|
247
335
|
},
|
|
@@ -327,9 +415,13 @@ export class RealtimeClient {
|
|
|
327
415
|
* disconnect from scheduling its own reconnect: the close handler is detached first. It also
|
|
328
416
|
* cancels a connect still waiting on its token, which would otherwise install a socket after the
|
|
329
417
|
* caller asked for none.
|
|
418
|
+
*
|
|
419
|
+
* A channel still registered is told CLOSED: its join went with the socket and nothing will
|
|
420
|
+
* reconnect it, so the SUBSCRIBED it last reported is no longer true.
|
|
330
421
|
*/
|
|
331
422
|
disconnect(): void {
|
|
332
423
|
this.abandonSocket("client disconnect")
|
|
424
|
+
this.notifyChannels("CLOSED")
|
|
333
425
|
}
|
|
334
426
|
|
|
335
427
|
// ─── Internal ──────────────────────────────────────────────────────────
|
|
@@ -345,6 +437,7 @@ export class RealtimeClient {
|
|
|
345
437
|
statusCallback: null,
|
|
346
438
|
subscribed: false,
|
|
347
439
|
joinSent: false,
|
|
440
|
+
members: [],
|
|
348
441
|
}
|
|
349
442
|
this.channels.set(name, state)
|
|
350
443
|
}
|
|
@@ -421,8 +514,9 @@ export class RealtimeClient {
|
|
|
421
514
|
|
|
422
515
|
ws.onmessage = (event) => {
|
|
423
516
|
try {
|
|
424
|
-
const msg = JSON.parse(String(event.data))
|
|
425
|
-
this.
|
|
517
|
+
const msg = JSON.parse(String(event.data))
|
|
518
|
+
// A frame in no shape this client knows is ignored, as an unknown `type` always was.
|
|
519
|
+
if (isServerMessage(msg)) this.handleServerMessage(msg)
|
|
426
520
|
} catch {
|
|
427
521
|
// Ignore unparseable messages
|
|
428
522
|
}
|
|
@@ -444,18 +538,14 @@ export class RealtimeClient {
|
|
|
444
538
|
|
|
445
539
|
private scheduleReconnect(): void {
|
|
446
540
|
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
447
|
-
|
|
448
|
-
state.statusCallback?.("TIMED_OUT")
|
|
449
|
-
}
|
|
541
|
+
this.notifyChannels("TIMED_OUT")
|
|
450
542
|
return
|
|
451
543
|
}
|
|
452
544
|
|
|
453
545
|
const delay = this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts)
|
|
454
546
|
this.reconnectAttempts++
|
|
455
547
|
|
|
456
|
-
|
|
457
|
-
state.statusCallback?.("SUBSCRIBING")
|
|
458
|
-
}
|
|
548
|
+
this.notifyChannels("SUBSCRIBING")
|
|
459
549
|
|
|
460
550
|
this.reconnectTimer = setTimeout(() => {
|
|
461
551
|
this.ensureConnection()
|
|
@@ -538,6 +628,7 @@ export class RealtimeClient {
|
|
|
538
628
|
const state = this.channels.get(msg.channel)
|
|
539
629
|
if (!state) return
|
|
540
630
|
|
|
631
|
+
state.members = withoutLeaves([...state.members, ...msg.joins], msg.leaves)
|
|
541
632
|
for (const listener of state.presenceListeners) {
|
|
542
633
|
listener({ joins: msg.joins, leaves: msg.leaves })
|
|
543
634
|
}
|
|
@@ -628,4 +719,16 @@ interface ChannelState {
|
|
|
628
719
|
* used to send a second frame.
|
|
629
720
|
*/
|
|
630
721
|
joinSent: boolean
|
|
722
|
+
/** Who the current socket has said is tracked on this channel, one entry per tracking socket. */
|
|
723
|
+
members: PresenceEntry[]
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/** `members` with one entry removed per leave: a user on two tabs is two entries and leaves twice. */
|
|
727
|
+
function withoutLeaves(members: PresenceEntry[], leaves: PresenceEntry[]): PresenceEntry[] {
|
|
728
|
+
const kept = [...members]
|
|
729
|
+
for (const leave of leaves) {
|
|
730
|
+
const at = kept.findIndex((member) => member.user_id === leave.user_id)
|
|
731
|
+
if (at !== -1) kept.splice(at, 1)
|
|
732
|
+
}
|
|
733
|
+
return kept
|
|
631
734
|
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The row a select string returns, read from the string itself.
|
|
3
|
+
*
|
|
4
|
+
* `select("*, author:authors(*)")` used to be typed as the table's row whatever the string said, so
|
|
5
|
+
* a caller embedding a relation had to declare the joined shape by hand and keep it in step with the
|
|
6
|
+
* string. That is a second copy of the query, and the type said nothing when the two drifted. This
|
|
7
|
+
* reads PostgREST's select grammar at the type level and resolves each embedded resource through the
|
|
8
|
+
* `Relationships` the generator writes for every table.
|
|
9
|
+
*
|
|
10
|
+
* What is understood: `*`, columns, `alias:column`, `column::cast`, JSON paths (`data->a->>b`),
|
|
11
|
+
* embedded resources (`rel(...)`, `alias:rel(...)`, nested) with `!inner` and a foreign-key column
|
|
12
|
+
* hint (`rel!author_id(...)`), in both directions of a foreign key and through a junction table.
|
|
13
|
+
*
|
|
14
|
+
* A to-one embed is `Row | null` unless it is `!inner`. A foreign key that is NOT NULL does not make
|
|
15
|
+
* the embed non-null: row level security can hide the referenced row while the referencing one stays
|
|
16
|
+
* readable, and PostgREST then returns `null` for it. `!inner` drops such rows instead, so there the
|
|
17
|
+
* embed is the row.
|
|
18
|
+
*
|
|
19
|
+
* A name the schema does not have becomes a {@link SelectError} rather than `unknown`, so the mistake
|
|
20
|
+
* surfaces where the value is used, with the reason in the type.
|
|
21
|
+
*/
|
|
22
|
+
import type { TableDef } from "./types.js"
|
|
23
|
+
|
|
24
|
+
/** One foreign key, as the generator describes it on the table that holds it. */
|
|
25
|
+
export interface TableRelationship {
|
|
26
|
+
columns: readonly string[]
|
|
27
|
+
isOneToOne: boolean
|
|
28
|
+
referencedRelation: string
|
|
29
|
+
referencedColumns: readonly string[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What a select string named that the schema does not have, with the reason. */
|
|
33
|
+
export interface SelectError<TMessage extends string> {
|
|
34
|
+
readonly selectError: TMessage
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
type Tables = Record<string, TableDef>
|
|
38
|
+
|
|
39
|
+
/** The row `select(columns)` resolves to on table `TName`. */
|
|
40
|
+
export type SelectRow<TTables extends Tables, TName extends string, TColumns extends string> =
|
|
41
|
+
string extends TColumns
|
|
42
|
+
? RowOf<TTables, TName>
|
|
43
|
+
: ParseFields<TTables, TName, SplitTopLevel<TColumns>>
|
|
44
|
+
|
|
45
|
+
// ─── Grammar ──────────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
type Space = " " | "\n" | "\t" | "\r"
|
|
48
|
+
type TrimStart<S extends string> = S extends `${infer C}${infer R}` ? (C extends Space ? TrimStart<R> : S) : S
|
|
49
|
+
type TrimEnd<S extends string> = S extends `${infer R}${Space}` ? TrimEnd<R> : S
|
|
50
|
+
type Trim<S extends string> = TrimEnd<TrimStart<S>>
|
|
51
|
+
|
|
52
|
+
type Push<TAcc extends string[], TItem extends string> = Trim<TItem> extends "" ? TAcc : [...TAcc, Trim<TItem>]
|
|
53
|
+
|
|
54
|
+
/** Split on the commas outside any parentheses: `a, b(c, d)` is two fields, not three. */
|
|
55
|
+
type SplitTopLevel<
|
|
56
|
+
S extends string,
|
|
57
|
+
TDepth extends 0[] = [],
|
|
58
|
+
TCurrent extends string = "",
|
|
59
|
+
TAcc extends string[] = [],
|
|
60
|
+
> = S extends `${infer C}${infer Rest}`
|
|
61
|
+
? C extends "("
|
|
62
|
+
? SplitTopLevel<Rest, [...TDepth, 0], `${TCurrent}${C}`, TAcc>
|
|
63
|
+
: C extends ")"
|
|
64
|
+
? SplitTopLevel<Rest, TDepth extends [0, ...infer Outer extends 0[]] ? Outer : [], `${TCurrent}${C}`, TAcc>
|
|
65
|
+
: C extends ","
|
|
66
|
+
? TDepth extends []
|
|
67
|
+
? SplitTopLevel<Rest, TDepth, "", Push<TAcc, TCurrent>>
|
|
68
|
+
: SplitTopLevel<Rest, TDepth, `${TCurrent}${C}`, TAcc>
|
|
69
|
+
: SplitTopLevel<Rest, TDepth, `${TCurrent}${C}`, TAcc>
|
|
70
|
+
: Push<TAcc, TCurrent>
|
|
71
|
+
|
|
72
|
+
type Simplify<T> = { [K in keyof T]: T[K] } & {}
|
|
73
|
+
|
|
74
|
+
type ParseFields<TTables extends Tables, TName extends string, TFields extends string[]> =
|
|
75
|
+
TFields extends ["*"]
|
|
76
|
+
? RowOf<TTables, TName>
|
|
77
|
+
: Simplify<MergeFields<TTables, TName, TFields>>
|
|
78
|
+
|
|
79
|
+
type MergeFields<TTables extends Tables, TName extends string, TFields extends string[], TAcc = unknown> =
|
|
80
|
+
TFields extends [infer F extends string, ...infer Rest extends string[]]
|
|
81
|
+
? MergeFields<TTables, TName, Rest, TAcc & ParseField<TTables, TName, F>>
|
|
82
|
+
: TAcc
|
|
83
|
+
|
|
84
|
+
/** `alias:body`, where the alias is what comes before the first `:` unless that is a cast's `::`. */
|
|
85
|
+
type ParseField<TTables extends Tables, TName extends string, F extends string> =
|
|
86
|
+
F extends "*"
|
|
87
|
+
? RowOf<TTables, TName>
|
|
88
|
+
: F extends `${infer Alias}:${infer Body}`
|
|
89
|
+
? Body extends `:${string}`
|
|
90
|
+
? Unaliased<TTables, TName, F>
|
|
91
|
+
: Alias extends `${string}(${string}`
|
|
92
|
+
? Unaliased<TTables, TName, F>
|
|
93
|
+
: { [K in Trim<Alias>]: FieldType<TTables, TName, Trim<Body>> }
|
|
94
|
+
: Unaliased<TTables, TName, F>
|
|
95
|
+
|
|
96
|
+
type Unaliased<TTables extends Tables, TName extends string, F extends string> = {
|
|
97
|
+
[K in NaturalName<F>]: FieldType<TTables, TName, F>
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The key PostgREST gives an unaliased field: the resource, the column, or a JSON path's last key. */
|
|
101
|
+
type NaturalName<F extends string> =
|
|
102
|
+
F extends `${infer Resource}(${string}` ? ResourceName<Trim<Resource>>
|
|
103
|
+
: F extends `${infer Column}::${string}` ? NaturalName<Column>
|
|
104
|
+
: F extends `${string}->>${infer Rest}` ? NaturalName<Rest>
|
|
105
|
+
: F extends `${string}->${infer Rest}` ? NaturalName<Rest>
|
|
106
|
+
: F
|
|
107
|
+
|
|
108
|
+
type FieldType<TTables extends Tables, TName extends string, Body extends string> =
|
|
109
|
+
Body extends `${infer Resource}(${infer Inner})`
|
|
110
|
+
? Embed<TTables, TName, Trim<Resource>, Inner>
|
|
111
|
+
: ColumnType<RowOf<TTables, TName>, TName, Body>
|
|
112
|
+
|
|
113
|
+
/** The column a field reads, without its cast (`::text`) or JSON path (`->a->>b`). */
|
|
114
|
+
type BaseColumn<B extends string> =
|
|
115
|
+
B extends `${infer C}::${string}` ? BaseColumn<C> : B extends `${infer C}->${string}` ? C : B
|
|
116
|
+
|
|
117
|
+
/** A plain column is its row type; a cast or a JSON path reads a value the schema cannot type. */
|
|
118
|
+
type ColumnType<TRow, TName extends string, Body extends string> =
|
|
119
|
+
BaseColumn<Body> extends infer C extends string
|
|
120
|
+
? C extends keyof TRow
|
|
121
|
+
? Body extends C ? TRow[C] : unknown
|
|
122
|
+
: SelectError<`column '${C}' does not exist on '${TName}'`>
|
|
123
|
+
: never
|
|
124
|
+
|
|
125
|
+
// ─── Embedded resources ───────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
type ResourceName<R extends string> = R extends `${infer Name}!${string}` ? Name : R
|
|
128
|
+
|
|
129
|
+
/** `rel!inner!author_id`: the `!` modifiers after a resource name, in any order. */
|
|
130
|
+
type Modifiers<R extends string> = R extends `${string}!${infer Rest}` ? SplitBang<Rest> : never
|
|
131
|
+
type SplitBang<S extends string> = S extends `${infer Head}!${infer Rest}` ? Head | SplitBang<Rest> : S
|
|
132
|
+
type ColumnHint<R extends string> = Exclude<Modifiers<R>, "inner" | "left">
|
|
133
|
+
|
|
134
|
+
type Embed<TTables extends Tables, TName extends string, TResource extends string, Inner extends string> =
|
|
135
|
+
string extends keyof TTables
|
|
136
|
+
? unknown
|
|
137
|
+
: ResourceName<TResource> extends infer Target extends string
|
|
138
|
+
? Target extends keyof TTables
|
|
139
|
+
? Shape<
|
|
140
|
+
Cardinality<TTables, TName, Target, ColumnHint<TResource>>,
|
|
141
|
+
SelectRow<TTables, Target, Inner>,
|
|
142
|
+
"inner" extends Modifiers<TResource> ? true : false,
|
|
143
|
+
`'${TName}' has no relationship to '${Target}'`
|
|
144
|
+
>
|
|
145
|
+
: SelectError<`'${Target}' is not a table`>
|
|
146
|
+
: never
|
|
147
|
+
|
|
148
|
+
type Shape<TKind, TRow, TInner extends boolean, TMessage extends string> =
|
|
149
|
+
TKind extends "one" ? (TInner extends true ? TRow : TRow | null)
|
|
150
|
+
: TKind extends "many" ? TRow[]
|
|
151
|
+
: SelectError<TMessage>
|
|
152
|
+
|
|
153
|
+
type RowOf<TTables extends Tables, TName extends string> = TTables[TName] extends { Row: infer R } ? R : never
|
|
154
|
+
|
|
155
|
+
type RelationshipsOf<TDef> =
|
|
156
|
+
TDef extends { Relationships: infer R extends readonly unknown[] } ? R[number] : never
|
|
157
|
+
|
|
158
|
+
/** The relationships of `From` naming `To`, narrowed to the hinted column when there is one. */
|
|
159
|
+
type Referencing<TTables extends Tables, From extends string, To extends string, Hint> = Extract<
|
|
160
|
+
RelationshipsOf<TTables[From]>,
|
|
161
|
+
[Hint] extends [never]
|
|
162
|
+
? { referencedRelation: To }
|
|
163
|
+
: { referencedRelation: To; columns: readonly [Hint & string, ...string[]] }
|
|
164
|
+
>
|
|
165
|
+
|
|
166
|
+
/** A table holding foreign keys to both sides: the junction of a many-to-many. */
|
|
167
|
+
type Junction<TTables extends Tables, From extends string, To extends string> = {
|
|
168
|
+
[J in keyof TTables & string]: [Referencing<TTables, J, From, never>] extends [never]
|
|
169
|
+
? never
|
|
170
|
+
: [Referencing<TTables, J, To, never>] extends [never]
|
|
171
|
+
? never
|
|
172
|
+
: J
|
|
173
|
+
}[keyof TTables & string]
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* How many rows an embed returns. The key on this side is to-one; the key on the other side is
|
|
177
|
+
* to-many unless it is unique; a junction holding keys to both is to-many.
|
|
178
|
+
*/
|
|
179
|
+
type Cardinality<TTables extends Tables, From extends string, To extends string, Hint> =
|
|
180
|
+
[Referencing<TTables, From, To, Hint>] extends [never]
|
|
181
|
+
? [Referencing<TTables, To, From, Hint>] extends [never]
|
|
182
|
+
? [Junction<TTables, From, To>] extends [never] ? "none" : "many"
|
|
183
|
+
: Referencing<TTables, To, From, Hint> extends { isOneToOne: true } ? "one" : "many"
|
|
184
|
+
: "one"
|