@supatype/client 0.3.6 → 0.8.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 +69 -30
- 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 +86 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +383 -275
- 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 +170 -165
- 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 +57 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +300 -88
- 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 +137 -38
- 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 +98 -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 +434 -281
- 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 +289 -208
- 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 +333 -90
- package/src/select-types.ts +184 -0
- package/src/storage.ts +223 -44
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +104 -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 +187 -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 +142 -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-ack-ref.test.ts +112 -0
- 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-shared-channel.test.ts +209 -0
- 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 +187 -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 +7 -9
- 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 +17 -31
- package/tests/storage-url-encoding.test.ts +52 -0
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/blob.ts +10 -0
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +41 -14
- 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
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import type { ChannelStatus, RealtimeClient, RealtimeEvent, RealtimePayload } from "./realtime.js"
|
|
2
|
+
import type { SupatypeError } from "./types.js"
|
|
3
|
+
import { isJsonObject } from "./json.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A table's live rows, for `from(table).subscribe()` and for the Vue, Svelte and Solid bindings.
|
|
7
|
+
*
|
|
8
|
+
* Each binding carried its own copy of the channel wiring, the status mapping and the row merge,
|
|
9
|
+
* beside the client's own wiring for `from(table).subscribe()`. The copies drifted the way copies
|
|
10
|
+
* do: none of the three bindings mapped SUBSCRIBING, so while a sign-in swapped the socket all
|
|
11
|
+
* three read "connected" with no join anywhere, and all three still shared one `public:table`
|
|
12
|
+
* channel that the client's own subscribe had long since stopped sharing. One copy here means
|
|
13
|
+
* each binding is only the adapter between this and its framework's state.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** What a binding shows for a subscription's connection. */
|
|
17
|
+
export type SubscriptionState = "connecting" | "connected" | "disconnected" | "error"
|
|
18
|
+
|
|
19
|
+
/** A binding's status and error, as one channel status implies them. */
|
|
20
|
+
export interface SubscriptionView {
|
|
21
|
+
status: SubscriptionState
|
|
22
|
+
error: SupatypeError | null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface TableWatchOptions {
|
|
26
|
+
event?: RealtimeEvent | undefined
|
|
27
|
+
filter?: string | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface TableSubscribeOptions extends TableWatchOptions {
|
|
31
|
+
schema?: string | undefined
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface TableWatchHandlers<TRow> {
|
|
35
|
+
/** The rows seen so far, after each change. */
|
|
36
|
+
rows(rows: TRow[]): void
|
|
37
|
+
/** The connection, after each status the channel reports. */
|
|
38
|
+
status(view: SubscriptionView): void
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface TableSubscription {
|
|
42
|
+
unsubscribe: () => void
|
|
43
|
+
channel: ReturnType<RealtimeClient["channel"]>
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Makes each table subscription's channel name unique.
|
|
48
|
+
*
|
|
49
|
+
* Module-wide rather than per client because it only has to be unique, and a name never seen by
|
|
50
|
+
* one client cannot collide on another.
|
|
51
|
+
*/
|
|
52
|
+
let tableSubscriptionCount = 0
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Subscribe to postgres_changes on one table, and join.
|
|
56
|
+
*
|
|
57
|
+
* Each call gets a channel of its own, named `schema:table:n`. The server keys a subscription by
|
|
58
|
+
* channel, so two calls sharing `schema:table` shared one filter and one event, and the first to
|
|
59
|
+
* unsubscribe removed the channel out from under the second. The name still reads as
|
|
60
|
+
* `schema:table` to anything that splits it, which is what a server predating `table` in the
|
|
61
|
+
* subscribe frame falls back to.
|
|
62
|
+
*/
|
|
63
|
+
export function subscribeToTable<TRow>(
|
|
64
|
+
realtime: RealtimeClient,
|
|
65
|
+
table: string,
|
|
66
|
+
callback: (payload: RealtimePayload<TRow>) => void,
|
|
67
|
+
opts?: TableSubscribeOptions | undefined,
|
|
68
|
+
): TableSubscription {
|
|
69
|
+
const schema = opts?.schema ?? "public"
|
|
70
|
+
tableSubscriptionCount += 1
|
|
71
|
+
const channel = realtime
|
|
72
|
+
.channel<TRow>(`${schema}:${table}:${tableSubscriptionCount}`)
|
|
73
|
+
.on(
|
|
74
|
+
"postgres_changes",
|
|
75
|
+
{
|
|
76
|
+
event: opts?.event ?? "*",
|
|
77
|
+
schema,
|
|
78
|
+
table,
|
|
79
|
+
...(opts?.filter !== undefined && { filter: opts.filter }),
|
|
80
|
+
},
|
|
81
|
+
callback,
|
|
82
|
+
)
|
|
83
|
+
// `on()` only records the listener. Without this nothing opened a socket or sent the join,
|
|
84
|
+
// and the callback waited forever unless something else on the client had joined already.
|
|
85
|
+
.subscribe()
|
|
86
|
+
return { channel, unsubscribe: () => channel.unsubscribe() }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The status and error a binding shows for a channel status.
|
|
91
|
+
*
|
|
92
|
+
* A refused join and a reconnect that gave up are both errors: neither is going to deliver
|
|
93
|
+
* anything without the caller doing something about it.
|
|
94
|
+
*/
|
|
95
|
+
export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
|
|
96
|
+
switch (status) {
|
|
97
|
+
case "SUBSCRIBING":
|
|
98
|
+
return { status: "connecting", error: null }
|
|
99
|
+
case "SUBSCRIBED":
|
|
100
|
+
return { status: "connected", error: null }
|
|
101
|
+
case "CLOSED":
|
|
102
|
+
return { status: "disconnected", error: null }
|
|
103
|
+
case "CHANNEL_ERROR":
|
|
104
|
+
return { status: "error", error: { message: "Subscription error" } }
|
|
105
|
+
case "TIMED_OUT":
|
|
106
|
+
return { status: "error", error: { message: "Realtime connection timed out" } }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function rowId(row: unknown): unknown {
|
|
111
|
+
return isJsonObject(row) ? row["id"] : undefined
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The rows after one change, matched on `id`.
|
|
116
|
+
*
|
|
117
|
+
* An insert or update always carries the new row; one without it (which the service does not send)
|
|
118
|
+
* leaves the rows as they were rather than putting a null among them.
|
|
119
|
+
*/
|
|
120
|
+
export function applyRowChange<TRow>(rows: TRow[] | null, payload: RealtimePayload<TRow>): TRow[] {
|
|
121
|
+
const current = rows ?? []
|
|
122
|
+
const next = payload.new
|
|
123
|
+
switch (payload.eventType) {
|
|
124
|
+
case "INSERT":
|
|
125
|
+
return next === null ? current : [...current, next]
|
|
126
|
+
case "UPDATE":
|
|
127
|
+
return next === null ? current : current.map((row) => (rowId(row) === rowId(next) ? next : row))
|
|
128
|
+
case "DELETE":
|
|
129
|
+
return current.filter((row) => rowId(row) !== rowId(payload.old))
|
|
130
|
+
default:
|
|
131
|
+
return current
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Subscribe to changes on a `public` table, and return the unsubscribe.
|
|
137
|
+
*
|
|
138
|
+
* The handlers are told the rows and the connection status; the binding decides where they live.
|
|
139
|
+
* The status is watched on the channel `subscribeToTable` already joined, which is what its
|
|
140
|
+
* channel's `subscribe(cb)` is for.
|
|
141
|
+
*/
|
|
142
|
+
export function watchTable<TRow>(
|
|
143
|
+
realtime: RealtimeClient,
|
|
144
|
+
table: string,
|
|
145
|
+
options: TableWatchOptions | undefined,
|
|
146
|
+
handlers: TableWatchHandlers<TRow>,
|
|
147
|
+
): () => void {
|
|
148
|
+
let rows: TRow[] | null = null
|
|
149
|
+
const subscription = subscribeToTable<TRow>(
|
|
150
|
+
realtime,
|
|
151
|
+
table,
|
|
152
|
+
(payload) => {
|
|
153
|
+
rows = applyRowChange(rows, payload)
|
|
154
|
+
handlers.rows(rows)
|
|
155
|
+
},
|
|
156
|
+
options,
|
|
157
|
+
)
|
|
158
|
+
subscription.channel.subscribe((status) => handlers.status(subscriptionViewOf(status)))
|
|
159
|
+
return subscription.unsubscribe
|
|
160
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { TableRelationship } from "./select-types.js"
|
|
2
|
+
|
|
1
3
|
// ─── Auth types ───────────────────────────────────────────────────────────────
|
|
2
4
|
|
|
3
5
|
export interface UserIdentity {
|
|
@@ -137,6 +139,28 @@ export interface SupatypeError {
|
|
|
137
139
|
* you.
|
|
138
140
|
*/
|
|
139
141
|
field?: string | undefined
|
|
142
|
+
/**
|
|
143
|
+
* What the server suggests doing instead, when it said. PostgREST passes a Postgres `HINT`
|
|
144
|
+
* through, and the gateway adds one to an insert into a drafts model that is refused for asking
|
|
145
|
+
* for its row back, naming `supatype.create_record` and `supatype.create_records`.
|
|
146
|
+
*/
|
|
147
|
+
hint?: string | undefined
|
|
148
|
+
/**
|
|
149
|
+
* The detail line Postgres attached, when it gave one. A unique violation names its columns and
|
|
150
|
+
* values here (`Key (slug)=(intro) already exists.`), which is how a caller learns which of the
|
|
151
|
+
* values it sent collided without parsing the message.
|
|
152
|
+
*/
|
|
153
|
+
details?: string | undefined
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A sign-in the auth server refused and reported back in the redirect URL.
|
|
158
|
+
*
|
|
159
|
+
* `provider` names the OAuth provider this browser started the sign-in with, when the client
|
|
160
|
+
* remembers one, so an app showing one button per provider can put the message by the right one.
|
|
161
|
+
*/
|
|
162
|
+
export interface AuthRedirectError extends SupatypeError {
|
|
163
|
+
provider?: string | undefined
|
|
140
164
|
}
|
|
141
165
|
|
|
142
166
|
// ─── Query result ─────────────────────────────────────────────────────────────
|
|
@@ -192,6 +216,14 @@ export interface RpcOptions {
|
|
|
192
216
|
count?: "exact" | "planned" | "estimated" | undefined
|
|
193
217
|
/** Postgres schema holding the function, sent as `Content-Profile`. */
|
|
194
218
|
schema?: string | undefined
|
|
219
|
+
/**
|
|
220
|
+
* Retry this call on a transient failure (a dropped connection, a 5xx, a 429). Default: false.
|
|
221
|
+
*
|
|
222
|
+
* An RPC is a POST, and the client cannot tell a read from a write: a call that failed in flight
|
|
223
|
+
* may already have run, and running it again could apply its writes twice. Set this for a
|
|
224
|
+
* function that only reads, or whose writes are safe to repeat. A `head` call is always retried.
|
|
225
|
+
*/
|
|
226
|
+
idempotent?: boolean | undefined
|
|
195
227
|
}
|
|
196
228
|
|
|
197
229
|
export interface RpcResult<TData> {
|
|
@@ -209,8 +241,38 @@ export interface TableDef {
|
|
|
209
241
|
*/
|
|
210
242
|
Insert: Record<string, unknown>
|
|
211
243
|
Update: Record<string, unknown>
|
|
244
|
+
/**
|
|
245
|
+
* The foreign keys this table holds, which an embedded select is resolved through. Generated for
|
|
246
|
+
* every table; a hand-written definition without them can still select its own columns.
|
|
247
|
+
*/
|
|
248
|
+
Relationships?: readonly TableRelationship[] | undefined
|
|
249
|
+
/**
|
|
250
|
+
* `true` on a model that keeps drafts, where `update` saves a new draft of each record and
|
|
251
|
+
* `{ publish: true }` publishes it in the same call. Generated; absent on every other table. A
|
|
252
|
+
* hand-written definition that leaves it unsaid is offered the option, and the client refuses it
|
|
253
|
+
* at run time on a table it does not know keeps drafts.
|
|
254
|
+
*/
|
|
255
|
+
Drafts?: boolean | undefined
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** What `update` takes beyond the changes, on a model that keeps drafts. */
|
|
259
|
+
export interface DraftUpdateOptions {
|
|
260
|
+
/**
|
|
261
|
+
* Publish each new draft in the same call, so the live rows change and the history records the
|
|
262
|
+
* version that went live. Without it the live rows stay as they are until a version is published.
|
|
263
|
+
*/
|
|
264
|
+
publish?: boolean | undefined
|
|
212
265
|
}
|
|
213
266
|
|
|
267
|
+
/**
|
|
268
|
+
* The options `update` takes on `TDef`: {@link DraftUpdateOptions} on a model that keeps drafts, or
|
|
269
|
+
* one whose definition does not say; nothing on a generated table that keeps none.
|
|
270
|
+
*/
|
|
271
|
+
export type UpdateOptions<TDef extends TableDef> =
|
|
272
|
+
TDef extends { Drafts: true } ? DraftUpdateOptions
|
|
273
|
+
: "Drafts" extends keyof TDef ? (TDef["Drafts"] extends false | undefined ? never : DraftUpdateOptions)
|
|
274
|
+
: never
|
|
275
|
+
|
|
214
276
|
/**
|
|
215
277
|
* Module augmentation anchors used by generated `supatype` types output.
|
|
216
278
|
*
|
|
@@ -331,6 +393,13 @@ export interface AuthStorage {
|
|
|
331
393
|
*/
|
|
332
394
|
export const DRAFT_SCHEMA = "draft"
|
|
333
395
|
|
|
396
|
+
/**
|
|
397
|
+
* The schema holding the generated publishing functions: `create_record`, `create_draft`, `publish`
|
|
398
|
+
* and the rest. PostgREST resolves `/rpc/<name>` against the default profile, so every call to one
|
|
399
|
+
* names this schema with `Content-Profile`.
|
|
400
|
+
*/
|
|
401
|
+
export const PUBLISHING_SCHEMA = "supatype"
|
|
402
|
+
|
|
334
403
|
export interface SelectQueryOptions {
|
|
335
404
|
count?: "exact" | "planned" | "estimated" | undefined
|
|
336
405
|
head?: boolean | undefined
|
|
@@ -358,6 +427,20 @@ export interface SupatypeClientConfig {
|
|
|
358
427
|
auth?: {
|
|
359
428
|
/** Persist session across page reloads (browser only). Default: true */
|
|
360
429
|
persistSession?: boolean | undefined
|
|
430
|
+
/**
|
|
431
|
+
* Refresh the access token on a timer shortly before it expires, and at once when the client
|
|
432
|
+
* starts with an expired one. Default: true. Off, a refresh happens only when a request finds
|
|
433
|
+
* the token expired: what a client built for one server request wants (`@supatype/ssr`).
|
|
434
|
+
*/
|
|
435
|
+
autoRefreshToken?: boolean | undefined
|
|
436
|
+
/**
|
|
437
|
+
* Refresh an expired access token when a request or `auth.getSession()` finds it. Default: true.
|
|
438
|
+
* Off, the expired token is sent as it is and the server refuses it, and the session is left as it
|
|
439
|
+
* was. For a client whose refreshed session could not be stored anywhere: a refresh spends the
|
|
440
|
+
* refresh token, so whoever holds it (the browser, for `@supatype/ssr` in a Server Component)
|
|
441
|
+
* would be refused on its own next refresh. `auth.refreshSession()` still refreshes when called.
|
|
442
|
+
*/
|
|
443
|
+
refreshExpiredToken?: boolean | undefined
|
|
361
444
|
/** localStorage key to use for session storage. Default: "supatype.auth.session" */
|
|
362
445
|
storageKey?: string | undefined
|
|
363
446
|
/**
|
|
@@ -371,15 +454,30 @@ export interface SupatypeClientConfig {
|
|
|
371
454
|
* React Native: pass an AsyncStorage or expo-secure-store adapter.
|
|
372
455
|
*/
|
|
373
456
|
storage?: AuthStorage | undefined
|
|
457
|
+
/**
|
|
458
|
+
* Finish a sign-in the auth server has just redirected back with (OAuth, magic link, recovery
|
|
459
|
+
* link): tokens in the URL fragment or a PKCE `code` in the query become the session, `SIGNED_IN`
|
|
460
|
+
* is emitted, and the parameters are removed from the address bar. Browser only. Default: true,
|
|
461
|
+
* as supabase-js's option of the same name. `auth.initialize()` reports a refusal in the URL.
|
|
462
|
+
*/
|
|
463
|
+
detectSessionInUrl?: boolean | undefined
|
|
374
464
|
} | undefined
|
|
375
465
|
/**
|
|
376
|
-
*
|
|
377
|
-
*
|
|
466
|
+
* Retry a transient failure (a dropped connection, a 5xx, a 429). Default: true.
|
|
467
|
+
*
|
|
468
|
+
* Only reads are retried: GET and HEAD requests (table selects, storage downloads, `getUser`), and
|
|
469
|
+
* the few reads sent as POST (storage `list`, signed URLs). Every other request is sent once,
|
|
470
|
+
* whatever this says: a write that failed in flight may still have been applied, and sending it
|
|
471
|
+
* again could apply it twice. `rpc`, `graphql` and `functions.invoke` take `idempotent: true` per
|
|
472
|
+
* call to opt in.
|
|
378
473
|
*/
|
|
379
474
|
retry?: boolean | undefined
|
|
380
475
|
/**
|
|
381
476
|
* Request timeout in milliseconds. Default: 30000 (30 seconds).
|
|
382
|
-
*
|
|
477
|
+
*
|
|
478
|
+
* Applies to every HTTP request the client makes: tables, `rpc`, `graphql`, `functions`, auth and
|
|
479
|
+
* storage, uploads included, so raise it for large uploads on slow links. The realtime socket is
|
|
480
|
+
* not an HTTP request and is not covered.
|
|
383
481
|
*/
|
|
384
482
|
timeout?: number | undefined
|
|
385
483
|
/**
|
|
@@ -410,7 +508,8 @@ export interface SupatypeClientConfig {
|
|
|
410
508
|
*/
|
|
411
509
|
previewCode?: string | undefined
|
|
412
510
|
/**
|
|
413
|
-
* Extra headers merged into every request (e.g. Studio `X-Supatype-Environment`).
|
|
511
|
+
* Extra headers merged into every request (e.g. Studio `X-Supatype-Environment`). A function is
|
|
512
|
+
* read on every request, for a header that changes for the life of the client.
|
|
414
513
|
*/
|
|
415
|
-
headers?: Record<string, string> | undefined
|
|
514
|
+
headers?: Record<string, string> | (() => Record<string, string>) | undefined
|
|
416
515
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
2
|
+
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
import { AuthErrorCodes } from "../src/errors.js"
|
|
4
|
+
import { getErrorDocumentation } from "../src/error-codes-doc.js"
|
|
5
|
+
|
|
6
|
+
// `AuthErrorCodes` held `AUTH_INVALID_CREDENTIALS` and the like, which the auth server never
|
|
7
|
+
// sends: it answers `{ error_code: "invalid_credentials", ... }`, and the client passes that code
|
|
8
|
+
// through. So `error.code === AuthErrorCodes.INVALID_CREDENTIALS` was false for every wrong
|
|
9
|
+
// password. Each constant is checked against the code the server sends in that situation
|
|
10
|
+
// (supatype-auth, internal/auth/apierrors/errorcode.go), through the client.
|
|
11
|
+
|
|
12
|
+
afterEach(() => {
|
|
13
|
+
vi.unstubAllGlobals()
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
const SERVER_SENDS: Array<[keyof typeof AuthErrorCodes, string]> = [
|
|
17
|
+
["INVALID_CREDENTIALS", "invalid_credentials"],
|
|
18
|
+
["USER_NOT_FOUND", "user_not_found"],
|
|
19
|
+
["EMAIL_NOT_CONFIRMED", "email_not_confirmed"],
|
|
20
|
+
["PHONE_NOT_CONFIRMED", "phone_not_confirmed"],
|
|
21
|
+
["SESSION_EXPIRED", "session_expired"],
|
|
22
|
+
["INVALID_TOKEN", "bad_jwt"],
|
|
23
|
+
["MFA_REQUIRED", "insufficient_aal"],
|
|
24
|
+
["MFA_CHALLENGE_EXPIRED", "mfa_challenge_expired"],
|
|
25
|
+
["MFA_VERIFICATION_FAILED", "mfa_verification_failed"],
|
|
26
|
+
["WEAK_PASSWORD", "weak_password"],
|
|
27
|
+
["USER_ALREADY_EXISTS", "user_already_exists"],
|
|
28
|
+
["OAUTH_CALLBACK_ERROR", "bad_oauth_callback"],
|
|
29
|
+
["MAGIC_LINK_EXPIRED", "otp_expired"],
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
describe("AuthErrorCodes", () => {
|
|
33
|
+
it.each(SERVER_SENDS)("%s is the code the server sends (%s)", async (name, serverCode) => {
|
|
34
|
+
vi.stubGlobal(
|
|
35
|
+
"fetch",
|
|
36
|
+
vi.fn().mockResolvedValue({
|
|
37
|
+
ok: false,
|
|
38
|
+
status: 400,
|
|
39
|
+
json: vi.fn().mockResolvedValue({ code: 400, error_code: serverCode, msg: "refused" }),
|
|
40
|
+
headers: { get: () => null },
|
|
41
|
+
}),
|
|
42
|
+
)
|
|
43
|
+
const client = new AuthClient("http://localhost:9999", { apikey: "k", "Content-Type": "application/json" })
|
|
44
|
+
const { error } = await client.signInWithPassword({ email: "a@example.com", password: "pw" })
|
|
45
|
+
expect(error?.code).toBe(AuthErrorCodes[name])
|
|
46
|
+
})
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
describe("the error documentation", () => {
|
|
50
|
+
it.each(SERVER_SENDS)("has an entry for %s under the code the server sends", (name) => {
|
|
51
|
+
expect(getErrorDocumentation(AuthErrorCodes[name])?.category).toBe("auth")
|
|
52
|
+
})
|
|
53
|
+
})
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
+
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
import type { SupatypeError } from "../src/types.js"
|
|
4
|
+
import { fetchReturning } from "./support/fetch-mock.js"
|
|
5
|
+
|
|
6
|
+
const AUTH_URL = "http://localhost:9999"
|
|
7
|
+
const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
|
|
8
|
+
|
|
9
|
+
const TOKEN_RESPONSE = {
|
|
10
|
+
access_token: "access-token-123",
|
|
11
|
+
refresh_token: "refresh-token-abc",
|
|
12
|
+
token_type: "bearer",
|
|
13
|
+
expires_in: 3600,
|
|
14
|
+
user: { id: "user-1", email: "a@example.com", app_metadata: {}, user_metadata: {} },
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** What the auth server sends today: a numeric `code`, a string `error_code` and a `msg`. */
|
|
18
|
+
const API_ERROR = { code: 422, error_code: "weak_password", msg: "Password should be at least 8 characters." }
|
|
19
|
+
|
|
20
|
+
/** The OAuth token endpoint's older shape: `error` is the code and `error_description` the message. */
|
|
21
|
+
const OAUTH_ERROR = { error: "invalid_grant", error_description: "Invalid Refresh Token: Already Used" }
|
|
22
|
+
|
|
23
|
+
async function signedIn(): Promise<AuthClient> {
|
|
24
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
25
|
+
vi.stubGlobal("fetch", fetchReturning(TOKEN_RESPONSE, 200))
|
|
26
|
+
await client.signInWithPassword({ email: "a@example.com", password: "pw" })
|
|
27
|
+
return client
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
type AuthCall = (client: AuthClient) => Promise<{ error: SupatypeError | null }>
|
|
31
|
+
|
|
32
|
+
const CALLS: Array<[string, AuthCall]> = [
|
|
33
|
+
["signUp", (c) => c.signUp({ email: "a@example.com", password: "x" })],
|
|
34
|
+
["signInWithPassword", (c) => c.signInWithPassword({ email: "a@example.com", password: "x" })],
|
|
35
|
+
["signInAnonymously", (c) => c.signInAnonymously()],
|
|
36
|
+
["signInWithOtp", (c) => c.signInWithOtp({ email: "a@example.com" })],
|
|
37
|
+
["signInWithIdToken", (c) => c.signInWithIdToken({ provider: "google", token: "t" })],
|
|
38
|
+
["verifyOtp", (c) => c.verifyOtp({ type: "email", token: "1", email: "a@example.com" })],
|
|
39
|
+
["resend", (c) => c.resend({ type: "signup", email: "a@example.com" })],
|
|
40
|
+
["resetPasswordForEmail", (c) => c.resetPasswordForEmail("a@example.com")],
|
|
41
|
+
["updateUser", (c) => c.updateUser({ password: "x" })],
|
|
42
|
+
["getUser", (c) => c.getUser()],
|
|
43
|
+
["refreshSession", (c) => c.refreshSession()],
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
describe("auth errors carry the server's error code", () => {
|
|
47
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
48
|
+
|
|
49
|
+
for (const [name, call] of CALLS) {
|
|
50
|
+
it(`${name}: error_code becomes code, msg becomes message`, async () => {
|
|
51
|
+
const client = await signedIn()
|
|
52
|
+
vi.stubGlobal("fetch", fetchReturning(API_ERROR, 422))
|
|
53
|
+
const { error } = await call(client)
|
|
54
|
+
expect(error).toEqual({ message: API_ERROR.msg, status: 422, code: "weak_password" })
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
it("the OAuth shape's `error` is the code and `error_description` the message", async () => {
|
|
59
|
+
const client = await signedIn()
|
|
60
|
+
vi.stubGlobal("fetch", fetchReturning(OAUTH_ERROR, 400))
|
|
61
|
+
const { error } = await client.refreshSession()
|
|
62
|
+
expect(error).toEqual({ message: OAUTH_ERROR.error_description, status: 400, code: "invalid_grant" })
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it("a body that is not JSON still gives a message and the status", async () => {
|
|
66
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
67
|
+
const notJson = (): Promise<Response> => Promise.resolve(new Response("<html>Bad gateway</html>", { status: 502 }))
|
|
68
|
+
vi.stubGlobal("fetch", vi.fn<typeof fetch>(notJson))
|
|
69
|
+
const { error } = await client.signInWithPassword({ email: "a@example.com", password: "x" })
|
|
70
|
+
expect(error?.status).toBe(502)
|
|
71
|
+
expect(error?.message).not.toBe("")
|
|
72
|
+
expect(error?.code).toBeUndefined()
|
|
73
|
+
})
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
describe("redirect errors carry the server's error code", () => {
|
|
77
|
+
it("getSessionFromUrl keeps error_code from an expired email link", async () => {
|
|
78
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
79
|
+
const { error } = await client.getSessionFromUrl(
|
|
80
|
+
"https://app.example/#error=access_denied&error_code=otp_expired&error_description=Email+link+is+invalid+or+has+expired",
|
|
81
|
+
)
|
|
82
|
+
expect(error).toEqual({ message: "Email link is invalid or has expired", status: 400, code: "otp_expired" })
|
|
83
|
+
})
|
|
84
|
+
})
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
+
import { AuthClient } from "../src/auth.js"
|
|
3
|
+
import type { AuthChangeEvent } from "../src/types.js"
|
|
4
|
+
import { fetchReturning } from "./support/fetch-mock.js"
|
|
5
|
+
|
|
6
|
+
const AUTH_URL = "http://localhost:9999"
|
|
7
|
+
const HEADERS = { apikey: "test-anon-key", "Content-Type": "application/json" }
|
|
8
|
+
|
|
9
|
+
const RAW_USER = {
|
|
10
|
+
id: "user-1",
|
|
11
|
+
email: "old@example.com",
|
|
12
|
+
created_at: "2024-01-01T00:00:00Z",
|
|
13
|
+
updated_at: "2024-01-01T00:00:00Z",
|
|
14
|
+
app_metadata: { provider: "email" },
|
|
15
|
+
user_metadata: {},
|
|
16
|
+
role: "authenticated",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const TOKEN_RESPONSE = {
|
|
20
|
+
access_token: "access-token-123",
|
|
21
|
+
refresh_token: "refresh-token-abc",
|
|
22
|
+
token_type: "bearer",
|
|
23
|
+
expires_in: 3600,
|
|
24
|
+
user: RAW_USER,
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function accessTokenWithExp(): string {
|
|
28
|
+
const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
|
|
29
|
+
return `eyJhbGciOiJub25lIn0.${payload}.sig`
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Every event a listener sees after registration, without the registration emission itself. */
|
|
33
|
+
function recordEvents(client: AuthClient): AuthChangeEvent[] {
|
|
34
|
+
const events: AuthChangeEvent[] = []
|
|
35
|
+
let registered = false
|
|
36
|
+
client.onAuthStateChange((event) => {
|
|
37
|
+
if (registered) events.push(event)
|
|
38
|
+
})
|
|
39
|
+
registered = true
|
|
40
|
+
return events
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function signedInClient(): Promise<AuthClient> {
|
|
44
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
45
|
+
vi.stubGlobal("fetch", fetchReturning(TOKEN_RESPONSE))
|
|
46
|
+
await client.signInWithPassword({ email: "old@example.com", password: "pw" })
|
|
47
|
+
return client
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe("USER_UPDATED", () => {
|
|
51
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
52
|
+
|
|
53
|
+
it("is emitted after a successful updateUser, with the updated user on the session", async () => {
|
|
54
|
+
const client = await signedInClient()
|
|
55
|
+
const sessions: Array<string | undefined> = []
|
|
56
|
+
const events: AuthChangeEvent[] = []
|
|
57
|
+
let registered = false
|
|
58
|
+
client.onAuthStateChange((event, session) => {
|
|
59
|
+
if (!registered) return
|
|
60
|
+
events.push(event)
|
|
61
|
+
sessions.push(session?.user.email)
|
|
62
|
+
})
|
|
63
|
+
registered = true
|
|
64
|
+
|
|
65
|
+
vi.stubGlobal("fetch", fetchReturning({ ...RAW_USER, email: "new@example.com" }))
|
|
66
|
+
const { error } = await client.updateUser({ email: "new@example.com" })
|
|
67
|
+
|
|
68
|
+
expect(error).toBeNull()
|
|
69
|
+
expect(events).toEqual(["USER_UPDATED"])
|
|
70
|
+
expect(sessions).toEqual(["new@example.com"])
|
|
71
|
+
const { data } = await client.getSession()
|
|
72
|
+
expect(data.session?.user.email).toBe("new@example.com")
|
|
73
|
+
expect(data.session?.accessToken).toBe("access-token-123")
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it("is not emitted when updateUser fails", async () => {
|
|
77
|
+
const client = await signedInClient()
|
|
78
|
+
const events = recordEvents(client)
|
|
79
|
+
|
|
80
|
+
vi.stubGlobal("fetch", fetchReturning({ msg: "weak password" }, 422))
|
|
81
|
+
const { error } = await client.updateUser({ password: "x" })
|
|
82
|
+
|
|
83
|
+
expect(error?.status).toBe(422)
|
|
84
|
+
expect(events).toEqual([])
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
describe("PASSWORD_RECOVERY", () => {
|
|
89
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
90
|
+
|
|
91
|
+
it("is emitted when a recovery link's tokens are read from the URL", async () => {
|
|
92
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
93
|
+
const events = recordEvents(client)
|
|
94
|
+
vi.stubGlobal("fetch", fetchReturning(RAW_USER))
|
|
95
|
+
|
|
96
|
+
const { error } = await client.getSessionFromUrl(
|
|
97
|
+
`https://app.example/reset#access_token=${accessTokenWithExp()}&refresh_token=rt-1&expires_in=3600&token_type=bearer&type=recovery`,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
expect(error).toBeNull()
|
|
101
|
+
expect(events).toEqual(["SIGNED_IN", "PASSWORD_RECOVERY"])
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it("is not emitted for an ordinary sign-in link", async () => {
|
|
105
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
106
|
+
const events = recordEvents(client)
|
|
107
|
+
vi.stubGlobal("fetch", fetchReturning(RAW_USER))
|
|
108
|
+
|
|
109
|
+
await client.getSessionFromUrl(
|
|
110
|
+
`https://app.example/#access_token=${accessTokenWithExp()}&refresh_token=rt-1&type=magiclink`,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
expect(events).toEqual(["SIGNED_IN"])
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
it("is emitted when a recovery OTP is verified", async () => {
|
|
117
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
118
|
+
const events = recordEvents(client)
|
|
119
|
+
vi.stubGlobal("fetch", fetchReturning(TOKEN_RESPONSE))
|
|
120
|
+
|
|
121
|
+
const { error } = await client.verifyOtp({ type: "recovery", token: "123456", email: "old@example.com" })
|
|
122
|
+
|
|
123
|
+
expect(error).toBeNull()
|
|
124
|
+
expect(events).toEqual(["SIGNED_IN", "PASSWORD_RECOVERY"])
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
it("is not emitted when a recovery OTP is refused", async () => {
|
|
128
|
+
const client = new AuthClient(AUTH_URL, HEADERS)
|
|
129
|
+
const events = recordEvents(client)
|
|
130
|
+
vi.stubGlobal("fetch", fetchReturning({ msg: "expired" }, 403))
|
|
131
|
+
|
|
132
|
+
await client.verifyOtp({ type: "recovery", token: "123456", email: "old@example.com" })
|
|
133
|
+
|
|
134
|
+
expect(events).toEqual([])
|
|
135
|
+
})
|
|
136
|
+
})
|