@supatype/client 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/realtime.ts CHANGED
@@ -137,6 +137,10 @@ interface ServerSystemMessage {
137
137
  type: "system"
138
138
  status: "ok" | "error"
139
139
  message: string
140
+ /** The channel a refusal is about; an error without one is about the socket. */
141
+ channel?: string
142
+ /** The `ref` of the join this answers. A server that predates refs sends none. */
143
+ ref?: string
140
144
  }
141
145
 
142
146
  type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadcastMessage | ServerSystemMessage
@@ -172,6 +176,8 @@ const isSystemMessage: Guard<ServerSystemMessage> = isShape({
172
176
  type: isOneOf(["system"]),
173
177
  status: isOneOf(["ok", "error"]),
174
178
  message: isString,
179
+ channel: optional(isString),
180
+ ref: optional(isString),
175
181
  })
176
182
 
177
183
  /** A frame from the realtime service (packages/realtime/src/types.ts) in one of the four shapes. */
@@ -179,6 +185,9 @@ function isServerMessage(value: unknown): value is ServerMessage {
179
185
  return isChangeMessage(value) || isPresenceMessage(value) || isBroadcastMessage(value) || isSystemMessage(value)
180
186
  }
181
187
 
188
+ /** How the server's acknowledgement of a join begins; the channel name follows. */
189
+ const SUBSCRIBED_TO = "subscribed to "
190
+
182
191
  // ─── Realtime client ─────────────────────────────────────────────────────────
183
192
 
