@supatype/client 0.8.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.
Files changed (126) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +73 -69
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +110 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +50 -6
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +132 -40
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +4 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +2 -0
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/error-codes-doc.d.ts +1 -1
  15. package/dist/error-codes-doc.d.ts.map +1 -1
  16. package/dist/error-codes-doc.js +7 -0
  17. package/dist/error-codes-doc.js.map +1 -1
  18. package/dist/errors.d.ts +81 -21
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +133 -46
  21. package/dist/errors.js.map +1 -1
  22. package/dist/graphql-transport.d.ts +10 -3
  23. package/dist/graphql-transport.d.ts.map +1 -1
  24. package/dist/graphql-transport.js +5 -5
  25. package/dist/graphql-transport.js.map +1 -1
  26. package/dist/index.d.ts +23 -16
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +66 -48
  29. package/dist/index.js.map +1 -1
  30. package/dist/latest-rows.d.ts +29 -0
  31. package/dist/latest-rows.d.ts.map +1 -0
  32. package/dist/latest-rows.js +51 -0
  33. package/dist/latest-rows.js.map +1 -0
  34. package/dist/mutation-request.d.ts +19 -5
  35. package/dist/mutation-request.d.ts.map +1 -1
  36. package/dist/mutation-request.js +18 -15
  37. package/dist/mutation-request.js.map +1 -1
  38. package/dist/page-env-script.d.ts +12 -0
  39. package/dist/page-env-script.d.ts.map +1 -0
  40. package/dist/page-env-script.js +30 -0
  41. package/dist/page-env-script.js.map +1 -0
  42. package/dist/preview.d.ts +2 -1
  43. package/dist/preview.d.ts.map +1 -1
  44. package/dist/preview.js +7 -3
  45. package/dist/preview.js.map +1 -1
  46. package/dist/query.d.ts +49 -19
  47. package/dist/query.d.ts.map +1 -1
  48. package/dist/query.js +102 -33
  49. package/dist/query.js.map +1 -1
  50. package/dist/realtime.d.ts +5 -2
  51. package/dist/realtime.d.ts.map +1 -1
  52. package/dist/realtime.js +13 -6
  53. package/dist/realtime.js.map +1 -1
  54. package/dist/runtime-env.d.ts +59 -0
  55. package/dist/runtime-env.d.ts.map +1 -0
  56. package/dist/runtime-env.js +167 -0
  57. package/dist/runtime-env.js.map +1 -0
  58. package/dist/setup-fault.d.ts +13 -0
  59. package/dist/setup-fault.d.ts.map +1 -0
  60. package/dist/setup-fault.js +17 -0
  61. package/dist/setup-fault.js.map +1 -0
  62. package/dist/storage.d.ts +10 -5
  63. package/dist/storage.d.ts.map +1 -1
  64. package/dist/storage.js +22 -13
  65. package/dist/storage.js.map +1 -1
  66. package/dist/table-subscription.d.ts +1 -1
  67. package/dist/table-subscription.d.ts.map +1 -1
  68. package/dist/table-subscription.js +3 -2
  69. package/dist/table-subscription.js.map +1 -1
  70. package/dist/thrown-error.d.ts +16 -0
  71. package/dist/thrown-error.d.ts.map +1 -0
  72. package/dist/thrown-error.js +31 -0
  73. package/dist/thrown-error.js.map +1 -0
  74. package/dist/types.d.ts +59 -15
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +6 -2
  78. package/src/auth.ts +135 -44
  79. package/src/bindings.ts +4 -1
  80. package/src/error-codes-doc.ts +9 -1
  81. package/src/errors.ts +155 -57
  82. package/src/graphql-transport.ts +7 -8
  83. package/src/index.ts +82 -60
  84. package/src/latest-rows.ts +78 -0
  85. package/src/mutation-request.ts +34 -19
  86. package/src/page-env-script.ts +27 -0
  87. package/src/preview.ts +8 -4
  88. package/src/query.ts +128 -52
  89. package/src/realtime.ts +15 -6
  90. package/src/runtime-env.ts +220 -0
  91. package/src/setup-fault.ts +18 -0
  92. package/src/storage.ts +26 -16
  93. package/src/table-subscription.ts +3 -3
  94. package/src/thrown-error.ts +31 -0
  95. package/src/types.ts +65 -14
  96. package/tests/auth-errors.test.ts +3 -3
  97. package/tests/auth-events.test.ts +3 -7
  98. package/tests/auth-sso.test.ts +260 -0
  99. package/tests/auth-url-session.test.ts +6 -25
  100. package/tests/data-plane-auth.test.ts +1 -6
  101. package/tests/draft-insert.test.ts +9 -9
  102. package/tests/draft-update.test.ts +5 -5
  103. package/tests/entry-points.test.ts +9 -0
  104. package/tests/error-family.test.ts +79 -0
  105. package/tests/helpers/auth-unmount-binding.ts +63 -0
  106. package/tests/helpers/oauth-binding.ts +4 -3
  107. package/tests/helpers/stale-read-binding.ts +113 -0
  108. package/tests/helpers/thrown-error-binding.ts +127 -0
  109. package/tests/minimal-writes.test.ts +118 -0
  110. package/tests/postgrest-error-codes.test.ts +5 -5
  111. package/tests/query.test.ts +3 -3
  112. package/tests/rate-limit-integration.test.ts +1 -1
  113. package/tests/realtime-session-auth.test.ts +1 -4
  114. package/tests/result-error-class.test.ts +107 -0
  115. package/tests/retry-policy.test.ts +1 -1
  116. package/tests/rpc-resend.test.ts +33 -8
  117. package/tests/runtime-env-bundle.test.ts +121 -0
  118. package/tests/runtime-env-page-script.test.ts +174 -0
  119. package/tests/runtime-env.test.ts +224 -0
  120. package/tests/server-bodies.test.ts +3 -3
  121. package/tests/supatype-prepare.test.ts +139 -0
  122. package/tests/support/browser.ts +28 -0
  123. package/tests/support/jwt.ts +9 -0
  124. package/tests/thrown-error.test.ts +59 -0
  125. package/tests/unauthorized-resend.test.ts +107 -0
  126. package/tsconfig.tsbuildinfo +1 -1
