@supatype/client 0.9.0 → 0.9.1
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 +71 -68
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +82 -0
- package/dist/auth.d.ts +41 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +102 -32
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +3 -0
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -0
- package/dist/bindings.js.map +1 -1
- 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 +7 -0
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +81 -21
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +133 -46
- package/dist/errors.js.map +1 -1
- package/dist/graphql-transport.d.ts +8 -1
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js +5 -5
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -37
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +29 -0
- package/dist/latest-rows.d.ts.map +1 -0
- package/dist/latest-rows.js +51 -0
- package/dist/latest-rows.js.map +1 -0
- package/dist/mutation-request.d.ts +2 -1
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +2 -1
- package/dist/mutation-request.js.map +1 -1
- package/dist/page-env-script.d.ts +12 -0
- package/dist/page-env-script.d.ts.map +1 -0
- package/dist/page-env-script.js +30 -0
- package/dist/page-env-script.js.map +1 -0
- package/dist/preview.d.ts +2 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +7 -3
- package/dist/preview.js.map +1 -1
- package/dist/query.d.ts +11 -5
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +22 -13
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +5 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +13 -6
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +59 -0
- package/dist/runtime-env.d.ts.map +1 -0
- package/dist/runtime-env.js +167 -0
- package/dist/runtime-env.js.map +1 -0
- package/dist/setup-fault.d.ts +13 -0
- package/dist/setup-fault.d.ts.map +1 -0
- package/dist/setup-fault.js +17 -0
- package/dist/setup-fault.js.map +1 -0
- package/dist/storage.d.ts +10 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +22 -13
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +1 -1
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +3 -2
- package/dist/table-subscription.js.map +1 -1
- package/dist/thrown-error.d.ts +16 -0
- package/dist/thrown-error.d.ts.map +1 -0
- package/dist/thrown-error.js +31 -0
- package/dist/thrown-error.js.map +1 -0
- package/dist/types.d.ts +59 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -1
- package/src/auth.ts +106 -36
- package/src/bindings.ts +3 -0
- package/src/error-codes-doc.ts +9 -1
- package/src/errors.ts +155 -57
- package/src/graphql-transport.ts +5 -6
- package/src/index.ts +62 -44
- package/src/latest-rows.ts +78 -0
- package/src/mutation-request.ts +3 -2
- package/src/page-env-script.ts +27 -0
- package/src/preview.ts +8 -4
- package/src/query.ts +27 -16
- package/src/realtime.ts +15 -6
- package/src/runtime-env.ts +220 -0
- package/src/setup-fault.ts +18 -0
- package/src/storage.ts +26 -16
- package/src/table-subscription.ts +3 -3
- package/src/thrown-error.ts +31 -0
- package/src/types.ts +65 -14
- package/tests/auth-errors.test.ts +3 -3
- package/tests/auth-events.test.ts +3 -7
- package/tests/auth-sso.test.ts +260 -0
- package/tests/auth-url-session.test.ts +6 -25
- package/tests/entry-points.test.ts +9 -0
- package/tests/error-family.test.ts +79 -0
- package/tests/helpers/auth-unmount-binding.ts +63 -0
- package/tests/helpers/oauth-binding.ts +4 -3
- package/tests/helpers/stale-read-binding.ts +113 -0
- package/tests/helpers/thrown-error-binding.ts +127 -0
- package/tests/postgrest-error-codes.test.ts +4 -4
- package/tests/rate-limit-integration.test.ts +1 -1
- package/tests/result-error-class.test.ts +107 -0
- package/tests/retry-policy.test.ts +1 -1
- package/tests/runtime-env-bundle.test.ts +121 -0
- package/tests/runtime-env-page-script.test.ts +174 -0
- package/tests/runtime-env.test.ts +224 -0
- package/tests/server-bodies.test.ts +3 -3
- package/tests/support/browser.ts +28 -0
- package/tests/support/jwt.ts +5 -0
- package/tests/thrown-error.test.ts +59 -0
- package/tsconfig.tsbuildinfo +1 -1
package/src/errors.ts
CHANGED
|
@@ -1,57 +1,158 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { SupatypeErrorFields } from "./types.js"
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* The Supatype SDK's one error family.
|
|
5
|
+
*
|
|
6
|
+
* `SupatypeError` is every error a `{ data, error }` result carries, and the root of the errors the
|
|
7
|
+
* SDK throws, so `error instanceof SupatypeError` holds for all of them. `SupatypeCodedError` is the
|
|
8
|
+
* thrown kind: the same fields with a required machine-readable `code` and a `helpUrl`.
|
|
6
9
|
*/
|
|
7
10
|
|
|
8
11
|
const DOCS_BASE = "https://docs.supatype.com/errors"
|
|
9
12
|
|
|
13
|
+
/** The fields an error carries beside its message, each kept only when it has a value. */
|
|
14
|
+
const ERROR_FIELDS = ["code", "status", "field", "hint", "details"] as const
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Set `key` as `error`'s own field, enumerable as a plain object's, so JSON and spread keep it. A
|
|
18
|
+
* function rather than a method: a protected member would make two copies of the class (source and
|
|
19
|
+
* build) refuse each other's errors.
|
|
20
|
+
*/
|
|
21
|
+
function keep(error: Error, key: string, value: unknown): void {
|
|
22
|
+
Object.defineProperty(error, key, { value, enumerable: true, writable: true, configurable: true })
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Give `cls` the `name` its errors print, on the prototype so it is not a key of each error. */
|
|
26
|
+
function nameErrors(cls: { prototype: Error }, name: string): void {
|
|
27
|
+
Object.defineProperty(cls.prototype, "name", { value: name, writable: true, configurable: true })
|
|
28
|
+
}
|
|
29
|
+
|
|
10
30
|
/**
|
|
11
|
-
*
|
|
31
|
+
* An error a Supatype result carries, and the base of every error the SDK throws.
|
|
32
|
+
*
|
|
33
|
+
* An `Error`, so `instanceof Error` holds, a stack is kept, and `String(error)` reads
|
|
34
|
+
* `SupatypeError: <message>`. Its own fields are exactly the result's (`message`, then whichever of
|
|
35
|
+
* `code`, `status`, `field`, `hint` and `details` it has), so reading them, spreading the error, or
|
|
36
|
+
* turning it into JSON gives those fields. A failure in transit keeps what was thrown as `cause`.
|
|
12
37
|
*/
|
|
13
|
-
export class SupatypeError extends Error {
|
|
14
|
-
readonly code
|
|
15
|
-
readonly
|
|
16
|
-
readonly
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
this
|
|
23
|
-
|
|
38
|
+
export class SupatypeError extends Error implements SupatypeErrorFields {
|
|
39
|
+
declare readonly code?: string | undefined
|
|
40
|
+
declare readonly status?: number | undefined
|
|
41
|
+
declare readonly field?: string | undefined
|
|
42
|
+
declare readonly hint?: string | undefined
|
|
43
|
+
declare readonly details?: string | undefined
|
|
44
|
+
|
|
45
|
+
constructor(fields: SupatypeErrorFields, options?: { cause?: unknown }) {
|
|
46
|
+
super(fields.message, options)
|
|
47
|
+
keep(this, "message", fields.message)
|
|
48
|
+
for (const key of ERROR_FIELDS) {
|
|
49
|
+
if (fields[key] !== undefined) keep(this, key, fields[key])
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The error's fields as a plain object, which is what JSON gets, and nothing else. */
|
|
54
|
+
toJSON(): SupatypeErrorFields {
|
|
55
|
+
const fields: SupatypeErrorFields = { message: this.message }
|
|
56
|
+
for (const key of ERROR_FIELDS) {
|
|
57
|
+
if (this[key] !== undefined) Object.assign(fields, { [key]: this[key] })
|
|
58
|
+
}
|
|
59
|
+
return fields
|
|
24
60
|
}
|
|
25
61
|
}
|
|
62
|
+
nameErrors(SupatypeError, "SupatypeError")
|
|
26
63
|
|
|
27
64
|
/**
|
|
28
|
-
*
|
|
65
|
+
* A sign-in the auth server refused and reported back in the redirect URL.
|
|
66
|
+
*
|
|
67
|
+
* `provider` names the OAuth provider this browser started the sign-in with, when the client
|
|
68
|
+
* remembers one, so an app showing one button per provider can put the message by the right one.
|
|
69
|
+
* It is one more own field, so JSON and spread carry it too.
|
|
70
|
+
*/
|
|
71
|
+
export class AuthRedirectError extends SupatypeError {
|
|
72
|
+
declare readonly provider?: string | undefined
|
|
73
|
+
|
|
74
|
+
constructor(fields: SupatypeErrorFields & { provider?: string | undefined }, options?: { cause?: unknown }) {
|
|
75
|
+
super(fields, options)
|
|
76
|
+
if (fields.provider !== undefined) keep(this, "provider", fields.provider)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
override toJSON(): SupatypeErrorFields & { provider?: string } {
|
|
80
|
+
return { ...super.toJSON(), ...(this.provider !== undefined && { provider: this.provider }) }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
nameErrors(AuthRedirectError, "AuthRedirectError")
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* An error the SDK throws: a `SupatypeError` whose `code` is always there, with a `helpUrl` to the
|
|
87
|
+
* page that explains it. Its HTTP status, when it has one, is `status`, as on every result.
|
|
29
88
|
*/
|
|
30
|
-
export class
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
89
|
+
export class SupatypeCodedError extends SupatypeError {
|
|
90
|
+
declare readonly code: string
|
|
91
|
+
|
|
92
|
+
constructor(message: string, code: string, status?: number, options?: { cause?: unknown }) {
|
|
93
|
+
super({ message, code, ...(status !== undefined && { status }) }, options)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The documentation for this error's code. */
|
|
97
|
+
get helpUrl(): string {
|
|
98
|
+
return `${DOCS_BASE}#${this.code.toLowerCase()}`
|
|
34
99
|
}
|
|
35
100
|
}
|
|
101
|
+
nameErrors(SupatypeCodedError, "SupatypeCodedError")
|
|
102
|
+
|
|
103
|
+
/** The two values a client cannot send a request without. */
|
|
104
|
+
export type ClientValue = "url" | "anonKey"
|
|
36
105
|
|
|
37
106
|
/**
|
|
38
|
-
*
|
|
107
|
+
* A request made by a client that has no API address or no anon key.
|
|
108
|
+
*
|
|
109
|
+
* Thrown by the request, never by `createClient`: a client created at module scope runs while a
|
|
110
|
+
* framework prerenders a page, which sends nothing and needs neither. It is a setup fault rather
|
|
111
|
+
* than an answer from the server, so no request turns it into `{ data: null, error }`
|
|
112
|
+
* (transportFailure rethrows it): an app that only reads `data` would show an empty page instead.
|
|
39
113
|
*/
|
|
40
|
-
export class
|
|
41
|
-
|
|
42
|
-
readonly
|
|
114
|
+
export class MissingClientValuesError extends SupatypeCodedError {
|
|
115
|
+
/** Which of the two values were still missing when the request was made. */
|
|
116
|
+
readonly missing: readonly ClientValue[]
|
|
43
117
|
|
|
118
|
+
constructor(message: string, missing: readonly ClientValue[]) {
|
|
119
|
+
super(message, "MISSING_CLIENT_VALUES")
|
|
120
|
+
this.missing = missing
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
nameErrors(MissingClientValuesError, "MissingClientValuesError")
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Authentication errors (login failures, token issues, MFA).
|
|
127
|
+
*/
|
|
128
|
+
export class AuthError extends SupatypeCodedError {
|
|
129
|
+
constructor(message: string, code: string = "AUTH_ERROR", status?: number) {
|
|
130
|
+
super(message, code, status)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
nameErrors(AuthError, "AuthError")
|
|
134
|
+
|
|
135
|
+
/** A PostgREST hint or detail line worth keeping: given and not blank. */
|
|
136
|
+
function given(text: string | null | undefined): string | undefined {
|
|
137
|
+
return text === null || text === undefined || text === "" ? undefined : text
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* PostgREST API errors with structured details. `details` and `hint` are absent when the server
|
|
142
|
+
* gave none, as on every other error.
|
|
143
|
+
*/
|
|
144
|
+
export class PostgrestError extends SupatypeCodedError {
|
|
44
145
|
constructor(
|
|
45
146
|
message: string,
|
|
46
147
|
code: string = "PGRST000",
|
|
47
|
-
|
|
148
|
+
status?: number,
|
|
48
149
|
details?: string | null,
|
|
49
150
|
hint?: string | null,
|
|
50
151
|
) {
|
|
51
|
-
super(message, code,
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
152
|
+
super(message, code, status)
|
|
153
|
+
const kept = { details: given(details), hint: given(hint) }
|
|
154
|
+
if (kept.details !== undefined) keep(this, "details", kept.details)
|
|
155
|
+
if (kept.hint !== undefined) keep(this, "hint", kept.hint)
|
|
55
156
|
}
|
|
56
157
|
|
|
57
158
|
/**
|
|
@@ -62,63 +163,60 @@ export class PostgrestError extends SupatypeError {
|
|
|
62
163
|
code?: string | undefined
|
|
63
164
|
details?: string | undefined
|
|
64
165
|
hint?: string | undefined
|
|
65
|
-
},
|
|
166
|
+
}, status: number): PostgrestError {
|
|
66
167
|
return new PostgrestError(
|
|
67
168
|
body.message || "PostgREST error",
|
|
68
|
-
body.code || `PGRST${
|
|
69
|
-
|
|
169
|
+
body.code || `PGRST${status}`,
|
|
170
|
+
status,
|
|
70
171
|
body.details,
|
|
71
172
|
body.hint,
|
|
72
173
|
)
|
|
73
174
|
}
|
|
74
175
|
}
|
|
176
|
+
nameErrors(PostgrestError, "PostgrestError")
|
|
75
177
|
|
|
76
178
|
/**
|
|
77
179
|
* Storage service errors (upload/download failures).
|
|
78
180
|
*/
|
|
79
|
-
export class StorageError extends
|
|
80
|
-
constructor(message: string, code: string = "STORAGE_ERROR",
|
|
81
|
-
super(message, code,
|
|
82
|
-
this.name = "StorageError"
|
|
181
|
+
export class StorageError extends SupatypeCodedError {
|
|
182
|
+
constructor(message: string, code: string = "STORAGE_ERROR", status?: number) {
|
|
183
|
+
super(message, code, status)
|
|
83
184
|
}
|
|
84
185
|
}
|
|
186
|
+
nameErrors(StorageError, "StorageError")
|
|
85
187
|
|
|
86
188
|
/**
|
|
87
189
|
* Realtime/WebSocket errors.
|
|
88
190
|
*/
|
|
89
|
-
export class RealtimeError extends
|
|
191
|
+
export class RealtimeError extends SupatypeCodedError {
|
|
90
192
|
constructor(message: string, code: string = "REALTIME_ERROR") {
|
|
91
193
|
super(message, code)
|
|
92
|
-
this.name = "RealtimeError"
|
|
93
194
|
}
|
|
94
195
|
}
|
|
196
|
+
nameErrors(RealtimeError, "RealtimeError")
|
|
95
197
|
|
|
96
198
|
/**
|
|
97
199
|
* Network errors (connection failures, timeouts, DNS).
|
|
98
200
|
*/
|
|
99
|
-
export class NetworkError extends
|
|
201
|
+
export class NetworkError extends SupatypeCodedError {
|
|
100
202
|
constructor(message: string, code: string = "NETWORK_ERROR") {
|
|
101
203
|
super(message, code)
|
|
102
|
-
this.name = "NetworkError"
|
|
103
204
|
}
|
|
104
205
|
}
|
|
206
|
+
nameErrors(NetworkError, "NetworkError")
|
|
105
207
|
|
|
106
208
|
/**
|
|
107
209
|
* Rate limit errors with retry information.
|
|
108
210
|
*/
|
|
109
|
-
export class RateLimitError extends
|
|
211
|
+
export class RateLimitError extends SupatypeCodedError {
|
|
110
212
|
readonly retryAfterSeconds: number
|
|
111
213
|
|
|
112
214
|
constructor(retryAfterSeconds: number) {
|
|
113
|
-
super(
|
|
114
|
-
`Rate limited. Retry after ${retryAfterSeconds} seconds.`,
|
|
115
|
-
"RATE_LIMITED",
|
|
116
|
-
429,
|
|
117
|
-
)
|
|
118
|
-
this.name = "RateLimitError"
|
|
215
|
+
super(`Rate limited. Retry after ${retryAfterSeconds} seconds.`, "RATE_LIMITED", 429)
|
|
119
216
|
this.retryAfterSeconds = retryAfterSeconds
|
|
120
217
|
}
|
|
121
218
|
}
|
|
219
|
+
nameErrors(RateLimitError, "RateLimitError")
|
|
122
220
|
|
|
123
221
|
// ── Common error codes ────────────────────────────────────────────
|
|
124
222
|
|
|
@@ -231,15 +329,15 @@ export const ErrorCodes = {
|
|
|
231
329
|
* A request that never got an answer, as a result rather than a throw.
|
|
232
330
|
*
|
|
233
331
|
* The client's fetch throws typed errors (a timeout, a rate limit after the last retry), and their
|
|
234
|
-
* code and status are what lets a caller tell "try again later" from "the server is gone"
|
|
332
|
+
* code and status are what lets a caller tell "try again later" from "the server is gone", so one
|
|
333
|
+
* of the family is the result as it is, and `instanceof NetworkError` still names it. Anything else
|
|
334
|
+
* thrown is held as the `cause` of a `SupatypeError` carrying its message.
|
|
335
|
+
*
|
|
336
|
+
* A client with no address or anon key is rethrown instead: that request was never sent, and the
|
|
337
|
+
* fix is in the app's setup, which a result an app may never read would hide.
|
|
235
338
|
*/
|
|
236
|
-
export function transportFailure(e: unknown):
|
|
237
|
-
if (e instanceof
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
code: e.code,
|
|
241
|
-
...(e.statusCode !== undefined && { status: e.statusCode }),
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
return { message: e instanceof Error ? e.message : "Network error" }
|
|
339
|
+
export function transportFailure(e: unknown): SupatypeError {
|
|
340
|
+
if (e instanceof MissingClientValuesError) throw e
|
|
341
|
+
if (e instanceof SupatypeError) return e
|
|
342
|
+
return new SupatypeError({ message: e instanceof Error ? e.message : "Network error" }, { cause: e })
|
|
245
343
|
}
|
package/src/graphql-transport.ts
CHANGED
|
@@ -5,13 +5,12 @@
|
|
|
5
5
|
* credential, because pg_graphql shows each role only what it may use. It is cached per role, so a
|
|
6
6
|
* refreshed token for the same role reuses it.
|
|
7
7
|
*/
|
|
8
|
-
import { transportFailure } from "./errors.js"
|
|
8
|
+
import { SupatypeError, transportFailure } from "./errors.js"
|
|
9
9
|
import type { RequestTransport } from "./fetch-with-retry.js"
|
|
10
10
|
import { GRAPHQL_SCHEMA_QUERY, GraphqlSchemaCache, decodeGraphqlAnswer, readGraphqlSchema, type GraphqlSchema } from "./graphql-json.js"
|
|
11
11
|
import { isJsonObject, refusalText } from "./json.js"
|
|
12
12
|
import { bearerRole } from "./jwt.js"
|
|
13
13
|
import { fetchWithOptional401Retry, type HeadersProvider, type UnauthorizedHandler } from "./query.js"
|
|
14
|
-
import type { SupatypeError } from "./types.js"
|
|
15
14
|
|
|
16
15
|
/** Where GraphQL requests go and what they carry. Studio builds one per send-as choice. */
|
|
17
16
|
export type GraphqlTransport = {
|
|
@@ -63,7 +62,7 @@ async function post(transport: GraphqlTransport, body: Record<string, unknown>,
|
|
|
63
62
|
const json: unknown = await res.json()
|
|
64
63
|
return { json, res }
|
|
65
64
|
} catch {
|
|
66
|
-
return { failure: { message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` } }
|
|
65
|
+
return { failure: new SupatypeError({ message: `GraphQL endpoint returned a non-JSON response (HTTP ${res.status} ${res.statusText})` }) }
|
|
67
66
|
}
|
|
68
67
|
}
|
|
69
68
|
|
|
@@ -82,16 +81,16 @@ function schemaKey(headers: Record<string, string>): string {
|
|
|
82
81
|
/** What a GraphQL endpoint's JSON answer means: its data, and the first error it reports. */
|
|
83
82
|
function graphqlResult(json: unknown, res: Response): GraphqlAnswer {
|
|
84
83
|
if (!isJsonObject(json)) {
|
|
85
|
-
return { data: null, error: { message: `GraphQL endpoint returned JSON that is not an object (HTTP ${res.status})`, status: res.status } }
|
|
84
|
+
return { data: null, error: new SupatypeError({ message: `GraphQL endpoint returned JSON that is not an object (HTTP ${res.status})`, status: res.status }) }
|
|
86
85
|
}
|
|
87
86
|
const data = json["data"] ?? null
|
|
88
87
|
if (!res.ok) {
|
|
89
88
|
const message = refusalText(json) ?? `GraphQL request failed (HTTP ${res.status})`
|
|
90
|
-
return { data, error: { message, status: res.status } }
|
|
89
|
+
return { data, error: new SupatypeError({ message, status: res.status }) }
|
|
91
90
|
}
|
|
92
91
|
const errors = json["errors"]
|
|
93
92
|
if (errors === undefined) return { data, error: null }
|
|
94
93
|
const first = Array.isArray(errors) ? errors[0] : undefined
|
|
95
94
|
const message = isJsonObject(first) && typeof first["message"] === "string" ? first["message"] : "GraphQL error"
|
|
96
|
-
return { data, error: { message } }
|
|
95
|
+
return { data, error: new SupatypeError({ message }) }
|
|
97
96
|
}
|
package/src/index.ts
CHANGED
|
@@ -17,12 +17,13 @@ import { StorageClient } from "./storage.js"
|
|
|
17
17
|
import { RealtimeClient } from "./realtime.js"
|
|
18
18
|
import type { RealtimePayload } from "./realtime.js"
|
|
19
19
|
import { subscribeToTable, type TableSubscribeOptions, type TableSubscription } from "./table-subscription.js"
|
|
20
|
-
import { PostgrestError, transportFailure } from "./errors.js"
|
|
20
|
+
import { PostgrestError, SupatypeError, transportFailure } from "./errors.js"
|
|
21
21
|
import { createRetryFetch } from "./retry.js"
|
|
22
22
|
import { isJsonObject, isString, readJsonObject, refusalText } from "./json.js"
|
|
23
23
|
import { jwtRole } from "./jwt.js"
|
|
24
24
|
import { createGraphqlRunner } from "./graphql-transport.js"
|
|
25
25
|
import { warnIfServerlessDirectConnection } from "./fetch-with-retry.js"
|
|
26
|
+
import { ClientTarget, settle, type Deferred } from "./runtime-env.js"
|
|
26
27
|
import type {
|
|
27
28
|
AnyDatabase,
|
|
28
29
|
AugmentedDatabase,
|
|
@@ -30,7 +31,6 @@ import type {
|
|
|
30
31
|
RpcResult,
|
|
31
32
|
SupatypeFunctions,
|
|
32
33
|
SupatypeClientConfig,
|
|
33
|
-
SupatypeError,
|
|
34
34
|
RpcOptions,
|
|
35
35
|
SelectQueryOptions,
|
|
36
36
|
TableDef,
|
|
@@ -45,8 +45,10 @@ export type {
|
|
|
45
45
|
Session,
|
|
46
46
|
AuthChangeEvent,
|
|
47
47
|
AuthFlowType,
|
|
48
|
-
|
|
49
|
-
|
|
48
|
+
SignInWithSSOCredentials,
|
|
49
|
+
SignInWithSSOOptions,
|
|
50
|
+
SignInWithSSOResult,
|
|
51
|
+
SupatypeErrorFields,
|
|
50
52
|
QueryResult,
|
|
51
53
|
MaskedField,
|
|
52
54
|
RpcResult,
|
|
@@ -90,7 +92,7 @@ export type { SelectRow, SelectError, TableRelationship } from "./select-types.j
|
|
|
90
92
|
*/
|
|
91
93
|
export type AnyClient = SupatypeClient<AnyDatabase>
|
|
92
94
|
export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
|
|
93
|
-
export { AuthClient } from "./auth.js"
|
|
95
|
+
export { AuthClient, SSO_PROVIDER } from "./auth.js"
|
|
94
96
|
export { onIdentityChange, type IdentitySource } from "./identity.js"
|
|
95
97
|
export { QueryBuilder, MutationBuilder, type HeadersProvider, type RequestTransport, type UnauthorizedHandler } from "./query.js"
|
|
96
98
|
export { QueryCache, defaultQueryCache } from "./query-cache.js"
|
|
@@ -101,6 +103,7 @@ export type { RealtimeEvent, RealtimePayload, ChannelStatus, PresenceEntry } fro
|
|
|
101
103
|
// The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
|
|
102
104
|
export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
|
|
103
105
|
export * from "./errors.js"
|
|
106
|
+
export { MissingClientValuesError, type ClientValue } from "./setup-fault.js"
|
|
104
107
|
|
|
105
108
|
// Called by the generated `supatype/generated/client.ts`, which is how a project tells the client which
|
|
106
109
|
// columns hold values a JSON parser would destroy. Exported because generated code imports it;
|
|
@@ -154,7 +157,8 @@ class TableClient<
|
|
|
154
157
|
TTables extends Record<string, TableDef> = Record<string, TableDef>,
|
|
155
158
|
TName extends string = string,
|
|
156
159
|
> {
|
|
157
|
-
|
|
160
|
+
/** Handed to each query as it is, so a deferred address is read only when the query is sent. */
|
|
161
|
+
private readonly baseUrl: Deferred<string>
|
|
158
162
|
private readonly table: string
|
|
159
163
|
private readonly path: string
|
|
160
164
|
private readonly getHeaders: HeadersProvider
|
|
@@ -173,7 +177,7 @@ class TableClient<
|
|
|
173
177
|
private profile: string | undefined
|
|
174
178
|
|
|
175
179
|
constructor(
|
|
176
|
-
baseUrl: string
|
|
180
|
+
baseUrl: Deferred<string>,
|
|
177
181
|
table: string,
|
|
178
182
|
getHeaders: HeadersProvider,
|
|
179
183
|
realtime: RealtimeClient,
|
|
@@ -344,7 +348,7 @@ class TableClient<
|
|
|
344
348
|
if (model !== undefined) return { editThrough: { table: this.table, primaryKey: model.primaryKey, publish } }
|
|
345
349
|
if (!publish) return undefined
|
|
346
350
|
const message = `{ publish: true } applies to a model that keeps drafts, and "${this.table}" is not one this client knows of. Import the client from the generated ${GENERATED_CLIENT_IMPORT}, which says which models keep drafts.`
|
|
347
|
-
return { refusal: { message } }
|
|
351
|
+
return { refusal: new SupatypeError({ message }) }
|
|
348
352
|
}
|
|
349
353
|
|
|
350
354
|
delete(): MutationBuilder<TDef["Row"], TTables, TName> {
|
|
@@ -404,11 +408,11 @@ function isDeclaredReturn<T>(value: unknown): value is T {
|
|
|
404
408
|
function functionError(body: Record<string, unknown>, status: number): SupatypeError {
|
|
405
409
|
const workerCode = isString(body["message"]) ? body["error"] : undefined
|
|
406
410
|
const code = isString(body["code"]) ? body["code"] : isString(workerCode) ? workerCode : undefined
|
|
407
|
-
return {
|
|
411
|
+
return new SupatypeError({
|
|
408
412
|
message: refusalText(body) ?? `Function returned ${status}`,
|
|
409
413
|
status,
|
|
410
414
|
...(code !== undefined && { code }),
|
|
411
|
-
}
|
|
415
|
+
})
|
|
412
416
|
}
|
|
413
417
|
|
|
414
418
|
/**
|
|
@@ -491,13 +495,13 @@ export interface FunctionInvokeOptions {
|
|
|
491
495
|
}
|
|
492
496
|
|
|
493
497
|
class FunctionsClient {
|
|
494
|
-
private readonly baseUrl: string
|
|
498
|
+
private readonly baseUrl: Deferred<string>
|
|
495
499
|
private readonly getHeaders: HeadersProvider
|
|
496
500
|
private readonly onUnauthorized: UnauthorizedHandler | undefined
|
|
497
501
|
private readonly doFetch: RequestTransport
|
|
498
502
|
|
|
499
503
|
constructor(
|
|
500
|
-
baseUrl: string
|
|
504
|
+
baseUrl: Deferred<string>,
|
|
501
505
|
getHeaders: HeadersProvider,
|
|
502
506
|
doFetch: RequestTransport,
|
|
503
507
|
onUnauthorized?: UnauthorizedHandler | undefined,
|
|
@@ -541,7 +545,7 @@ class FunctionsClient {
|
|
|
541
545
|
try {
|
|
542
546
|
const res = await fetchWithOptional401Retry(
|
|
543
547
|
this.doFetch,
|
|
544
|
-
`${this.baseUrl}/functions/v1/${functionName}`,
|
|
548
|
+
`${settle(this.baseUrl)}/functions/v1/${functionName}`,
|
|
545
549
|
fetchOpts,
|
|
546
550
|
resolveHeaders,
|
|
547
551
|
this.onUnauthorized,
|
|
@@ -607,11 +611,22 @@ export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabas
|
|
|
607
611
|
): Promise<RpcResult<FunctionReturns<TDatabase, TFn>>>
|
|
608
612
|
}
|
|
609
613
|
|
|
614
|
+
/** The headers a request carries as the anon role: the anon key, then the caller's own. */
|
|
615
|
+
function anonHeaders(anonKey: string, extra: Record<string, string>): Record<string, string> {
|
|
616
|
+
return { apikey: anonKey, Authorization: `Bearer ${anonKey}`, "Content-Type": "application/json", ...extra }
|
|
617
|
+
}
|
|
618
|
+
|
|
610
619
|
export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
611
620
|
config: SupatypeClientConfig,
|
|
612
621
|
): SupatypeClient<TDatabase> {
|
|
622
|
+
// The address and anon key as given, else as the page sets them, read when a request is made
|
|
623
|
+
// (runtime-env.ts). Every request asks through these two, so the first one made without them
|
|
624
|
+
// throws the error naming them, and creating the client never does.
|
|
625
|
+
const target = new ClientTarget(config)
|
|
626
|
+
const address = (): string => target.resolve().url
|
|
627
|
+
|
|
613
628
|
// Warn early if a direct Postgres URL is used in a serverless environment
|
|
614
|
-
warnIfServerlessDirectConnection(config.url)
|
|
629
|
+
if (config.url !== undefined && config.url !== "") warnIfServerlessDirectConnection(config.url)
|
|
615
630
|
|
|
616
631
|
// A client with both is a route sending admin credentials down a path meant for strangers, which
|
|
617
632
|
// is precisely what the preview link exists to remove. Thrown rather than warned: the two are
|
|
@@ -629,19 +644,19 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
629
644
|
const previewCredential =
|
|
630
645
|
config.previewCode === undefined || config.previewCode === ""
|
|
631
646
|
? null
|
|
632
|
-
: new PreviewCredential(
|
|
647
|
+
: new PreviewCredential(address, config.previewCode)
|
|
633
648
|
|
|
634
649
|
// `headers` may be a function, read on every request: Studio changes the acting mode it asks for
|
|
635
650
|
// without rebuilding its client (and losing its session and sockets).
|
|
636
651
|
const extraHeaders = (): Record<string, string> =>
|
|
637
652
|
typeof config.headers === "function" ? config.headers() : (config.headers ?? {})
|
|
638
653
|
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
654
|
+
// The caller's extra headers as they were when the client was made, as the anon headers have
|
|
655
|
+
// always carried them; each request adds them again as they are by then (getAuthHeaders).
|
|
656
|
+
const initialExtraHeaders = extraHeaders()
|
|
657
|
+
let anon: Record<string, string> | undefined
|
|
658
|
+
const baseHeaders = (): Record<string, string> =>
|
|
659
|
+
(anon ??= anonHeaders(target.resolve().anonKey, initialExtraHeaders))
|
|
645
660
|
|
|
646
661
|
// Create a retry-aware fetch bound to client-level config
|
|
647
662
|
const doFetch = createRetryFetch({
|
|
@@ -649,7 +664,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
649
664
|
timeout: config.timeout,
|
|
650
665
|
})
|
|
651
666
|
|
|
652
|
-
const auth = new AuthClient(`${
|
|
667
|
+
const auth = new AuthClient(() => `${address()}/auth/v1`, baseHeaders, {
|
|
653
668
|
initialSession: config.initialSession,
|
|
654
669
|
persistSession: config.auth?.persistSession,
|
|
655
670
|
autoRefreshToken: config.auth?.autoRefreshToken,
|
|
@@ -679,7 +694,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
679
694
|
if (previewCredential !== null) {
|
|
680
695
|
// Throws when the link will not resolve. The query layer turns that into an ordinary
|
|
681
696
|
// `{ data: null, error }`, so a revoked link reads as a message rather than as a crash.
|
|
682
|
-
return { ...baseHeaders, Authorization: `Bearer ${await previewCredential.token()}` }
|
|
697
|
+
return { ...baseHeaders(), Authorization: `Bearer ${await previewCredential.token()}` }
|
|
683
698
|
}
|
|
684
699
|
await auth.ensureValidSession()
|
|
685
700
|
const token = auth.currentAccessToken
|
|
@@ -688,10 +703,10 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
688
703
|
// Guardrail: malformed sessions can carry a JWT with empty role, which
|
|
689
704
|
// PostgREST rejects ("role \"\" does not exist"). Fall back to anon.
|
|
690
705
|
if (role !== null && role.trim().length > 0) {
|
|
691
|
-
return { ...baseHeaders, Authorization: `Bearer ${token}` }
|
|
706
|
+
return { ...baseHeaders(), Authorization: `Bearer ${token}` }
|
|
692
707
|
}
|
|
693
708
|
}
|
|
694
|
-
return baseHeaders
|
|
709
|
+
return baseHeaders()
|
|
695
710
|
}
|
|
696
711
|
|
|
697
712
|
// Every request's headers: its credential, then the caller's own extra headers as they are now.
|
|
@@ -706,22 +721,29 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
706
721
|
// request carried the anon key for the life of the page. An app's per-user storage policies saw
|
|
707
722
|
// `anon` rather than the caller, and through Studio's proxy the request was refused outright,
|
|
708
723
|
// because an anon key carries no `sub` and the proxy requires one.
|
|
709
|
-
const storage = new StorageClient(`${
|
|
724
|
+
const storage = new StorageClient(() => `${address()}/storage/v1`, getAuthHeaders, doFetch)
|
|
710
725
|
|
|
711
726
|
// The same provider the other sub-clients get, not `baseHeaders`.
|
|
712
727
|
//
|
|
713
|
-
// `baseHeaders`
|
|
728
|
+
// `baseHeaders` only ever carries the anon key, so handing it over pinned every socket to the
|
|
714
729
|
// anon key for the life of the page. Realtime enforces RLS, so on a table that is not
|
|
715
730
|
// anon-readable the socket reported SUBSCRIBED and delivered nothing, which is exactly the
|
|
716
731
|
// failure the storage note above describes.
|
|
717
|
-
const realtime = new RealtimeClient(`${
|
|
732
|
+
const realtime = new RealtimeClient(() => `${address()}/realtime/v1`, getAuthHeaders)
|
|
718
733
|
|
|
719
734
|
const onUnauthorized = config.serviceRoleKey
|
|
720
735
|
? undefined
|
|
721
736
|
: (refusedToken: string): Promise<boolean> => auth.refreshRefusedSession(refusedToken)
|
|
722
737
|
|
|
723
|
-
const functions = new FunctionsClient(
|
|
724
|
-
const runGraphql = createGraphqlRunner({
|
|
738
|
+
const functions = new FunctionsClient(address, getAuthHeaders, doFetch, onUnauthorized)
|
|
739
|
+
const runGraphql = createGraphqlRunner({
|
|
740
|
+
get endpoint(): string {
|
|
741
|
+
return `${address()}/graphql/v1`
|
|
742
|
+
},
|
|
743
|
+
send: doFetch,
|
|
744
|
+
headers: getAuthHeaders,
|
|
745
|
+
onUnauthorized,
|
|
746
|
+
})
|
|
725
747
|
|
|
726
748
|
// Signing in has to reach an already-open socket.
|
|
727
749
|
//
|
|
@@ -746,10 +768,13 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
746
768
|
TTables extends Record<string, TableDef> = Record<string, TableDef>,
|
|
747
769
|
TName extends string = string,
|
|
748
770
|
>(table: string): TableClient<TDef, TTables, TName> =>
|
|
749
|
-
new TableClient<TDef, TTables, TName>(
|
|
771
|
+
new TableClient<TDef, TTables, TName>(address, table, getAuthHeaders, realtime, queryCache, onUnauthorized, doFetch)
|
|
750
772
|
|
|
751
773
|
return {
|
|
752
|
-
|
|
774
|
+
/** The API address: as given, else as the page has set it; empty while neither has one. */
|
|
775
|
+
get url(): string {
|
|
776
|
+
return target.currentUrl()
|
|
777
|
+
},
|
|
753
778
|
serviceRoleKey: config.serviceRoleKey,
|
|
754
779
|
|
|
755
780
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
@@ -817,7 +842,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
817
842
|
try {
|
|
818
843
|
res = await fetchWithOptional401Retry(
|
|
819
844
|
doFetch,
|
|
820
|
-
`${
|
|
845
|
+
`${address()}/rest/v1/rpc/${fn}`,
|
|
821
846
|
{
|
|
822
847
|
method,
|
|
823
848
|
...(params !== undefined && method !== "HEAD" && { body: JSON.stringify(params) }),
|
|
@@ -832,7 +857,9 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
832
857
|
|
|
833
858
|
if (!res.ok) {
|
|
834
859
|
const body = await readJsonObject(res)
|
|
835
|
-
|
|
860
|
+
// A PostgrestError is one of the family: its own fields are the result's, hint and details
|
|
861
|
+
// only when the server gave them.
|
|
862
|
+
const error = PostgrestError.fromResponse(
|
|
836
863
|
{
|
|
837
864
|
message: refusalText(body),
|
|
838
865
|
code: typeof body["code"] === "string" ? body["code"] : undefined,
|
|
@@ -841,16 +868,7 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
841
868
|
},
|
|
842
869
|
res.status,
|
|
843
870
|
)
|
|
844
|
-
return {
|
|
845
|
-
data: null,
|
|
846
|
-
error: {
|
|
847
|
-
message: pgError.message,
|
|
848
|
-
status: pgError.statusCode,
|
|
849
|
-
code: pgError.code,
|
|
850
|
-
...(pgError.hint !== null && pgError.hint !== "" && { hint: pgError.hint }),
|
|
851
|
-
...(pgError.details !== null && pgError.details !== "" && { details: pgError.details }),
|
|
852
|
-
},
|
|
853
|
-
}
|
|
871
|
+
return { data: null, error }
|
|
854
872
|
}
|
|
855
873
|
|
|
856
874
|
if (method === "HEAD" || res.status === 204) {
|