184
193
  export class RealtimeClient {
@@ -202,6 +211,8 @@ export class RealtimeClient {
202
211
  * the next one, so the two cannot disagree.
203
212
  */
204
213
  private attempt: Promise<void> | null = null
214
+ /** The last `ref` a join was sent with. Unique for the life of the client, across sockets. */
215
+ private lastRef = 0
205
216
 
206
217
  /**
207
218
  * `auth` is either a headers provider or a fixed set of headers: the same pair `QueryBuilder` and
@@ -258,11 +269,9 @@ export class RealtimeClient {
258
269
  this.ensureConnection(token)
259
270
  }
260
271
 
261
- /** Tell every channel's status callback the same thing. */
272
+ /** Tell every channel's status callbacks the same thing. */
262
273
  private notifyChannels(status: ChannelStatus): void {
263
- for (const state of this.channels.values()) {
264
- state.statusCallback?.(status)
265
- }
274
+ for (const state of this.channels.values()) notifyHandles(state, status)
266
275
  }
267
276
 
268
277
  /**
@@ -304,6 +313,9 @@ export class RealtimeClient {
304
313
  for (const state of this.channels.values()) {
305
314
  state.subscribed = false
306
315
  state.joinSent = false
316
+ state.joined = undefined
317
+ state.joining = undefined
318
+ state.joinRef = undefined
307
319
  this.forgetMembers(state)
308
320
  }
309
321
  }
@@ -312,11 +324,29 @@ export class RealtimeClient {
312
324
  if (state.members.length === 0) return
313
325
  const leaves = state.members
314
326
  state.members = []
315
- for (const listener of state.presenceListeners) listener({ joins: [], leaves })
327
+ for (const handle of state.handles) {
328
+ for (const listener of handle.presenceListeners) listener({ joins: [], leaves })
329
+ }
316
330
  }
317
331
 
332
+ /**
333
+ * A handle on the channel `name`, with listeners and a status callback of its own.
334
+ *
335
+ * Handles on one name share the join, since the server knows one subscription per channel per
336
+ * socket, and nothing else. They used to share everything: a second `subscribe()` replaced the
337
+ * first one's status callback, and the first `unsubscribe()` left the channel for both, so two
338
+ * `useSubscription` hooks with one channel name broke each other when either unmounted. The join
339
+ * is now left only when the last handle on the name unsubscribes.
340
+ */
318
341
  channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
319
342
  const state = this.getOrCreateChannel(name)
343
+ const handle: ChannelHandle = {
344
+ pgListeners: [],
345
+ presenceListeners: [],
346
+ broadcastListeners: new Map(),
347
+ statusCallback: null,
348
+ }
349
+ state.handles.add(handle)
320
350
 
321
351
  const sub: ChannelSubscription<TRow> = {
322
352
  on(_event, opts, callback) {
@@ -324,7 +354,7 @@ export class RealtimeClient {
324
354
  // default to "public" regardless, and since the frame always carries a schema, a channel
325
355
  // named `app:orders` was registered against `public.orders`.
326
356
  const named = parseChannelName(name)
327
- state.pgListeners.push({
357
+ handle.pgListeners.push({
328
358
  event: opts.event,
329
359
  schema: opts.schema ?? named.schema,
330
360
  table: opts.table ?? named.table,
@@ -335,20 +365,19 @@ export class RealtimeClient {
335
365
  },
336
366
 
337
367
  onPresence(callback) {
338
- state.presenceListeners.push(callback)
368
+ handle.presenceListeners.push(callback)
339
369
  return sub
340
370
  },
341
371
 
342
372
  onBroadcast(event, callback) {
343
- if (!state.broadcastListeners.has(event)) {
344
- state.broadcastListeners.set(event, [])
345
- }
346
- state.broadcastListeners.get(event)!.push(callback)
373
+ const listeners = handle.broadcastListeners.get(event) ?? []
374
+ listeners.push(callback)
375
+ handle.broadcastListeners.set(event, listeners)
347
376
  return sub
348
377
  },
349
378
 
350
379
  subscribe: (callback) => {
351
- state.statusCallback = callback ?? null
380
+ handle.statusCallback = callback ?? null
352
381
  // Joining twice is a no-op rather than a second frame, so `from(table).subscribe()` can
353
382
  // join on its own and a caller can still call this afterwards just to watch the status.
354
383
  // A join already acknowledged will not be acknowledged again, so say so here or the new
@@ -360,12 +389,11 @@ export class RealtimeClient {
360
389
  },
361
390
 
362
391
  unsubscribe: () => {
363
- this.sendUnsubscribe(state)
364
- this.channels.delete(name)
365
- // Close WebSocket if no channels left
366
- if (this.channels.size === 0) {
367
- this.disconnect()
368
- }
392
+ // Only the last handle on the name leaves the channel. A handle unsubscribing twice, or
393
+ // after `removeChannel` already removed its channel, has nothing left to leave.
394
+ if (!state.handles.delete(handle)) return
395
+ if (state.handles.size > 0) this.rejoinIfUnheard(state)
396
+ else if (this.channels.get(name) === state) this.removeChannel(name)
369
397
  },
370
398
 
371
399
  broadcast: (event, payload) => {
@@ -431,12 +459,12 @@ export class RealtimeClient {
431
459
  if (!state) {
432
460
  state = {
433
461
  name,
434
- pgListeners: [],
435
- presenceListeners: [],
436
- broadcastListeners: new Map(),
437
- statusCallback: null,
462
+ handles: new Set(),
438
463
  subscribed: false,
439
464
  joinSent: false,
465
+ joined: undefined,
466
+ joining: undefined,
467
+ joinRef: undefined,
440
468
  members: [],
441
469
  }
442
470
  this.channels.set(name, state)
@@ -570,24 +598,42 @@ export class RealtimeClient {
570
598
  }
571
599
 
572
600
  private handleSystem(msg: ServerSystemMessage): void {
573
- // When server confirms subscription
574
- if (msg.status === "ok" && msg.message.startsWith("subscribed to ")) {
575
- const channel = msg.message.replace("subscribed to ", "")
576
- const state = this.channels.get(channel)
577
- if (state) {
578
- state.subscribed = true
579
- state.statusCallback?.("SUBSCRIBED")
580
- }
601
+ if (msg.status === "ok" && msg.message.startsWith(SUBSCRIBED_TO)) {
602
+ const state = this.answeredJoin(msg.message.slice(SUBSCRIBED_TO.length), msg.ref)
603
+ if (state !== undefined) acknowledgeJoin(state)
581
604
  }
605
+ if (msg.status === "error") this.handleRefusal(msg)
606
+ }
582
607
 
583
- if (msg.status === "error") {
584
- // Find which channel this error relates to, broadcast to all as fallback
585
- for (const state of this.channels.values()) {
586
- // A refused join registered nothing on the server, so a channel not yet confirmed may
587
- // join again on this socket. Marked as sent, a retry after authenticating sent nothing.
588
- if (!state.subscribed) state.joinSent = false
589
- state.statusCallback?.("CHANNEL_ERROR")
590
- }
608
+ /**
609
+ * The channel whose pending join a reply answers, or undefined when it answers none.
610
+ *
611
+ * A reply carrying a ref answers the join sent with that ref and no other. Read by channel name
612
+ * alone, a join's reply settled whichever join on that name was pending when it arrived, so two
613
+ * joins close together (a rejoin, or a leave and a new join) each took the other's answer. A
614
+ * server that predates refs sends none, and its replies are still read by name.
615
+ */
616
+ private answeredJoin(channel: string, ref: string | undefined): ChannelState | undefined {
617
+ const state = this.channels.get(channel)
618
+ if (state === undefined || ref === undefined) return state
619
+ return state.joinRef === ref ? state : undefined
620
+ }
621
+
622
+ /**
623
+ * A refusal names its channel and fails that one alone: one bad filter used to put every healthy
624
+ * channel on the socket into CHANNEL_ERROR. An error naming none, from an older server or about
625
+ * the socket itself, still reaches them all. A named channel this client has since left, or one
626
+ * whose refused join it has since replaced, is told nothing.
627
+ */
628
+ private handleRefusal(msg: ServerSystemMessage): void {
629
+ const affected = msg.channel === undefined ? [...this.channels.values()] : [this.answeredJoin(msg.channel, msg.ref)]
630
+ for (const state of affected) {
631
+ if (state === undefined) continue
632
+ // A refused join registered nothing on the server, so a channel not yet confirmed may
633
+ // join again on this socket. Marked as sent, a retry after authenticating sent nothing.
634
+ if (!state.subscribed) state.joinSent = false
635
+ if (msg.ref !== undefined) state.joinRef = undefined
636
+ notifyHandles(state, "CHANNEL_ERROR")
591
637
  }
592
638
  }
593
639
 
@@ -602,15 +648,14 @@ export class RealtimeClient {
602
648
  const newRecord = coerceRecord(msg.payload.new, exact)
603
649
  const oldRecord = coerceRecord(msg.payload.old, exact)
604
650
 
605
- // The channel is subscribed to the first listener's table, which is what `sendSubscribe`
606
- // registers, so a change is that table's and goes only to listeners for it. Schema and table
607
- // come from there, not from splitting the channel name: a channel named for its purpose told
608
- // a `chat_message` listener its rows came from a table called `lobby-chat`. A listener for a
609
- // different table on the same channel is never served by it, rather than handed these rows
610
- // under its own table's name.
611
- const subscribed = state.pgListeners[0]
651
+ // The channel is subscribed to the table `sendSubscribe` registered, so a change is that
652
+ // table's and goes only to listeners for it. Schema and table come from there, not from
653
+ // splitting the channel name: a channel named for its purpose told a `chat_message` listener
654
+ // its rows came from a table called `lobby-chat`. A listener for a different table on the same
655
+ // channel is never served by it, rather than handed these rows under its own table's name.
656
+ const subscribed = state.joined
612
657
  if (!subscribed) return
613
- for (const listener of state.pgListeners) {
658
+ for (const listener of pgListenersOf(state)) {
614
659
  if (listener.schema !== subscribed.schema || listener.table !== subscribed.table) continue
615
660
  if (listener.event !== "*" && listener.event !== msg.event) continue
616
661
  listener.callback({
@@ -629,8 +674,10 @@ export class RealtimeClient {
629
674
  if (!state) return
630
675
 
631
676
  state.members = withoutLeaves([...state.members, ...msg.joins], msg.leaves)
632
- for (const listener of state.presenceListeners) {
633
- listener({ joins: msg.joins, leaves: msg.leaves })
677
+ for (const handle of state.handles) {
678
+ for (const listener of handle.presenceListeners) {
679
+ listener({ joins: msg.joins, leaves: msg.leaves })
680
+ }
634
681
  }
635
682
  }
636
683
 
@@ -638,9 +685,8 @@ export class RealtimeClient {
638
685
  const state = this.channels.get(msg.channel)
639
686
  if (!state) return
640
687
 
641
- const listeners = state.broadcastListeners.get(msg.event)
642
- if (listeners) {
643
- for (const listener of listeners) {
688
+ for (const handle of state.handles) {
689
+ for (const listener of handle.broadcastListeners.get(msg.event) ?? []) {
644
690
  listener(msg.payload)
645
691
  }
646
692
  }
@@ -651,36 +697,34 @@ export class RealtimeClient {
651
697
  if (state.joinSent) return
652
698
  state.joinSent = true
653
699
 
654
- // Build filter from the first pg listener (if any)
655
- const firstListener = state.pgListeners[0]
656
- const filter: Record<string, string> = {}
657
- if (firstListener?.filter) {
658
- // Parse PostgREST filter format "column=eq.value" into { column: "eq.value" }
659
- for (const part of firstListener.filter.split(",")) {
660
- const eqIdx = part.indexOf("=")
661
- if (eqIdx > 0) {
662
- filter[part.slice(0, eqIdx)] = part.slice(eqIdx + 1)
663
- }
664
- }
665
- }
700
+ const target = joinTargetOf(state)
701
+ state.joining = target
702
+ // A first join's rows are its own from the start. A join sent again on this socket replaces one
703
+ // the server delivers for until it acknowledges this one, so the old target stays until then.
704
+ state.joined ??= target
705
+ state.joinRef = String(++this.lastRef)
706
+ this.sendMessage(subscribeFrame(state.name, target, state.joinRef))
707
+ }
666
708
 
667
- // `table` and `schema` travel with the subscription, rather than being inferred from the
668
- // channel name at the other end.
669
- //
670
- // They were resolved here and then dropped, and the server falls back to reading the channel
671
- // name as `schema:table`. So a subscription worked only when the channel happened to be named
672
- // after its table, as `from(table).subscribe()` names its own. Anything else -- a channel
673
- // called `lobby-chat` carrying `table: "chat_message"`, which is what `useSubscription` exists
674
- // to let you write -- registered against a table no change can match. The socket reported
675
- // SUBSCRIBED and delivered nothing, which is indistinguishable from a quiet table.
676
- this.sendMessage({
677
- type: "subscribe",
678
- channel: state.name,
679
- event: firstListener?.event ?? "*",
680
- ...(firstListener?.table !== undefined && { table: firstListener.table }),
681
- ...(firstListener?.schema !== undefined && { schema: firstListener.schema }),
682
- filter: Object.keys(filter).length > 0 ? filter : undefined,
683
- })
709
+ /**
710
+ * Join `state` again when no listener left on it is for the join it holds.
711
+ *
712
+ * Handles share one join, made for the oldest row listener. When that listener's handle left, the
713
+ * 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.
717
+ */
718
+ private rejoinIfUnheard(state: ChannelState): void {
719
+ const held = state.joining ?? state.joined
720
+ if (!state.joinSent || held === undefined) return
721
+ const listeners = pgListenersOf(state)
722
+ if (listeners.length === 0 || listeners.some((listener) => sameJoin(listener, held))) return
723
+ state.subscribed = false
724
+ state.joinSent = false
725
+ this.forgetMembers(state)
726
+ notifyHandles(state, "SUBSCRIBING")
727
+ this.sendSubscribe(state)
684
728
  }
685
729
 
686
730
  private sendUnsubscribe(state: ChannelState): void {
@@ -704,12 +748,19 @@ interface PgListener {
704
748
  callback: RealtimeCallback<Record<string, unknown>>
705
749
  }
706
750
 
707
- interface ChannelState {
708
- name: string
751
+ /** What one `channel(name)` call registered: its own listeners and status callback. */
752
+ interface ChannelHandle {
709
753
  pgListeners: PgListener[]
710
754
  presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
711
755
  broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
712
756
  statusCallback: ((status: ChannelStatus) => void) | null
757
+ }
758
+
759
+ /** One channel name's join on the socket, shared by every handle on that name. */
760
+ interface ChannelState {
761
+ name: string
762
+ /** The handles on this name, oldest first. The channel is left when the last one unsubscribes. */
763
+ handles: Set<ChannelHandle>
713
764
  /** The server acknowledged the join on the current socket. */
714
765
  subscribed: boolean
715
766
  /**
@@ -719,10 +770,99 @@ interface ChannelState {
719
770
  * used to send a second frame.
720
771
  */
721
772
  joinSent: boolean
773
+ /**
774
+ * The table the join on the current socket registered, from the row listener first when it was
775
+ * sent, else from the channel name. It, not whichever listener is first now, is what an incoming
776
+ * row belongs to: it stays registered while any listener is for it, and a join sent again in its
777
+ * place takes over only once the server acknowledges it. Undefined before any join on the socket.
778
+ */
779
+ joined: JoinTarget | undefined
780
+ /** The join sent on the current socket and not yet acknowledged. */
781
+ joining: JoinTarget | undefined
782
+ /**
783
+ * The `ref` the join awaiting its reply was sent with, and the only reply that may settle it. A
784
+ * reply carrying any other ref answers a join since replaced or left, and is not this one's.
785
+ */
786
+ joinRef: string | undefined
722
787
  /** Who the current socket has said is tracked on this channel, one entry per tracking socket. */
723
788
  members: PresenceEntry[]
724
789
  }
725
790
 
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">
793
+
794
+ /**
795
+ * What a join on `state` registers now: its oldest row listener's table, event and filter. With no
796
+ * row listener, the table the channel name gives, read as the server's fallback reads it: the one
797
+ * the server would register for a join that named none.
798
+ */
799
+ function joinTargetOf(state: ChannelState): JoinTarget {
800
+ 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 }
803
+ }
804
+
805
+ /** Whether a listener is for exactly what a join registered. */
806
+ function sameJoin(listener: JoinTarget, join: JoinTarget): boolean {
807
+ return listener.schema === join.schema && listener.table === join.table &&
808
+ listener.event === join.event && listener.filter === join.filter
809
+ }
810
+
811
+ /** Every handle's row listeners, oldest handle first: the first of them is what the join registers. */
812
+ function pgListenersOf(state: ChannelState): PgListener[] {
813
+ return [...state.handles].flatMap((handle) => handle.pgListeners)
814
+ }
815
+
816
+ /**
817
+ * The frame that joins `channel` for `target`, carrying `ref` for the server to echo on its reply.
818
+ *
819
+ * `table` and `schema` travel with the subscription, rather than being inferred from the channel
820
+ * name at the other end.
821
+ *
822
+ * They were resolved here and then dropped, and the server falls back to reading the channel name
823
+ * as `schema:table`. So a subscription worked only when the channel happened to be named after its
824
+ * table, as `from(table).subscribe()` names its own. Anything else, such as a channel called
825
+ * `lobby-chat` carrying `table: "chat_message"` (which is what `useSubscription` exists to let you
826
+ * write), registered against a table no change can match. The socket reported SUBSCRIBED and
827
+ * delivered nothing, which is indistinguishable from a quiet table.
828
+ */
829
+ function subscribeFrame(channel: string, target: JoinTarget, ref: string): Record<string, unknown> {
830
+ return {
831
+ type: "subscribe",
832
+ channel,
833
+ event: target.event,
834
+ table: target.table,
835
+ schema: target.schema,
836
+ filter: filterFrame(target.filter),
837
+ ref,
838
+ }
839
+ }
840
+
841
+ /** A PostgREST filter, `column=eq.value,...`, as the subscribe frame carries it, or undefined for none. */
842
+ function filterFrame(filter: string | undefined): Record<string, string> | undefined {
843
+ if (!filter) return undefined
844
+ const parsed: Record<string, string> = {}
845
+ for (const part of filter.split(",")) {
846
+ const eqIdx = part.indexOf("=")
847
+ if (eqIdx > 0) parsed[part.slice(0, eqIdx)] = part.slice(eqIdx + 1)
848
+ }
849
+ return Object.keys(parsed).length > 0 ? parsed : undefined
850
+ }
851
+
852
+ /** The server took the join `state` was waiting on: from now on its rows are that join's. */
853
+ function acknowledgeJoin(state: ChannelState): void {
854
+ state.subscribed = true
855
+ if (state.joining !== undefined) state.joined = state.joining
856
+ state.joining = undefined
857
+ state.joinRef = undefined
858
+ notifyHandles(state, "SUBSCRIBED")
859
+ }
860
+
861
+ /** 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)
864
+ }
865
+
726
866
  /** `members` with one entry removed per leave: a user on two tabs is two entries and leaves twice. */
727
867
  function withoutLeaves(members: PresenceEntry[], leaves: PresenceEntry[]): PresenceEntry[] {
728
868
  const kept = [...members]
package/src/storage.ts CHANGED
@@ -14,6 +14,14 @@ import {
14
14
  type Guard,
15
15
  } from "./json.js"
16
16
 
17
+ /**
18
+ * An object path as it goes into a URL: each segment encoded, the `/` between them kept, since the
19
+ * server matches the path on it. Interpolated as given, a name holding `?` or `#` cut the URL short.
20
+ */
21
+ function encodeObjectPath(path: string): string {
22
+ return path.split("/").map(encodeURIComponent).join("/")
23
+ }
24
+
17
25
  /**
18
26
  * An object as `list()` answers it, field for field (packages/storage/src/routes/objects.ts,
19
27
  * `listedObject`), named relative to the folder listed. A null is sent as null, never left out.
@@ -290,7 +298,7 @@ export class BucketClient {
290
298
  if (options?.upsert === true) {
291
299
  headers["x-upsert"] = "true"
292
300
  }
293
- const res = await this.send(`${this.url}/object/${this.bucket}/${path}`, {
301
+ const res = await this.send(`${this.url}/object/${this.bucket}/${encodeObjectPath(path)}`, {
294
302
  method: "POST",
295
303
  headers,
296
304
  body: file,
@@ -342,7 +350,7 @@ export class BucketClient {
342
350
  path: string,
343
351
  expiresIn: number,
344
352
  ): Promise<{ data: { signedUrl: string } | null; error: SupatypeError | null }> {
345
- const res = await this.send(`${this.url}/object/sign/${this.bucket}/${path}`, {
353
+ const res = await this.send(`${this.url}/object/sign/${this.bucket}/${encodeObjectPath(path)}`, {
346
354
  method: "POST",
347
355
  // Signing creates nothing on the server, so a second request is harmless.
348
356
  idempotent: true,
@@ -419,7 +427,7 @@ export class BucketClient {
419
427
  path: string,
420
428
  transform?: TransformOptions | undefined,
421
429
  ): string {
422
- let url = `${this.url}/object/${access}/${this.bucket}/${path}`
430
+ let url = `${this.url}/object/${access}/${this.bucket}/${encodeObjectPath(path)}`
423
431
  if (transform) {
424
432
  const params = new URLSearchParams()
425
433
  if (transform.width !== undefined) params.set("width", String(transform.width))
package/src/types.ts CHANGED
@@ -427,6 +427,20 @@ export interface SupatypeClientConfig {
427
427
  auth?: {
428
428
  /** Persist session across page reloads (browser only). Default: true */
429
429
  persistSession?: boolean | undefined
430
+ /**
431
+ * Refresh the access token on a timer shortly before it expires, and at once when the client
432
+ * starts with an expired one. Default: true. Off, a refresh happens only when a request finds
433
+ * the token expired: what a client built for one server request wants (`@supatype/ssr`).
434
+ */
435
+ autoRefreshToken?: boolean | undefined
436
+ /**
437
+ * Refresh an expired access token when a request or `auth.getSession()` finds it. Default: true.
438
+ * Off, the expired token is sent as it is and the server refuses it, and the session is left as it
439
+ * was. For a client whose refreshed session could not be stored anywhere: a refresh spends the
440
+ * refresh token, so whoever holds it (the browser, for `@supatype/ssr` in a Server Component)
441
+ * would be refused on its own next refresh. `auth.refreshSession()` still refreshes when called.
442
+ */
443
+ refreshExpiredToken?: boolean | undefined
430
444
  /** localStorage key to use for session storage. Default: "supatype.auth.session" */
431
445
  storageKey?: string | undefined
432
446
  /**
@@ -719,3 +719,68 @@ describe("email links carry the caller's redirect", () => {
719
719
  expect(url.searchParams.get("redirect_to")).toBe("myapp://auth/callback")
720
720
  })
721
721
  })
722
+
723
+ // ─── autoRefreshToken ────────────────────────────────────────────────────────
724
+
725
+ describe("AuthClient autoRefreshToken", () => {
726
+ /** A session whose access token expired a minute ago. */
727
+ const expired = {
728
+ accessToken: "expired-token",
729
+ refreshToken: "refresh-token-abc",
730
+ tokenType: "bearer",
731
+ expiresIn: 3600,
732
+ expiresAt: Math.floor(Date.now() / 1000) - 60,
733
+ user: { id: "user-1", appMetadata: {}, userMetadata: {}, createdAt: "", updatedAt: "" },
734
+ }
735
+
736
+ it("schedules a refresh timer by default", () => {
737
+ vi.useFakeTimers()
738
+ try {
739
+ vi.stubGlobal("fetch", mockFetch(TOKEN_RESPONSE))
740
+ new AuthClient(SUPATYPE_URL, HEADERS, { initialSession: { ...expired, expiresAt: expired.expiresAt + 7200 } })
741
+ expect(vi.getTimerCount()).toBe(1)
742
+ } finally {
743
+ vi.useRealTimers()
744
+ vi.unstubAllGlobals()
745
+ }
746
+ })
747
+
748
+ it("schedules nothing and refreshes nothing on its own when off", async () => {
749
+ vi.useFakeTimers()
750
+ const fetchSpy = mockFetch(TOKEN_RESPONSE)
751
+ vi.stubGlobal("fetch", fetchSpy)
752
+ try {
753
+ const client = new AuthClient(SUPATYPE_URL, HEADERS, { initialSession: expired, autoRefreshToken: false })
754
+ await vi.runAllTimersAsync()
755
+ expect(vi.getTimerCount()).toBe(0)
756
+ expect(fetchSpy).not.toHaveBeenCalled()
757
+
758
+ // A caller that needs a valid token still gets one, and refreshing schedules nothing either.
759
+ await client.ensureValidSession()
760
+ expect(client.currentAccessToken).toBe("access-token-123")
761
+ expect(vi.getTimerCount()).toBe(0)
762
+ } finally {
763
+ vi.useRealTimers()
764
+ vi.unstubAllGlobals()
765
+ }
766
+ })
767
+
768
+ it("leaves an expired session as it is when refreshExpiredToken is off", async () => {
769
+ const fetchSpy = mockFetch(TOKEN_RESPONSE)
770
+ vi.stubGlobal("fetch", fetchSpy)
771
+ try {
772
+ const client = new AuthClient(SUPATYPE_URL, HEADERS, {
773
+ initialSession: expired,
774
+ autoRefreshToken: false,
775
+ refreshExpiredToken: false,
776
+ })
777
+ await client.ensureValidSession()
778
+ const { data } = await client.getSession()
779
+ expect(fetchSpy).not.toHaveBeenCalled()
780
+ expect(client.currentAccessToken).toBe("expired-token")
781
+ expect(data.session?.refreshToken).toBe("refresh-token-abc")
782
+ } finally {
783
+ vi.unstubAllGlobals()
784
+ }
785
+ })
786
+ })
@@ -20,6 +20,8 @@ export interface SocketSwapHarness {
20
20
  realtime: RealtimeClient
21
21
  /** Every socket opened so far, oldest first. */
22
22
  sockets: MockWebSocketInstance[]
23
+ /** The newest socket. Fails the test when none has been opened. */
24
+ socket(): MockWebSocketInstance
23
25
  /** Let queued connects and opens run. */
24
26
  settle(): Promise<void>
25
27
  /** The server acknowledges every join sent on the newest socket. */
@@ -50,6 +52,7 @@ export function createSocketSwapHarness(): SocketSwapHarness {
50
52
  return {
51
53
  realtime,
52
54
  sockets: mock.instances,
55
+ socket: () => newestOf(mock.instances),
53
56
  settle,
54
57
  ackJoins: () => {
55
58
  for (const channel of subscribedChannels(newestOf(mock.instances))) reply("ok", `subscribed to ${channel}`)