@supatype/client 0.9.0 → 0.9.2

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 (128) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +76 -68
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +82 -0
  5. package/dist/auth.d.ts +50 -6
  6. package/dist/auth.d.ts.map +1 -1
  7. package/dist/auth.js +117 -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 +10 -6
  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 +44 -0
  30. package/dist/latest-rows.d.ts.map +1 -0
  31. package/dist/latest-rows.js +58 -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 +18 -5
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +33 -16
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime.d.ts +22 -8
  50. package/dist/realtime.d.ts.map +1 -1
  51. package/dist/realtime.js +121 -41
  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 +202 -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 +5 -3
  66. package/dist/table-subscription.d.ts.map +1 -1
  67. package/dist/table-subscription.js +8 -5
  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 +64 -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 +121 -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 +63 -45
  83. package/src/latest-rows.ts +95 -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 +38 -19
  88. package/src/realtime.ts +146 -44
  89. package/src/runtime-env.ts +262 -0
  90. package/src/setup-fault.ts +18 -0
  91. package/src/storage.ts +26 -16
  92. package/src/table-subscription.ts +8 -6
  93. package/src/thrown-error.ts +31 -0
  94. package/src/types.ts +70 -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 +291 -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/examples-runtime-env.test.ts +135 -0
  102. package/tests/helpers/auth-unmount-binding.ts +63 -0
  103. package/tests/helpers/mock-websocket.ts +22 -0
  104. package/tests/helpers/oauth-binding.ts +4 -3
  105. package/tests/helpers/reactive-options-binding.ts +99 -0
  106. package/tests/helpers/stale-read-binding.ts +113 -0
  107. package/tests/helpers/thrown-error-binding.ts +127 -0
  108. package/tests/postgrest-error-codes.test.ts +4 -4
  109. package/tests/query.test.ts +39 -2
  110. package/tests/rate-limit-integration.test.ts +1 -1
  111. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  112. package/tests/realtime-refusal-error.test.ts +79 -0
  113. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  114. package/tests/realtime-session-auth.test.ts +0 -1
  115. package/tests/realtime-shared-channel.test.ts +9 -27
  116. package/tests/result-error-class.test.ts +107 -0
  117. package/tests/retry-policy.test.ts +1 -1
  118. package/tests/runtime-env-bundle.test.ts +121 -0
  119. package/tests/runtime-env-expo.test.ts +58 -0
  120. package/tests/runtime-env-page-script.test.ts +174 -0
  121. package/tests/runtime-env.test.ts +259 -0
  122. package/tests/server-bodies.test.ts +3 -3
  123. package/tests/subscribe-frame.test.ts +48 -0
  124. package/tests/support/browser.ts +28 -0
  125. package/tests/support/jwt.ts +5 -0
  126. package/tests/thrown-error.test.ts +59 -0
  127. package/tsconfig.json +2 -1
  128. package/tsconfig.tsbuildinfo +1 -1
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
 
@@ -17,6 +18,13 @@ type RealtimeCallback<TRow> = (payload: RealtimePayload<TRow>) => void
17
18
 
18
19
  export type ChannelStatus = "SUBSCRIBED" | "SUBSCRIBING" | "CLOSED" | "CHANNEL_ERROR" | "TIMED_OUT"
19
20
 
