@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.
Files changed (116) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +71 -68
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +82 -0
  5. package/dist/auth.d.ts +41 -6
  6. package/dist/auth.d.ts.map +1 -1
  7. package/dist/auth.js +102 -32
  8. package/dist/auth.js.map +1 -1
  9. package/dist/bindings.d.ts +3 -0
  10. package/dist/bindings.d.ts.map +1 -1
  11. package/dist/bindings.js +2 -0
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/error-codes-doc.d.ts +1 -1
  14. package/dist/error-codes-doc.d.ts.map +1 -1
  15. package/dist/error-codes-doc.js +7 -0
  16. package/dist/error-codes-doc.js.map +1 -1
  17. package/dist/errors.d.ts +81 -21
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +133 -46
  20. package/dist/errors.js.map +1 -1
  21. package/dist/graphql-transport.d.ts +8 -1
  22. package/dist/graphql-transport.d.ts.map +1 -1
  23. package/dist/graphql-transport.js +5 -5
  24. package/dist/graphql-transport.js.map +1 -1
  25. package/dist/index.d.ts +9 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +52 -37
  28. package/dist/index.js.map +1 -1
  29. package/dist/latest-rows.d.ts +29 -0
  30. package/dist/latest-rows.d.ts.map +1 -0
  31. package/dist/latest-rows.js +51 -0
  32. package/dist/latest-rows.js.map +1 -0
  33. package/dist/mutation-request.d.ts +2 -1
  34. package/dist/mutation-request.d.ts.map +1 -1
  35. package/dist/mutation-request.js +2 -1
  36. package/dist/mutation-request.js.map +1 -1
  37. package/dist/page-env-script.d.ts +12 -0
  38. package/dist/page-env-script.d.ts.map +1 -0
  39. package/dist/page-env-script.js +30 -0
  40. package/dist/page-env-script.js.map +1 -0
  41. package/dist/preview.d.ts +2 -1
  42. package/dist/preview.d.ts.map +1 -1
  43. package/dist/preview.js +7 -3
  44. package/dist/preview.js.map +1 -1
  45. package/dist/query.d.ts +11 -5
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +22 -13
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime.d.ts +5 -2
  50. package/dist/realtime.d.ts.map +1 -1
  51. package/dist/realtime.js +13 -6
  52. package/dist/realtime.js.map +1 -1
  53. package/dist/runtime-env.d.ts +59 -0
  54. package/dist/runtime-env.d.ts.map +1 -0
  55. package/dist/runtime-env.js +167 -0
  56. package/dist/runtime-env.js.map +1 -0
  57. package/dist/setup-fault.d.ts +13 -0
  58. package/dist/setup-fault.d.ts.map +1 -0
  59. package/dist/setup-fault.js +17 -0
  60. package/dist/setup-fault.js.map +1 -0
  61. package/dist/storage.d.ts +10 -5
  62. package/dist/storage.d.ts.map +1 -1
  63. package/dist/storage.js +22 -13
  64. package/dist/storage.js.map +1 -1
  65. package/dist/table-subscription.d.ts +1 -1
  66. package/dist/table-subscription.d.ts.map +1 -1
  67. package/dist/table-subscription.js +3 -2
  68. package/dist/table-subscription.js.map +1 -1
  69. package/dist/thrown-error.d.ts +16 -0
  70. package/dist/thrown-error.d.ts.map +1 -0
  71. package/dist/thrown-error.js +31 -0
  72. package/dist/thrown-error.js.map +1 -0
  73. package/dist/types.d.ts +59 -15
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/types.js.map +1 -1
  76. package/package.json +2 -1
  77. package/src/auth.ts +106 -36
  78. package/src/bindings.ts +3 -0
  79. package/src/error-codes-doc.ts +9 -1
  80. package/src/errors.ts +155 -57
  81. package/src/graphql-transport.ts +5 -6
  82. package/src/index.ts +62 -44
  83. package/src/latest-rows.ts +78 -0
  84. package/src/mutation-request.ts +3 -2
  85. package/src/page-env-script.ts +27 -0
  86. package/src/preview.ts +8 -4
  87. package/src/query.ts +27 -16
  88. package/src/realtime.ts +15 -6
  89. package/src/runtime-env.ts +220 -0
  90. package/src/setup-fault.ts +18 -0
  91. package/src/storage.ts +26 -16
  92. package/src/table-subscription.ts +3 -3
  93. package/src/thrown-error.ts +31 -0
  94. package/src/types.ts +65 -14
  95. package/tests/auth-errors.test.ts +3 -3
  96. package/tests/auth-events.test.ts +3 -7
  97. package/tests/auth-sso.test.ts +260 -0
  98. package/tests/auth-url-session.test.ts +6 -25
  99. package/tests/entry-points.test.ts +9 -0
  100. package/tests/error-family.test.ts +79 -0
  101. package/tests/helpers/auth-unmount-binding.ts +63 -0
  102. package/tests/helpers/oauth-binding.ts +4 -3
  103. package/tests/helpers/stale-read-binding.ts +113 -0
  104. package/tests/helpers/thrown-error-binding.ts +127 -0
  105. package/tests/postgrest-error-codes.test.ts +4 -4
  106. package/tests/rate-limit-integration.test.ts +1 -1
  107. package/tests/result-error-class.test.ts +107 -0
  108. package/tests/retry-policy.test.ts +1 -1
  109. package/tests/runtime-env-bundle.test.ts +121 -0
  110. package/tests/runtime-env-page-script.test.ts +174 -0
  111. package/tests/runtime-env.test.ts +224 -0
  112. package/tests/server-bodies.test.ts +3 -3
  113. package/tests/support/browser.ts +28 -0
  114. package/tests/support/jwt.ts +5 -0
  115. package/tests/thrown-error.test.ts +59 -0
  116. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,78 @@