package/src/errors.ts CHANGED
@@ -1,57 +1,158 @@
1
- import type { SupatypeError as SupatypeErrorShape } from "./types.js"
1
+ import type { SupatypeErrorFields } from "./types.js"
2
2
 
3
3
  /**
4
- * Typed error hierarchy for the Supatype SDK.
5
- * Every error has a machine-readable `code` field and optional `helpUrl`.
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
- * Base error class for all Supatype SDK errors.
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: string
15
- readonly helpUrl: string
16
- readonly statusCode?: number | undefined
17
-
18
- constructor(message: string, code: string, statusCode?: number) {
19
- super(message)
20
- this.name = "SupatypeError"
21
- this.code = code
22
- this.statusCode = statusCode
23
- this.helpUrl = `${DOCS_BASE}#${code.toLowerCase()}`
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
- * Authentication errors (login failures, token issues, MFA).
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 AuthError extends SupatypeError {
31
- constructor(message: string, code: string = "AUTH_ERROR", statusCode?: number) {
32
- super(message, code, statusCode)
33
- this.name = "AuthError"
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
- * PostgREST API errors with structured details.
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 PostgrestError extends SupatypeError {
41
- readonly details: string | null
42
- readonly hint: string | null
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
- statusCode?: number,
148
+ status?: number,
48
149
  details?: string | null,
49
150
  hint?: string | null,
50
151
  ) {
51
- super(message, code, statusCode)
52
- this.name = "PostgrestError"
53
- this.details = details ?? null
54
- this.hint = hint ?? null
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
- }, statusCode: number): PostgrestError {
166
+ }, status: number): PostgrestError {
66
167
  return new PostgrestError(
67
168
  body.message || "PostgREST error",
68
- body.code || `PGRST${statusCode}`,
69
- statusCode,
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 SupatypeError {
80
- constructor(message: string, code: string = "STORAGE_ERROR", statusCode?: number) {
81
- super(message, code, statusCode)
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 SupatypeError {
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 SupatypeError {
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 SupatypeError {
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): SupatypeErrorShape {
237
- if (e instanceof SupatypeError) {
238
- return {
239
- message: e.message,
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
  }
@@ -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
- import { fetchWithOptional401Retry, type HeadersProvider } from "./query.js"
14
- import type { SupatypeError } from "./types.js"
13
+ import { fetchWithOptional401Retry, type HeadersProvider, type UnauthorizedHandler } from "./query.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 = {
@@ -19,7 +18,7 @@ export type GraphqlTransport = {
19
18
  readonly endpoint: string
20
19
  readonly send: RequestTransport
21
20
  readonly headers: HeadersProvider
22
- readonly onUnauthorized?: (() => Promise<void>) | undefined
21
+ readonly onUnauthorized?: UnauthorizedHandler | undefined
23
22
  /** Whose schema a request reads, from its headers. Defaults to the bearer token's role. */
24
23
  readonly schemaKey?: ((headers: Record<string, string>) => string) | undefined
25
24
  }
@@ -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
  }