21
+ /**
22
+ * Told each status a channel reaches. `err` carries the server's reason with a CHANNEL_ERROR it
23
+ * refused, such as a join for a table that does not exist, and is undefined otherwise: the same
24
+ * `(status, err)` shape Supabase's client uses, so a callback taking only the status is unaffected.
25
+ */
26
+ export type ChannelStatusCallback = (status: ChannelStatus, err?: Error | undefined) => void
27
+
20
28
  interface ChannelSubscription<TRow> {
21
29
  on(
22
30
  event: "postgres_changes",
@@ -38,7 +46,7 @@ interface ChannelSubscription<TRow> {
38
46
  callback: (payload: Record<string, unknown>) => void,
39
47
  ): ChannelSubscription<TRow>
40
48
  /** Subscribe to the channel, opening the WebSocket if needed. */
41
- subscribe(callback?: ((status: ChannelStatus) => void) | undefined): ChannelSubscription<TRow>
49
+ subscribe(callback?: ChannelStatusCallback | undefined): ChannelSubscription<TRow>
42
50
  /** Unsubscribe and clean up. */
43
51
  unsubscribe(): void
44
52
  /** Send a broadcast event to the channel. */
@@ -102,6 +110,26 @@ function parseChannelName(name: string): { schema: string; table: string } {
102
110
  return { schema: "public", table: name }
103
111
  }
104
112
 
113
+ /**
114
+ * The schema and table a listener on channel `name` is for.
115
+ *
116
+ * The name is read as `schema:table` only when it supplies the table as well. A listener that
117
+ * names its table and no schema means `public`, as the docs say. 0.9.1 release test (RB4): the
118
+ * schema was taken from the name whatever the listener said, so the documented
119
+ * `channel("post:42").on(..., { table: "comment" })` joined `post.comment`, reported SUBSCRIBED
120
+ * and delivered nothing. The server's `resolveTarget` reads a frame the same way.
121
+ */
122
+ function listenerTarget(
123
+ name: string,
124
+ opts: { schema?: string | undefined; table?: string | undefined },
125
+ ): { schema: string; table: string } {
126
+ if (opts.table === undefined) {
127
+ const named = parseChannelName(name)
128
+ return { schema: opts.schema ?? named.schema, table: named.table }
129
+ }
130
+ return { schema: opts.schema ?? "public", table: opts.table }
131
+ }
132
+
105
133
  // ─── Server message types (subset matching @supatype/realtime) ───────────────
106
134
 
107
135
  interface ServerChangeMessage {
@@ -191,7 +219,7 @@ const SUBSCRIBED_TO = "subscribed to "
191
219
  // ─── Realtime client ─────────────────────────────────────────────────────────
192
220
 
193
221
  export class RealtimeClient {
194
- private readonly url: string
222
+ private readonly base: Deferred<string>
195
223
  private readonly getHeaders: HeadersProvider
196
224
  private ws: WebSocket | null = null
197
225
  private channels = new Map<string, ChannelState>()
@@ -223,12 +251,16 @@ export class RealtimeClient {
223
251
  * for the life of the page: on a table that is not anon-readable it reported SUBSCRIBED and then
224
252
  * delivered nothing, which is indistinguishable from a quiet table.
225
253
  */
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")
254
+ constructor(url: Deferred<string>, auth: Record<string, string> | HeadersProvider) {
255
+ this.base = url
229
256
  this.getHeaders = asHeadersProvider(auth)
230
257
  }
231
258
 
259
+ /** The socket's address, as ws(s) for an http(s) one. Read when connecting, not before. */
260
+ private get url(): string {
261
+ return settle(this.base).replace(/^http/, "ws")
262
+ }
263
+
232
264
  /** The token this socket should authenticate with, or undefined when there is none. */
233
265
  private async resolveToken(): Promise<string | undefined> {
234
266
  const token = bearerToken(await this.getHeaders())
@@ -316,16 +348,7 @@ export class RealtimeClient {
316
348
  state.joined = undefined
317
349
  state.joining = undefined
318
350
  state.joinRef = undefined
319
- this.forgetMembers(state)
320
- }
321
- }
322
-
323
- private forgetMembers(state: ChannelState): void {
324
- if (state.members.length === 0) return
325
- const leaves = state.members
326
- state.members = []
327
- for (const handle of state.handles) {
328
- for (const listener of handle.presenceListeners) listener({ joins: [], leaves })
351
+ forgetMembers(state)
329
352
  }
330
353
  }
331
354
 
@@ -349,18 +372,18 @@ export class RealtimeClient {
349
372
  state.handles.add(handle)
350
373
 
351
374
  const sub: ChannelSubscription<TRow> = {
352
- on(_event, opts, callback) {
353
- // Defaults read the channel name the way the server's fallback does. The schema used to
354
- // default to "public" regardless, and since the frame always carries a schema, a channel
355
- // named `app:orders` was registered against `public.orders`.
356
- const named = parseChannelName(name)
375
+ on: (_event, opts, callback) => {
376
+ // A channel named `app:orders` with no table on the listener is `app.orders`, the way the
377
+ // server's fallback reads it; a listener naming its table defaults to `public`.
357
378
  handle.pgListeners.push({
358
379
  event: opts.event,
359
- schema: opts.schema ?? named.schema,
360
- table: opts.table ?? named.table,
380
+ ...listenerTarget(name, opts),
361
381
  filter: opts.filter,
362
382
  callback: forCallerRows(callback),
363
383
  })
384
+ // A join already sent for broadcast or presence alone delivers no rows, and `subscribe()`
385
+ // will not send another, so the first row listener on it joins again here.
386
+ this.rejoinIfUnheard(state)
364
387
  return sub
365
388
  },
366
389
 
@@ -382,7 +405,7 @@ export class RealtimeClient {
382
405
  // join on its own and a caller can still call this afterwards just to watch the status.
383
406
  // A join already acknowledged will not be acknowledged again, so say so here or the new
384
407
  // callback waits for a SUBSCRIBED that is never coming.
385
- if (state.subscribed) callback?.("SUBSCRIBED")
408
+ if (state.subscribed && serves(state.joined, handle)) callback?.("SUBSCRIBED")
386
409
  this.ensureConnection()
387
410
  this.sendSubscribe(state)
388
411
  return sub
@@ -482,6 +505,9 @@ export class RealtimeClient {
482
505
  // One connect at a time: resolving the token is asynchronous, so two subscribes in the same
483
506
  // tick would otherwise each open a socket and the second would orphan the first.
484
507
  if (this.isLive() || this.attempt !== null) return
508
+ // Read here, synchronously, so a client with no address or anon key throws from the subscribe
509
+ // that asked for the socket rather than from a background attempt nobody is waiting on.
510
+ const url = this.url
485
511
 
486
512
  let attempt: Promise<void>
487
513
  const isCurrent = (): boolean => this.attempt === attempt
@@ -489,7 +515,7 @@ export class RealtimeClient {
489
515
  // is still the current one. Called directly, the path that already has a token reaches that
490
516
  // question with no await in front of it, compares against a handle nobody had stored yet, and
491
517
  // abandons itself.
492
- attempt = Promise.resolve().then(() => this.openSocket(isCurrent, token))
518
+ attempt = Promise.resolve().then(() => this.openSocket(url, isCurrent, token))
493
519
  this.attempt = attempt
494
520
  void attempt.finally(() => {
495
521
  // Only if it is still ours. An attempt abandoned mid-flight must not clear the handle of the
@@ -506,6 +532,7 @@ export class RealtimeClient {
506
532
  * meantime, by disconnect() or by reauthenticate(), does not install itself afterwards.
507
533
  */
508
534
  private async openSocket(
535
+ url: string,
509
536
  isCurrent: () => boolean,
510
537
  known?: string | undefined,
511
538
  ): Promise<void> {
@@ -526,7 +553,7 @@ export class RealtimeClient {
526
553
  if (!isCurrent()) return
527
554
 
528
555
  this.currentToken = token
529
- const wsUrl = token ? `${this.url}?token=${encodeURIComponent(token)}` : this.url
556
+ const wsUrl = token ? `${url}?token=${encodeURIComponent(token)}` : url
530
557
  const ws = new WebSocket(wsUrl)
531
558
  this.ws = ws
532
559
 
@@ -629,11 +656,17 @@ export class RealtimeClient {
629
656
  const affected = msg.channel === undefined ? [...this.channels.values()] : [this.answeredJoin(msg.channel, msg.ref)]
630
657
  for (const state of affected) {
631
658
  if (state === undefined) continue
659
+ if (msg.channel !== undefined && state.subscribed) {
660
+ refuseRejoin(state, new Error(msg.message))
661
+ continue
662
+ }
632
663
  // A refused join registered nothing on the server, so a channel not yet confirmed may
633
664
  // join again on this socket. Marked as sent, a retry after authenticating sent nothing.
634
665
  if (!state.subscribed) state.joinSent = false
635
666
  if (msg.ref !== undefined) state.joinRef = undefined
636
- notifyHandles(state, "CHANNEL_ERROR")
667
+ // The server's reason goes to the callback (N-FF5): "table public.notes does not exist"
668
+ // tells the developer what to fix, and a bare CHANNEL_ERROR did not.
669
+ notifyHandles(state, "CHANNEL_ERROR", new Error(msg.message))
637
670
  }
638
671
  }
639
672
 
@@ -707,23 +740,29 @@ export class RealtimeClient {
707
740
  }
708
741
 
709
742
  /**
710
- * Join `state` again when no listener left on it is for the join it holds.
743
+ * Join `state` again when the join it holds delivers rows to no listener left on it.
711
744
  *
712
745
  * Handles share one join, made for the oldest row listener. When that listener's handle left, the
713
746
  * join stayed registered for its table, and every other handle reported SUBSCRIBED and was sent
714
- * nothing. Joined again in place, without leaving first: the server replaces a channel's
715
- * subscription on a second join, where leaving would drop the presence this socket tracks there.
716
- * The server tells the new join who is present all over again, so the members known now leave.
747
+ * nothing. A join sent before any row listener asked for no rows, so a row listener added after it
748
+ * was never sent any either (0.9.2 release test, FF-1). Joined again in place, without leaving
749
+ * first: the server replaces a channel's subscription on a second join, where leaving would drop
750
+ * the presence this socket tracks there.
751
+ *
752
+ * An acknowledged join stays registered and serving until the server takes this one, and for good
753
+ * if it refuses it. So the handles it serves stay SUBSCRIBED and its members stay present, and
754
+ * only a handle it does not serve is told SUBSCRIBING. Every handle used to be, and a refused
755
+ * rejoin then left them all in CHANNEL_ERROR with broadcast still arriving (0.9.2 round 4, S-1).
717
756
  */
718
757
  private rejoinIfUnheard(state: ChannelState): void {
719
758
  const held = state.joining ?? state.joined
720
759
  if (!state.joinSent || held === undefined) return
721
760
  const listeners = pgListenersOf(state)
722
- if (listeners.length === 0 || listeners.some((listener) => sameJoin(listener, held))) return
723
- state.subscribed = false
761
+ if (listeners.length === 0) return
762
+ if (held.rows && listeners.some((listener) => sameJoin(listener, held))) return
724
763
  state.joinSent = false
725
- this.forgetMembers(state)
726
- notifyHandles(state, "SUBSCRIBING")
764
+ if (state.subscribed) notifyUnserved(state, "SUBSCRIBING")
765
+ else notifyHandles(state, "SUBSCRIBING")
727
766
  this.sendSubscribe(state)
728
767
  }
729
768
 
@@ -753,7 +792,7 @@ interface ChannelHandle {
753
792
  pgListeners: PgListener[]
754
793
  presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
755
794
  broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
756
- statusCallback: ((status: ChannelStatus) => void) | null
795
+ statusCallback: ChannelStatusCallback | null
757
796
  }
758
797
 
759
798
  /** One channel name's join on the socket, shared by every handle on that name. */
@@ -788,8 +827,16 @@ interface ChannelState {
788
827
  members: PresenceEntry[]
789
828
  }
790
829
 
791
- /** What a join registers on the server: the table whose changes it delivers, and which of them. */
792
- type JoinTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
830
+ /** The table, event and filter a row listener is for. */
831
+ type RowTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
832
+
833
+ /**
834
+ * What a join registers on the server: the table whose changes it delivers, and which of them.
835
+ * `rows` is whether it asked for them at all: a join for broadcast and presence alone is sent none.
836
+ */
837
+ interface JoinTarget extends RowTarget {
838
+ rows: boolean
839
+ }
793
840
 
794
841
  /**
795
842
  * What a join on `state` registers now: its oldest row listener's table, event and filter. With no
@@ -798,12 +845,14 @@ type JoinTarget = Pick<PgListener, "schema" | "table" | "event" | "filter">
798
845
  */
799
846
  function joinTargetOf(state: ChannelState): JoinTarget {
800
847
  const first = pgListenersOf(state)[0]
801
- if (first !== undefined) return { schema: first.schema, table: first.table, event: first.event, filter: first.filter }
802
- return { ...parseChannelName(state.name), event: "*", filter: undefined }
848
+ if (first !== undefined) {
849
+ return { schema: first.schema, table: first.table, event: first.event, filter: first.filter, rows: true }
850
+ }
851
+ return { ...parseChannelName(state.name), event: "*", filter: undefined, rows: false }
803
852
  }
804
853
 
805
854
  /** Whether a listener is for exactly what a join registered. */
806
- function sameJoin(listener: JoinTarget, join: JoinTarget): boolean {
855
+ function sameJoin(listener: RowTarget, join: RowTarget): boolean {
807
856
  return listener.schema === join.schema && listener.table === join.table &&
808
857
  listener.event === join.event && listener.filter === join.filter
809
858
  }
@@ -825,6 +874,9 @@ function pgListenersOf(state: ChannelState): PgListener[] {
825
874
  * `lobby-chat` carrying `table: "chat_message"` (which is what `useSubscription` exists to let you
826
875
  * write), registered against a table no change can match. The socket reported SUBSCRIBED and
827
876
  * delivered nothing, which is indistinguishable from a quiet table.
877
+ *
878
+ * `changes` says whether the join has a row listener. Only a row join has its table checked and is
879
+ * sent row changes: broadcast and presence on `room:x` were refused as a join for room.x (R2-RB2).
828
880
  */
829
881
  function subscribeFrame(channel: string, target: JoinTarget, ref: string): Record<string, unknown> {
830
882
  return {
@@ -833,6 +885,7 @@ function subscribeFrame(channel: string, target: JoinTarget, ref: string): Recor
833
885
  event: target.event,
834
886
  table: target.table,
835
887
  schema: target.schema,
888
+ changes: target.rows,
836
889
  filter: filterFrame(target.filter),
837
890
  ref,
838
891
  }
@@ -849,18 +902,67 @@ function filterFrame(filter: string | undefined): Record<string, string> | undef
849
902
  return Object.keys(parsed).length > 0 ? parsed : undefined
850
903
  }
851
904
 
852
- /** The server took the join `state` was waiting on: from now on its rows are that join's. */
905
+ /**
906
+ * The server took the join `state` was waiting on: from now on its rows are that join's.
907
+ *
908
+ * Over a join it had acknowledged, the server tells the new join who is present all over again,
909
+ * straight after this reply, so the members known now leave first. The handles the old join served
910
+ * were never told otherwise than SUBSCRIBED, so only the others are told it now.
911
+ */
853
912
  function acknowledgeJoin(state: ChannelState): void {
913
+ const replaced = state.subscribed
914
+ if (replaced) {
915
+ forgetMembers(state)
916
+ notifyUnserved(state, "SUBSCRIBED")
917
+ }
854
918
  state.subscribed = true
855
919
  if (state.joining !== undefined) state.joined = state.joining
856
920
  state.joining = undefined
857
921
  state.joinRef = undefined
858
- notifyHandles(state, "SUBSCRIBED")
922
+ if (!replaced) notifyHandles(state, "SUBSCRIBED")
923
+ }
924
+
925
+ /**
926
+ * The server refused a rejoin, so the acknowledged join it was to replace still stands, and stays
927
+ * the one this socket holds. Only a handle with a row listener it does not serve gets the refusal.
928
+ */
929
+ function refuseRejoin(state: ChannelState, refusal: Error): void {
930
+ state.joinSent = true
931
+ state.joining = undefined
932
+ state.joinRef = undefined
933
+ notifyUnserved(state, "CHANNEL_ERROR", refusal)
934
+ }
935
+
936
+ /**
937
+ * Whether `join` delivers rows to every row listener of `handle`, as `handleChange` routes them: by
938
+ * the join's table. Always, for a handle listening for none.
939
+ */
940
+ function serves(join: JoinTarget | undefined, handle: ChannelHandle): boolean {
941
+ return handle.pgListeners.every(
942
+ (listener) => join?.rows === true && listener.schema === join.schema && listener.table === join.table,
943
+ )
859
944
  }
860
945
 
861
946
  /** Tell each handle on a channel its status. */
862
- function notifyHandles(state: ChannelState, status: ChannelStatus): void {
863
- for (const handle of state.handles) handle.statusCallback?.(status)
947
+ function notifyHandles(state: ChannelState, status: ChannelStatus, err?: Error | undefined): void {
948
+ for (const handle of state.handles) handle.statusCallback?.(status, err)
949
+ }
950
+
951
+ /** Tell its status to each handle the join `state` holds does not serve. */
952
+ function notifyUnserved(state: ChannelState, status: ChannelStatus, err?: Error | undefined): void {
953
+ for (const handle of state.handles) {
954
+ if (!serves(state.joined, handle)) handle.statusCallback?.(status, err)
955
+ }
956
+ }
957
+
958
+ /** Every member this socket was told of leaves, as the next join is told them all again. */
959
+ function forgetMembers(state: ChannelState): void {
960
+ if (state.members.length === 0) return
961
+ const leaves = state.members
962
+ state.members = []
963
+ for (const handle of state.handles) {
964
+ for (const listener of handle.presenceListeners) listener({ joins: [], leaves })
965
+ }
864
966
  }
865
967
 
866
968
  /** `members` with one entry removed per leave: a user on two tabs is two entries and leaves twice. */
@@ -0,0 +1,262 @@
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
+ /**
71
+ * `url` without the "/" it may end in. Every path is joined on as `${url}/rest/v1/...`, and
72
+ * `https://api.example.com/` built `//rest/v1/...`, which the gateway refuses as a path with an
73
+ * empty part (0.9.1 release test RB2) and the server on native never routed to an API.
74
+ */
75
+ function withoutTrailingSlash(url: string): string {
76
+ return url.replace(/\/+$/, "")
77
+ }
78
+
79
+ /** An absolute http or https address, else undefined. */
80
+ function httpUrl(value: unknown): string | undefined {
81
+ const text = present(value)
82
+ if (text === undefined) return undefined
83
+ try {
84
+ const protocol = new URL(text).protocol
85
+ return protocol === "http:" || protocol === "https:" ? withoutTrailingSlash(text) : undefined
86
+ } catch {
87
+ return undefined
88
+ }
89
+ }
90
+
91
+ /** The page's `__SUPATYPE_ENV__` fields, each still unchecked; none when it is not an object. */
92
+ function pageEnv(): { url: unknown; anonKey: unknown; error: unknown } {
93
+ const env = objectOrEmpty(globalThis.__SUPATYPE_ENV__)
94
+ return { url: env["url"], anonKey: env["anonKey"], error: env["error"] }
95
+ }
96
+
97
+ /** What the error says, for the values still missing, by whichever name each is set under. */
98
+ interface MissingNames {
99
+ labels: string
100
+ buildNames: string
101
+ serverNames: string
102
+ pronoun: "it" | "them"
103
+ }
104
+
105
+ /** The build-time names and the fix that fills them, which both kinds of the error end with. */
106
+ function buildTimeFix(n: MissingNames): string {
107
+ return (
108
+ `Or set ${n.pronoun} at build time under the name your framework reads: ${n.buildNames}. Building ` +
109
+ `with \`supatype build -- <your build command>\` fills them from your deployment.`
110
+ )
111
+ }
112
+
113
+ /** The opening every page-side message without the global shares. */
114
+ function noPageGlobal(n: MissingNames): string {
115
+ return (
116
+ `Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
117
+ `window.__SUPATYPE_ENV__ by its first request.\n`
118
+ )
119
+ }
120
+
121
+ /** In a page: the page set no `__SUPATYPE_ENV__`, so the script that sets it comes first. */
122
+ function pageMessage(n: MissingNames): string {
123
+ return (
124
+ noPageGlobal(n) +
125
+ `When Supatype hosts the app, add <script src="/supatype-env.js" vite-ignore></script> to index.html before ` +
126
+ `the app's own script, and the server fills them in when the page loads. In a Next.js app, ` +
127
+ `export GET from @supatype/ssr/next in app/supatype-env.js/route.ts, load it in the root layout ` +
128
+ `with <Script src="/supatype-env.js" strategy="beforeInteractive" />, and set ${n.serverNames} ` +
129
+ `in the server's environment.\n${buildTimeFix(n)}`
130
+ )
131
+ }
132
+
133
+ /**
134
+ * Whether this runs in an Expo app. Expo's runtime sets `globalThis.expo`, on the web as on a phone.
135
+ * The app's own code reads the `EXPO_PUBLIC_` names, so which names were tried is not something the
136
+ * client can see; the global is the one sign it has.
137
+ */
138
+ function isExpoApp(): boolean {
139
+ const expo: unknown = Reflect.get(globalThis, "expo")
140
+ return typeof expo === "object" && expo !== null
141
+ }
142
+
143
+ /**
144
+ * In an Expo app: the page comes from `app/+html.tsx`, not an `index.html` (0.9.2 release test,
145
+ * N-S14), and a native build has no page at all.
146
+ */
147
+ function expoPageMessage(n: MissingNames): string {
148
+ return (
149
+ noPageGlobal(n) +
150
+ `On the web, when Supatype hosts the export, add <script src="/supatype-env.js" /> to the <head> of ` +
151
+ `app/+html.tsx (src/app/+html.tsx when the routes are in src/app), and the server fills them in when ` +
152
+ `the page loads; supatype init adds it to an Expo Router app. A native build has no page to read ` +
153
+ `them from, so it takes them at build time.\n${buildTimeFix(n)}`
154
+ )
155
+ }
156
+
157
+ /** On a server there is no page: its own variables are what to set. */
158
+ function serverMessage(n: MissingNames): string {
159
+ return (
160
+ `Supatype client has no ${n.labels}. It was given none, and it is running on a server, where ` +
161
+ `there is no page to read them from.\n` +
162
+ `Set ${n.serverNames} in the server's environment: createServerClient from @supatype/ssr reads ` +
163
+ `them when it is not given them, and @supatype/ssr/next serves them to the browser from ` +
164
+ `app/supatype-env.js/route.ts.\n${buildTimeFix(n)}`
165
+ )
166
+ }
167
+
168
+ /** The servers that answer `/supatype-env.js`, where its values or its reason come from. */
169
+ const SCRIPT_SERVERS =
170
+ "the Supatype server, or in a Next.js app the server running the route app/supatype-env.js/route.ts " +
171
+ "exports from @supatype/ssr/next"
172
+
173
+ /** In a page whose script set the server's reason in place of the values: that reason is the fix. */
174
+ function reasonMessage(n: MissingNames, script: string, reason: string): string {
175
+ return (
176
+ `Supatype client has no ${n.labels}. createClient was given none, and ${script} set no ${n.labels}, ` +
177
+ `giving the server's reason instead:\n${reason}\n` +
178
+ `Fix that in the environment of the server that answers it (${SCRIPT_SERVERS}), then reload the ` +
179
+ `page.\n${buildTimeFix(n)}`
180
+ )
181
+ }
182
+
183
+ /** In a page that has the script element and no global: the script is there, and did not run. */
184
+ function scriptDidNotRunMessage(n: MissingNames, script: string): string {
185
+ return (
186
+ `Supatype client has no ${n.labels}. createClient was given none, and the page loads ${script}, ` +
187
+ `but it had set no window.__SUPATYPE_ENV__ by the page's first request. The script did not run in ` +
188
+ `time: it was blocked, failed to load, ran after the app's own script, or came from a server too ` +
189
+ `old to serve it.\nOpen ${script} in the browser: it should set window.__SUPATYPE_ENV__. When it ` +
190
+ `does, load it before the app's own script, without async or defer. When it does not, update the ` +
191
+ `server that answers it (${SCRIPT_SERVERS}).\n${buildTimeFix(n)}`
192
+ )
193
+ }
194
+
195
+ /** In a page: the script's reason when it set one, else whether the page has the script at all. */
196
+ function pageFaultMessage(n: MissingNames): string {
197
+ const script = pageEnvScript()
198
+ const reason = present(pageEnv().error)
199
+ if (reason !== undefined) return reasonMessage(n, script ?? "/supatype-env.js", reason)
200
+ if (script !== undefined) return scriptDidNotRunMessage(n, script)
201
+ return isExpoApp() ? expoPageMessage(n) : pageMessage(n)
202
+ }
203
+
204
+ /** Each missing value's label and every name it is set under, as the error words them. */
205
+ function missingNames(missing: readonly ClientValue[]): MissingNames {
206
+ return {
207
+ labels: missing.map((key) => MISSING_VALUES[key].label).join(" and "),
208
+ buildNames: missing.flatMap((key) => FRONTEND_PREFIXES.map((prefix) => `${prefix}${MISSING_VALUES[key].name}`)).join(", "),
209
+ serverNames: missing.map((key) => MISSING_VALUES[key].name).join(" and "),
210
+ pronoun: missing.length > 1 ? "them" : "it",
211
+ }
212
+ }
213
+
214
+ /** The error for the values still missing, naming each one's every name and every fix. */
215
+ function missingClientValuesError(missing: readonly ClientValue[]): MissingClientValuesError {
216
+ const names = missingNames(missing)
217
+ // Read when the error is made, as the page is: a bundler cannot know which side it runs on.
218
+ const onServer = typeof window === "undefined"
219
+ return new MissingClientValuesError(onServer ? serverMessage(names) : pageFaultMessage(names), missing)
220
+ }
221
+
222
+ /**
223
+ * Where one client sends its requests, found when the first one is made.
224
+ *
225
+ * Each value is the one given, else the page's `__SUPATYPE_ENV__` as it is when a request asks.
226
+ * A value once found is kept, so every request after it goes to the same place, and the page is
227
+ * not read again once both are known.
228
+ */
229
+ export class ClientTarget {
230
+ #url: string | undefined
231
+ #anonKey: string | undefined
232
+ #resolved: ResolvedClientTarget | undefined
233
+
234
+ constructor(given: Pick<SupatypeClientConfig, "url" | "anonKey">) {
235
+ const url = present(given.url)
236
+ this.#url = url === undefined ? undefined : withoutTrailingSlash(url)
237
+ this.#anonKey = present(given.anonKey)
238
+ }
239
+
240
+ /** Both values, reading the page for any not found yet. Throws naming whatever is still missing. */
241
+ resolve(): ResolvedClientTarget {
242
+ if (this.#resolved !== undefined) return this.#resolved
243
+ const url = this.#findUrl()
244
+ this.#anonKey ??= present(pageEnv().anonKey)
245
+ if (url !== undefined && this.#anonKey !== undefined) return (this.#resolved = { url, anonKey: this.#anonKey })
246
+ const missing: ClientValue[] = []
247
+ if (url === undefined) missing.push("url")
248
+ if (this.#anonKey === undefined) missing.push("anonKey")
249
+ throw missingClientValuesError(missing)
250
+ }
251
+
252
+ /** The address if it can be found now, else an empty string. Never throws. */
253
+ currentUrl(): string {
254
+ return this.#findUrl() ?? ""
255
+ }
256
+
257
+ /** The address as given or as the page has set it, kept once found. */
258
+ #findUrl(): string | undefined {
259
+ this.#url ??= httpUrl(pageEnv().url)
260
+ return this.#url
261
+ }
262
+ }
@@ -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
+ }