1
+ import type { AnyClient } from "./index.js"
2
+ import type { SupatypeError } from "./types.js"
3
+ import { isRowsOf } from "./caller-types.js"
4
+ import { reportThrown } from "./thrown-error.js"
5
+
6
+ /** The read the Vue, Svelte and Solid queries make: columns, equality filters, order and a page. */
7
+ export interface RowsReadOptions {
8
+ columns?: string | undefined
9
+ filter?: Record<string, unknown> | undefined
10
+ order?: { column: string; ascending?: boolean | undefined } | undefined
11
+ limit?: number | undefined
12
+ offset?: number | undefined
13
+ }
14
+
15
+ /** Where a binding shows its reads: one started, and the newest one's answer. */
16
+ export interface RowsView<TRow> {
17
+ started(): void
18
+ settled(data: TRow[] | null, error: SupatypeError | null): void
19
+ }
20
+
21
+ /**
22
+ * A binding's reads of one table, where only the newest may change what it shows.
23
+ *
24
+ * A refetch while a read is in flight puts two reads on the wire, and the older can land last;
25
+ * its answer, a returned error or a throw, is dropped rather than replacing the newer one's. A
26
+ * read that throws (a client with no API address, say) ends like one that was refused, and is
27
+ * reported once with `console.error` even when a newer read has replaced it. `where` names the
28
+ * binding in that report.
29
+ */
30
+ export function latestRowsReader<TRow>(
31
+ client: AnyClient,
32
+ table: string,
33
+ where: string,
34
+ view: RowsView<TRow>,
35
+ ): (options: RowsReadOptions | undefined) => Promise<void> {
36
+ let latest = 0
37
+ return async (options) => {
38
+ const request = ++latest
39
+ view.started()
40
+ const answer = await answerOf<TRow>(client, table, where, options)
41
+ if (request === latest) view.settled(answer.data, answer.error)
42
+ }
43
+ }
44
+
45
+ async function answerOf<TRow>(
46
+ client: AnyClient,
47
+ table: string,
48
+ where: string,
49
+ options: RowsReadOptions | undefined,
50
+ ): Promise<{ data: TRow[] | null; error: SupatypeError | null }> {
51
+ try {
52
+ const result = await readRows(client, table, options)
53
+ return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error }
54
+ } catch (e) {
55
+ return { data: null, error: reportThrown(where, e) }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * The read `options` describe. Through the untyped client: the generated row types do not survive
61
+ * a table name known only at run time, so the binding types the rows as `TRow` once they arrive.
62
+ */
63
+ function readRows(client: AnyClient, table: string, options: RowsReadOptions | undefined) {
64
+ let query = client.from(table).select(options?.columns)
65
+ for (const [col, val] of Object.entries(options?.filter ?? {})) {
66
+ query = query.eq(col, val)
67
+ }
68
+ if (options?.order !== undefined) {
69
+ query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
70
+ }
71
+ if (options?.limit !== undefined) {
72
+ query = query.limit(options.limit)
73
+ }
74
+ if (options?.offset !== undefined) {
75
+ query = query.range(options.offset, options.offset + (options.limit ?? 100) - 1)
76
+ }
77
+ return query
78
+ }
@@ -1,5 +1,6 @@
1
1
  import type { AnyClient } from "./index.js"
2
- import type { DraftUpdateOptions, QueryResult, SupatypeError } from "./types.js"
2
+ import type { DraftUpdateOptions, QueryResult } from "./types.js"
3
+ import { SupatypeError } from "./errors.js"
3
4
  import { isRowsOf } from "./caller-types.js"
4
5
 
5
6
  export type MutationOperation = "insert" | "update" | "delete" | "upsert"
@@ -74,7 +75,7 @@ export async function runMutation<TRow>(
74
75
  request: MutationRequest = {},
75
76
  ): Promise<MutationOutcome<TRow>> {
76
77
  const pending = mutationRequest(client.from(table), operation, data, request)
77
- if (typeof pending === "string") return { data: null, error: { message: pending }, count: null }
78
+ if (typeof pending === "string") return { data: null, error: new SupatypeError({ message: pending }), count: null }
78
79
  const result = await pending
79
80
  return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count }
80
81
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The page's `<script src=".../supatype-env.js">` element, when it has one.
3
+ *
4
+ * A page that has the element and still no `window.__SUPATYPE_ENV__` did not run the script: it was
5
+ * blocked, failed to load, ran after the app's own script, or came from a server too old to serve
6
+ * it. A misconfigured server still answers 200 with a script setting `error`, so a missing global
7
+ * never means the server refused. The error a request throws then says the script is there and to
8
+ * open it, not to add it.
9
+ */
10
+
11
+ /** The absolute address of the page's `/supatype-env.js` script, or undefined when it has none. */
12
+ export function pageEnvScript(): string | undefined {
13
+ if (typeof document === "undefined") return undefined
14
+ for (const script of Array.from(document.scripts)) {
15
+ if (isEnvScript(script.src)) return script.src
16
+ }
17
+ return undefined
18
+ }
19
+
20
+ function isEnvScript(src: string): boolean {
21
+ if (src === "") return false
22
+ try {
23
+ return new URL(src).pathname.endsWith("/supatype-env.js")
24
+ } catch {
25
+ return false
26
+ }
27
+ }
package/src/preview.ts CHANGED
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  import { readJsonObject } from "./json.js"
24
+ import { settle, type Deferred } from "./runtime-env.js"
24
25
 
25
26
  /** Milliseconds of slack before expiry at which the token is treated as spent. */
26
27
  const REFRESH_SKEW_MS = 5_000
@@ -47,14 +48,14 @@ export class PreviewLinkError extends Error {
47
48
  * for as long as any request is outstanding, and this needs two strings.
48
49
  */
49
50
  export class PreviewCredential {
50
- readonly #endpoint: string
51
+ readonly #baseUrl: Deferred<string>
51
52
  readonly #code: string
52
53
  #token: string | null = null
53
54
  #expiresAtMs = 0
54
55
  #inFlight: Promise<string> | null = null
55
56
 
56
- constructor(baseUrl: string, code: string) {
57
- this.#endpoint = `${baseUrl.replace(/\/$/, "")}/preview-links/resolve`
57
+ constructor(baseUrl: Deferred<string>, code: string) {
58
+ this.#baseUrl = baseUrl
58
59
  this.#code = code
59
60
  }
60
61
 
@@ -71,9 +72,12 @@ export class PreviewCredential {
71
72
  }
72
73
 
73
74
  async #exchange(): Promise<string> {
75
+ // Read before the request rather than inside it: a client with no address throws the error that
76
+ // says so, not one calling the link invalid.
77
+ const endpoint = `${settle(this.#baseUrl).replace(/\/$/, "")}/preview-links/resolve`
74
78
  let response: Response
75
79
  try {
76
- response = await fetch(this.#endpoint, {
80
+ response = await fetch(endpoint, {
77
81
  method: "POST",
78
82
  headers: { "Content-Type": "application/json" },
79
83
  body: JSON.stringify({ code: this.#code }),
package/src/query.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  import type { QueryCache, QueryCacheOptions, CacheStatus } from "./query-cache.js"
2
2
  import { buildCacheKey, defaultQueryCache } from "./query-cache.js"
3
- import type { MaskedField, QueryResult, SelectQueryOptions, SupatypeError, TableDef } from "./types.js"
3
+ import type { MaskedField, QueryResult, SelectQueryOptions, TableDef } from "./types.js"
4
4
  import { DRAFT_SCHEMA, PUBLISHING_SCHEMA } from "./types.js"
5
5
  import { createCall, createdKeys, inCreatedOrder, readBackColumns } from "./draft-create.js"
6
6
  import type { SelectRow } from "./select-types.js"
7
7
  import { parseRowsExactly, tableFromPath } from "./exact-response.js"
8
8
  import { stringifyWithBigInts } from "./exact-values.js"
9
9
  import { FilterBuilder } from "./filters.js"
10
- import { PostgrestErrorCodes, transportFailure } from "./errors.js"
10
+ import { PostgrestErrorCodes, SupatypeError, transportFailure } from "./errors.js"
11
11
  import { plainFetch, type FetchOptions, type RequestTransport } from "./fetch-with-retry.js"
12
12
  import { isJsonObject, isOneOf, readJsonObject, refusalText } from "./json.js"
13
13
  import { bearerRole } from "./jwt.js"
14
+ import { settle, type Deferred } from "./runtime-env.js"
14
15
 
15
16
  const DEBUG_AUTH =
16
17
  (typeof process !== "undefined" && process.env["NEXT_PUBLIC_SUPATYPE_DEBUG_AUTH"] === "1") ||
@@ -35,7 +36,7 @@ function callerRows<TRow>(value: unknown): TRow[] | null {
35
36
 
36
37
  /** The body was JSON but not rows: PostgREST does not answer a table request that way. */
37
38
  function notRows(status: number): SupatypeError {
38
- return { message: `Unexpected response body: expected rows (HTTP ${status})`, status }
39
+ return new SupatypeError({ message: `Unexpected response body: expected rows (HTTP ${status})`, status })
39
40
  }
40
41
 
41
42
  /**
@@ -64,7 +65,7 @@ export function parseMaskedFields(header: string | null): MaskedField[] | undefi
64
65
  * the same error whether PostgREST refused the request or the client found the rows wrong.
65
66
  */
66
67
  function notOneRow(): SupatypeError {
67
- return { message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND }
68
+ return new SupatypeError({ message: "Cannot coerce the result to a single JSON object", code: PostgrestErrorCodes.NOT_FOUND })
68
69
  }
69
70
 
70
71
  /**
@@ -74,7 +75,7 @@ function notOneRow(): SupatypeError {
74
75
  * validator only ever runs on a write, so the column it named never reached the caller.
75
76
  */
76
77
  function refusal(err: Record<string, unknown>, status: number): SupatypeError {
77
- return {
78
+ return new SupatypeError({
78
79
  message: refusalText(err) ?? String(err["hint"] ?? "Request failed"),
79
80
  status,
80
81
  ...(err["code"] !== undefined && { code: String(err["code"]) }),
@@ -83,7 +84,7 @@ function refusal(err: Record<string, unknown>, status: number): SupatypeError {
83
84
  ...(typeof err["field"] === "string" && { field: err["field"] }),
84
85
  ...(typeof err["hint"] === "string" && err["hint"] !== "" && { hint: err["hint"] }),
85
86
  ...(typeof err["details"] === "string" && err["details"] !== "" && { details: err["details"] }),
86
- }
87
+ })
87
88
  }
88
89
 
89
90
  /** The refusal a failed request answered with, logged with `context` when auth debugging is on. */
@@ -112,7 +113,7 @@ async function readRefusal(
112
113
  */
113
114
  function readRows<TRow>(body: string, path: string, status: number, count: number | null): QueryResult<TRow[]> {
114
115
  const parsed = parseRowsExactly(body, tableFromPath(path))
115
- if (!parsed.ok) return { data: null, error: { message: parsed.message, status }, count: null }
116
+ if (!parsed.ok) return { data: null, error: new SupatypeError({ message: parsed.message, status }), count: null }
116
117
  const rows = callerRows<TRow>(parsed.value)
117
118
  if (rows === null) return { data: null, error: notRows(status), count: null }
118
119
  return { data: rows, error: null, count }
@@ -232,7 +233,7 @@ export function parseContentRangeTotal(header: string | null): number | null {
232
233
  // ─── QueryBuilder ─────────────────────────────────────────────────────────────
233
234
 
234
235
  export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<QueryResult<TRow[]>> {
235
- private readonly baseUrl: string
236
+ private readonly base: Deferred<string>
236
237
  private readonly path: string
237
238
  private readonly getHeaders: HeadersProvider
238
239
  private readonly onUnauthorized: UnauthorizedHandler | undefined
@@ -244,7 +245,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
244
245
  private readonly head: boolean
245
246
 
246
247
  constructor(
247
- baseUrl: string,
248
+ baseUrl: Deferred<string>,
248
249
  path: string,
249
250
  headers: Record<string, string> | HeadersProvider,
250
251
  columns?: string | undefined,
@@ -254,7 +255,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
254
255
  transport: RequestTransport = plainFetch,
255
256
  ) {
256
257
  super()
257
- this.baseUrl = baseUrl
258
+ this.base = baseUrl
258
259
  this.path = path
259
260
  this.getHeaders = asHeadersProvider(headers)
260
261
  this.onUnauthorized = onUnauthorized
@@ -354,6 +355,11 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
354
355
  return this._fetch({}).then(onfulfilled, onrejected)
355
356
  }
356
357
 
358
+ /** The address, read now: a deferred one is only known when the request is sent. */
359
+ private get baseUrl(): string {
360
+ return settle(this.base)
361
+ }
362
+
357
363
  private buildRequestUrl(): string {
358
364
  const qs = this.params.toString()
359
365
  return `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
@@ -524,7 +530,7 @@ function isWriteResult<TResult>(value: unknown): value is TResult {
524
530
  /** `single()` or `maybeSingle()` on a write that asked for no rows, refused before anything is sent. */
525
531
  function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
526
532
  const message = "A write returns no rows until select() asks for them: call select() before single() or maybeSingle()"
527
- return { data: null, error: { message }, count: null }
533
+ return { data: null, error: new SupatypeError({ message }), count: null }
528
534
  }
529
535
 
530
536
  /**
@@ -538,7 +544,7 @@ function rowNotSelected(): { data: null; error: SupatypeError; count: null } {
538
544
  export class MutationBuilder<TRow, TTables = unknown, TName extends string = string, TResult = null>
539
545
  extends FilterBuilder
540
546
  implements PromiseLike<QueryResult<TResult>> {
541
- private readonly baseUrl: string
547
+ private readonly base: Deferred<string>
542
548
  private readonly path: string
543
549
  private readonly getHeaders: HeadersProvider
544
550
  private readonly onUnauthorized: UnauthorizedHandler | undefined
@@ -553,7 +559,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
553
559
  private returning = false
554
560
 
555
561
  constructor(
556
- baseUrl: string,
562
+ baseUrl: Deferred<string>,
557
563
  path: string,
558
564
  headers: Record<string, string> | HeadersProvider,
559
565
  method: HttpMethod,
@@ -563,7 +569,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
563
569
  transport: RequestTransport = plainFetch,
564
570
  ) {
565
571
  super()
566
- this.baseUrl = baseUrl
572
+ this.base = baseUrl
567
573
  this.path = path
568
574
  this.getHeaders = asHeadersProvider(headers)
569
575
  this.onUnauthorized = onUnauthorized
@@ -655,6 +661,11 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
655
661
  }
656
662
  }
657
663
 
664
+ /** The address, read now: a deferred one is only known when the request is sent. */
665
+ private get baseUrl(): string {
666
+ return settle(this.base)
667
+ }
668
+
658
669
  private async _execute(fetchHeaders: Record<string, string> = {}): Promise<QueryResult<TRow[]>> {
659
670
  if (this.refusal !== undefined) return { data: null, error: this.refusal, count: null }
660
671
  if (this.createThrough !== undefined) return this.createDraftRecords(this.createThrough)
@@ -748,7 +759,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
748
759
  if (!this.returning) return this.nothingReturned()
749
760
  const select = readBackColumns(this.params.get("select"), target.primaryKey, keys.length)
750
761
  const result = await new QueryBuilder<Record<string, unknown>>(
751
- this.baseUrl,
762
+ this.base,
752
763
  this.path,
753
764
  this.getHeaders,
754
765
  select,
@@ -779,7 +790,7 @@ export class MutationBuilder<TRow, TTables = unknown, TName extends string = str
779
790
  const table = body["model_table"]
780
791
  if (!res.ok) return readRefusal(res, `[supatype:mutation] ${fn} failed`, async () => ({ url, table }))
781
792
  const answer: unknown = await res.json().catch(() => null)
782
- return createdKeys(answer) ?? { message: `${fn} answered without the record ids`, status: res.status }
793
+ return createdKeys(answer) ?? new SupatypeError({ message: `${fn} answered without the record ids`, status: res.status })
783
794
  }
784
795
  }
785
796
 
package/src/realtime.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
2
+ import { settle, type Deferred } from "./runtime-env.js"
2
3
  import { coerceRecordKinds, type ExactFields } from "./exact-values.js"
3
4
  import { isArrayOf, isJsonObject, isOneOf, isRecordOf, isShape, isString, nullable, optional, type Guard } from "./json.js"
4
5
 
@@ -191,7 +192,7 @@ const SUBSCRIBED_TO = "subscribed to "
191
192
  // ─── Realtime client ─────────────────────────────────────────────────────────
192
193
 
193
194
  export class RealtimeClient {
194
- private readonly url: string
195
+ private readonly base: Deferred<string>
195
196
  private readonly getHeaders: HeadersProvider
196
197
  private ws: WebSocket | null = null
197
198
  private channels = new Map<string, ChannelState>()
@@ -223,12 +224,16 @@ export class RealtimeClient {
223
224
  * for the life of the page: on a table that is not anon-readable it reported SUBSCRIBED and then
224
225
  * delivered nothing, which is indistinguishable from a quiet table.
225
226
  */
226
- constructor(url: string, auth: Record<string, string> | HeadersProvider) {
227
- // Convert http(s) URL to ws(s) URL
228
- this.url = url.replace(/^http/, "ws")
227
+ constructor(url: Deferred<string>, auth: Record<string, string> | HeadersProvider) {
228
+ this.base = url
229
229
  this.getHeaders = asHeadersProvider(auth)
230
230
  }
231
231
 
232
+ /** The socket's address, as ws(s) for an http(s) one. Read when connecting, not before. */
233
+ private get url(): string {
234
+ return settle(this.base).replace(/^http/, "ws")
235
+ }
236
+
232
237
  /** The token this socket should authenticate with, or undefined when there is none. */
233
238
  private async resolveToken(): Promise<string | undefined> {
234
239
  const token = bearerToken(await this.getHeaders())
@@ -482,6 +487,9 @@ export class RealtimeClient {
482
487
  // One connect at a time: resolving the token is asynchronous, so two subscribes in the same
483
488
  // tick would otherwise each open a socket and the second would orphan the first.
484
489
  if (this.isLive() || this.attempt !== null) return
490
+ // Read here, synchronously, so a client with no address or anon key throws from the subscribe
491
+ // that asked for the socket rather than from a background attempt nobody is waiting on.
492
+ const url = this.url
485
493
 
486
494
  let attempt: Promise<void>
487
495
  const isCurrent = (): boolean => this.attempt === attempt
@@ -489,7 +497,7 @@ export class RealtimeClient {
489
497
  // is still the current one. Called directly, the path that already has a token reaches that
490
498
  // question with no await in front of it, compares against a handle nobody had stored yet, and
491
499
  // abandons itself.
492
- attempt = Promise.resolve().then(() => this.openSocket(isCurrent, token))
500
+ attempt = Promise.resolve().then(() => this.openSocket(url, isCurrent, token))
493
501
  this.attempt = attempt
494
502
  void attempt.finally(() => {
495
503
  // Only if it is still ours. An attempt abandoned mid-flight must not clear the handle of the
@@ -506,6 +514,7 @@ export class RealtimeClient {
506
514
  * meantime, by disconnect() or by reauthenticate(), does not install itself afterwards.
507
515
  */
508
516
  private async openSocket(
517
+ url: string,
509
518
  isCurrent: () => boolean,
510
519
  known?: string | undefined,
511
520
  ): Promise<void> {
@@ -526,7 +535,7 @@ export class RealtimeClient {
526
535
  if (!isCurrent()) return
527
536
 
528
537
  this.currentToken = token
529
- const wsUrl = token ? `${this.url}?token=${encodeURIComponent(token)}` : this.url
538
+ const wsUrl = token ? `${url}?token=${encodeURIComponent(token)}` : url
530
539
  const ws = new WebSocket(wsUrl)
531
540
  this.ws = ws
532
541
 
@@ -0,0 +1,220 @@
1
+ /**
2
+ * The address and anon key a client runs with, when the build did not carry them.
3
+ *
4
+ * A server that hosts the app answers `GET /supatype-env.js` with
5
+ *
6
+ * window.__SUPATYPE_ENV__ = { url: "https://api.example.com", anonKey: "..." }
7
+ *
8
+ * and the page loads it before its own code: a classic `<script>` in a static app's head, or, in a
9
+ * Next.js app, the route `@supatype/ssr/next` exports, loaded by the root layout. One build then
10
+ * works for every deployment that serves it. A value the build did carry always wins.
11
+ *
12
+ * A server that cannot give the values still answers 200, with `{ error: "<why>" }` in their place:
13
+ * a browser runs no script answered with an error status, and tells the page nothing of why. The
14
+ * first request quotes that reason, with no request of its own.
15
+ *
16
+ * Nothing is checked when the client is created. `next build` prerenders every static page, so a
17
+ * client created at module scope runs during the build, which has neither value and sends nothing.
18
+ * The first request is what needs them: it reads the page again at that moment, since the script
19
+ * may load after the module that created the client, and throws naming whatever is still missing.
20
+ * That read happens at run time, so a bundler that replaced both names with `undefined` cannot fold
21
+ * it away, as it could an app's own `if (!key) throw`. No address is ever guessed from the page.
22
+ */
23
+
24
+ import { MissingClientValuesError, type ClientValue } from "./setup-fault.js"
25
+ import { objectOrEmpty } from "./json.js"
26
+ import { pageEnvScript } from "./page-env-script.js"
27
+ import type { SupatypeClientConfig } from "./types.js"
28
+
29
+ declare global {
30
+ /**
31
+ * Set by `<script src="/supatype-env.js">`. Typed `unknown` because nothing at compile time knows
32
+ * what the page holds; each field is checked before use.
33
+ */
34
+ var __SUPATYPE_ENV__: unknown
35
+ }
36
+
37
+ /** The two values every request needs, once each has been found. */
38
+ interface ResolvedClientTarget {
39
+ url: string
40
+ anonKey: string
41
+ }
42
+
43
+ /**
44
+ * A value, or a function that reads it when a request needs it. The sub-clients take either, so
45
+ * `createClient` can hand them an address it does not know yet.
46
+ */
47
+ export type Deferred<T extends string | Record<string, string>> = T | (() => T)
48
+
49
+ /** The value now: a plain one as it is, a deferred one read. */
50
+ export function settle<T extends string | Record<string, string>>(value: Deferred<T>): T {
51
+ return typeof value === "function" ? value() : value
52
+ }
53
+
54
+ /**
55
+ * Each framework's public prefix: Vite, SvelteKit and Astro (`PUBLIC_`), Next.js, Expo. The same
56
+ * list as the CLI's `frontend-env.ts`, which writes these names; this package cannot import it.
57
+ */
58
+ const FRONTEND_PREFIXES = ["VITE_", "PUBLIC_", "NEXT_PUBLIC_", "EXPO_PUBLIC_"] as const
59
+
60
+ const MISSING_VALUES = {
61
+ url: { label: "API address", name: "SUPATYPE_URL" },
62
+ anonKey: { label: "anon key", name: "SUPATYPE_ANON_KEY" },
63
+ } as const
64
+
65
+ /** A non-empty string, else undefined: what a bundler leaves for an unset name is either. */
66
+ function present(value: unknown): string | undefined {
67
+ return typeof value === "string" && value.trim() !== "" ? value : undefined
68
+ }
69
+
70
+ /** An absolute http or https address, else undefined. */
71
+ function httpUrl(value: unknown): string | undefined {
72
+ const text = present(value)
73
+ if (text === undefined) return undefined
74
+ try {
75
+ const protocol = new URL(text).protocol
76
+ return protocol === "http:" || protocol === "https:" ? text : undefined
77
+ } catch {
78
+ return undefined
79
+ }
80
+ }
81
+
82
+ /** The page's `__SUPATYPE_ENV__` fields, each still unchecked; none when it is not an object. */
83
+ function pageEnv(): { url: unknown; anonKey: unknown; error: unknown } {
84
+ const env = objectOrEmpty(globalThis.__SUPATYPE_ENV__)
85
+ return { url: env["url"], anonKey: env["anonKey"], error: env["error"] }
86
+ }
87
+
88
+ /** What the error says, for the values still missing, by whichever name each is set under. */
89
+ interface MissingNames {
90
+ labels: string
91
+ buildNames: string
92
+ serverNames: string
93
+ pronoun: "it" | "them"
94
+ }
95
+
96
+ /** The build-time names and the fix that fills them, which both kinds of the error end with. */
97
+ function buildTimeFix(n: MissingNames): string {
98
+ return (
99
+ `Or set ${n.pronoun} at build time under the name your framework reads: ${n.buildNames}. Building ` +
100
+ `with \`supatype build -- <your build command>\` fills them from your deployment.`
101
+ )
102
+ }
103
+
104
+ /** In a page: the page set no `__SUPATYPE_ENV__`, so the script that sets it comes first. */
105
+ function pageMessage(n: MissingNames): string {
106
+ return (
107
+ `Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
108
+ `window.__SUPATYPE_ENV__ by its first request.\n` +
109
+ `When Supatype hosts the app, add <script src="/supatype-env.js" vite-ignore></script> to index.html before ` +
110
+ `the app's own script, and the server fills them in when the page loads. In a Next.js app, ` +
111
+ `export GET from @supatype/ssr/next in app/supatype-env.js/route.ts, load it in the root layout ` +
112
+ `with <Script src="/supatype-env.js" strategy="beforeInteractive" />, and set ${n.serverNames} ` +
113
+ `in the server's environment.\n${buildTimeFix(n)}`
114
+ )
115
+ }
116
+
117
+ /** On a server there is no page: its own variables are what to set. */
118
+ function serverMessage(n: MissingNames): string {
119
+ return (
120
+ `Supatype client has no ${n.labels}. It was given none, and it is running on a server, where ` +
121
+ `there is no page to read them from.\n` +
122
+ `Set ${n.serverNames} in the server's environment: createServerClient from @supatype/ssr reads ` +
123
+ `them when it is not given them, and @supatype/ssr/next serves them to the browser from ` +
124
+ `app/supatype-env.js/route.ts.\n${buildTimeFix(n)}`
125
+ )
126
+ }
127
+
128
+ /** The servers that answer `/supatype-env.js`, where its values or its reason come from. */
129
+ const SCRIPT_SERVERS =
130
+ "the Supatype server, or in a Next.js app the server running the route app/supatype-env.js/route.ts " +
131
+ "exports from @supatype/ssr/next"
132
+
133
+ /** In a page whose script set the server's reason in place of the values: that reason is the fix. */
134
+ function reasonMessage(n: MissingNames, script: string, reason: string): string {
135
+ return (
136
+ `Supatype client has no ${n.labels}. createClient was given none, and ${script} set no ${n.labels}, ` +
137
+ `giving the server's reason instead:\n${reason}\n` +
138
+ `Fix that in the environment of the server that answers it (${SCRIPT_SERVERS}), then reload the ` +
139
+ `page.\n${buildTimeFix(n)}`
140
+ )
141
+ }
142
+
143
+ /** In a page that has the script element and no global: the script is there, and did not run. */
144
+ function scriptDidNotRunMessage(n: MissingNames, script: string): string {
145
+ return (
146
+ `Supatype client has no ${n.labels}. createClient was given none, and the page loads ${script}, ` +
147
+ `but it had set no window.__SUPATYPE_ENV__ by the page's first request. The script did not run in ` +
148
+ `time: it was blocked, failed to load, ran after the app's own script, or came from a server too ` +
149
+ `old to serve it.\nOpen ${script} in the browser: it should set window.__SUPATYPE_ENV__. When it ` +
150
+ `does, load it before the app's own script, without async or defer. When it does not, update the ` +
151
+ `server that answers it (${SCRIPT_SERVERS}).\n${buildTimeFix(n)}`
152
+ )
153
+ }
154
+
155
+ /** In a page: the script's reason when it set one, else whether the page has the script at all. */
156
+ function pageFaultMessage(n: MissingNames): string {
157
+ const script = pageEnvScript()
158
+ const reason = present(pageEnv().error)
159
+ if (reason !== undefined) return reasonMessage(n, script ?? "/supatype-env.js", reason)
160
+ return script === undefined ? pageMessage(n) : scriptDidNotRunMessage(n, script)
161
+ }
162
+
163
+ /** Each missing value's label and every name it is set under, as the error words them. */
164
+ function missingNames(missing: readonly ClientValue[]): MissingNames {
165
+ return {
166
+ labels: missing.map((key) => MISSING_VALUES[key].label).join(" and "),
167
+ buildNames: missing.flatMap((key) => FRONTEND_PREFIXES.map((prefix) => `${prefix}${MISSING_VALUES[key].name}`)).join(", "),
168
+ serverNames: missing.map((key) => MISSING_VALUES[key].name).join(" and "),
169
+ pronoun: missing.length > 1 ? "them" : "it",
170
+ }
171
+ }
172
+
173
+ /** The error for the values still missing, naming each one's every name and every fix. */
174
+ function missingClientValuesError(missing: readonly ClientValue[]): MissingClientValuesError {
175
+ const names = missingNames(missing)
176
+ // Read when the error is made, as the page is: a bundler cannot know which side it runs on.
177
+ const onServer = typeof window === "undefined"
178
+ return new MissingClientValuesError(onServer ? serverMessage(names) : pageFaultMessage(names), missing)
179
+ }
180
+
181
+ /**
182
+ * Where one client sends its requests, found when the first one is made.
183
+ *
184
+ * Each value is the one given, else the page's `__SUPATYPE_ENV__` as it is when a request asks.
185
+ * A value once found is kept, so every request after it goes to the same place, and the page is
186
+ * not read again once both are known.
187
+ */
188
+ export class ClientTarget {
189
+ #url: string | undefined
190
+ #anonKey: string | undefined
191
+ #resolved: ResolvedClientTarget | undefined
192
+
193
+ constructor(given: Pick<SupatypeClientConfig, "url" | "anonKey">) {
194
+ this.#url = present(given.url)
195
+ this.#anonKey = present(given.anonKey)
196
+ }
197
+
198
+ /** Both values, reading the page for any not found yet. Throws naming whatever is still missing. */
199
+ resolve(): ResolvedClientTarget {
200
+ if (this.#resolved !== undefined) return this.#resolved
201
+ const url = this.#findUrl()
202
+ this.#anonKey ??= present(pageEnv().anonKey)
203
+ if (url !== undefined && this.#anonKey !== undefined) return (this.#resolved = { url, anonKey: this.#anonKey })
204
+ const missing: ClientValue[] = []
205
+ if (url === undefined) missing.push("url")
206
+ if (this.#anonKey === undefined) missing.push("anonKey")
207
+ throw missingClientValuesError(missing)
208
+ }
209
+
210
+ /** The address if it can be found now, else an empty string. Never throws. */
211
+ currentUrl(): string {
212
+ return this.#findUrl() ?? ""
213
+ }
214
+
215
+ /** The address as given or as the page has set it, kept once found. */
216
+ #findUrl(): string | undefined {
217
+ this.#url ??= httpUrl(pageEnv().url)
218
+ return this.#url
219
+ }
220
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The one rule for a setup fault: a client with no address or anon key.
3
+ *
4
+ * `MissingClientValuesError` lives in errors.ts with the rest of the error family, which the main
5
+ * entry re-exports whole; `rethrowSetupFault` is kept here because it is not public.
6
+ */
7
+
8
+ import { MissingClientValuesError } from "./errors.js"
9
+
10
+ export { MissingClientValuesError, type ClientValue } from "./errors.js"
11
+
12
+ /**
13
+ * Throw `e` again when it is a setup fault (a client with no address or anon key). Every catch-all
14
+ * on a request path calls this first, so none can turn that error into a result or a sign-out.
15
+ */
16
+ export function rethrowSetupFault(e: unknown): void {
17
+ if (e instanceof MissingClientValuesError) throw e
18
+ }