@supatype/client 0.3.0 → 0.3.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 (44) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +25 -22
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/dist/auth.d.ts +1 -1
  5. package/dist/auth.d.ts.map +1 -1
  6. package/dist/identity.d.ts +29 -0
  7. package/dist/identity.d.ts.map +1 -0
  8. package/dist/identity.js +30 -0
  9. package/dist/identity.js.map +1 -0
  10. package/dist/index.d.ts +15 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +25 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/query-cache.d.ts +1 -1
  15. package/dist/query-cache.d.ts.map +1 -1
  16. package/dist/query-cache.js +2 -8
  17. package/dist/query-cache.js.map +1 -1
  18. package/dist/query.d.ts +13 -1
  19. package/dist/query.d.ts.map +1 -1
  20. package/dist/query.js +18 -2
  21. package/dist/query.js.map +1 -1
  22. package/dist/realtime.d.ts +61 -3
  23. package/dist/realtime.d.ts.map +1 -1
  24. package/dist/realtime.js +162 -22
  25. package/dist/realtime.js.map +1 -1
  26. package/dist/storage.d.ts +12 -0
  27. package/dist/storage.d.ts.map +1 -1
  28. package/dist/storage.js +17 -1
  29. package/dist/storage.js.map +1 -1
  30. package/package.json +1 -1
  31. package/src/auth.ts +1 -1
  32. package/src/identity.ts +43 -0
  33. package/src/index.ts +42 -1
  34. package/src/query-cache.ts +3 -10
  35. package/src/query.ts +18 -2
  36. package/src/realtime.ts +166 -25
  37. package/src/storage.ts +17 -1
  38. package/tests/helpers/mock-websocket.ts +70 -0
  39. package/tests/identity-change.test.ts +120 -0
  40. package/tests/realtime-multi-tenant-integration.test.ts +5 -50
  41. package/tests/realtime-session-auth.test.ts +177 -0
  42. package/tests/signed-url-absolute.test.ts +84 -0
  43. package/tests/subscribe-frame.test.ts +102 -0
  44. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,43 @@
1
+ import type { AuthListener } from "./auth.js"
2
+
3
+ /**
4
+ * The part of `AuthClient` this needs.
5
+ *
6
+ * Structural rather than the class itself so a caller, and a test, can supply anything that emits
7
+ * auth changes without constructing a whole client. The callback is `AuthListener`, the same type
8
+ * the real `onAuthStateChange` takes, so the stand-in cannot drift from what it stands in for.
9
+ */
10
+ export interface IdentitySource {
11
+ onAuthStateChange(callback: AuthListener): {
12
+ data: { subscription: { unsubscribe(): void } }
13
+ }
14
+ }
15
+
16
+ /**
17
+ * Call `onChange` whenever the signed-in identity changes, and not otherwise.
18
+ *
19
+ * `onAuthStateChange` also fires once at registration and again on every token refresh. A data hook
20
+ * subscribed to it raw would refetch on a timer for as long as the page stayed open, and would
21
+ * refetch once more immediately after the fetch it already makes on mount. This narrows the stream
22
+ * to the only transition that changes what a query is allowed to read: a different user, or none.
23
+ *
24
+ * Returns the unsubscribe function, so a caller can hand it straight to its own teardown hook.
25
+ */
26
+ export function onIdentityChange(auth: IdentitySource, onChange: () => void): () => void {
27
+ // `undefined` until the registration emission has established the baseline, so that emission is
28
+ // not itself read as a change.
29
+ let known: string | null | undefined
30
+ const { data } = auth.onAuthStateChange((_event, session) => {
31
+ const userId = session?.user.id ?? null
32
+ if (known === undefined) {
33
+ known = userId
34
+ return
35
+ }
36
+ if (userId === known) return
37
+ known = userId
38
+ onChange()
39
+ })
40
+ return () => {
41
+ data.subscription.unsubscribe()
42
+ }
43
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AuthClient } from "./auth.js"
2
+ import { onIdentityChange } from "./identity.js"
2
3
  import { PreviewCredential } from "./preview.js"
3
4
  import { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
4
5
  import { defaultQueryCache, type QueryCache } from "./query-cache.js"
@@ -49,8 +50,24 @@ export {
49
50
  PKCE_METHOD_S256,
50
51
  } from "./pkce.js"
51
52
  export { DRAFT_SCHEMA } from "./types.js"
53
+
54
+ /**
55
+ * A client whose database type the holder does not know.
56
+ *
57
+ * What every framework binding's context, provider or injection key is typed at. A context is one
58
+ * value shared by many consumers, so it cannot be generic, and at the `AugmentedDatabase` default
59
+ * it rejected `createClient<Database>(...)`, the client every real project builds. `AnyDatabase` is
60
+ * the constraint every generated database satisfies, so the typed client goes in unchanged and each
61
+ * binding's `useSupatype<TDatabase>()` narrows it on the way back out.
62
+ *
63
+ * Named here rather than spelled out in four packages so the decision has one home. It is also not
64
+ * `any`: that widening is one TypeScript already allows, so `any` bought nothing and cost every
65
+ * consumer its checking.
66
+ */
67
+ export type AnyClient = SupatypeClient<AnyDatabase>
52
68
  export type { QueryCacheOptions, CacheStatus } from "./query-cache.js"
53
69
  export { AuthClient } from "./auth.js"
70
+ export { onIdentityChange, type IdentitySource } from "./identity.js"
54
71
  export { QueryBuilder, MutationBuilder, type HeadersProvider } from "./query.js"
55
72
  export { QueryCache, defaultQueryCache } from "./query-cache.js"
56
73
  export { StorageClient, BucketClient } from "./storage.js"
@@ -504,7 +521,6 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
504
521
  cookiePrefix: config.auth?.cookiePrefix,
505
522
  storage: config.auth?.storage,
506
523
  })
507
- const realtime = new RealtimeClient(`${config.url}/realtime/v1`, baseHeaders)
508
524
  const queryCache = config.queryCache ?? defaultQueryCache
509
525
 
510
526
  const getAuthHeaders = async (): Promise<Record<string, string>> => {
@@ -547,12 +563,37 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
547
563
  // because an anon key carries no `sub` and the proxy requires one.
548
564
  const storage = new StorageClient(`${config.url}/storage/v1`, getAuthHeaders)
549
565
 
566
+ // The same provider the other sub-clients get, not `baseHeaders`.
567
+ //
568
+ // `baseHeaders` is built once and never mutated, so handing it over pinned every socket to the
569
+ // anon key for the life of the page. Realtime enforces RLS, so on a table that is not
570
+ // anon-readable the socket reported SUBSCRIBED and delivered nothing, which is exactly the
571
+ // failure the storage note above describes.
572
+ const realtime = new RealtimeClient(`${config.url}/realtime/v1`, getAuthHeaders)
573
+
550
574
  const onUnauthorized = config.serviceRoleKey
551
575
  ? undefined
552
576
  : (): Promise<void> => auth.ensureValidSession()
553
577
 
554
578
  const functions = new FunctionsClient(config.url, getAuthHeaders, doFetch, onUnauthorized)
555
579
 
580
+ // Signing in has to reach an already-open socket.
581
+ //
582
+ // Every binding subscribes when its component mounts, which is before the user has signed in, so
583
+ // the socket that matters is always one opened while signed out. Resolving the token per
584
+ // connection is not enough on its own; something has to tell the connection it is now stale.
585
+ //
586
+ // `onIdentityChange`, not `onAuthStateChange`: a refreshed token is a different string for the
587
+ // same person, and reconnecting on it would close and re-open the socket once an hour for the
588
+ // life of the tab, losing every change committed in the gap. That is the silent miss this whole
589
+ // change exists to remove, so it must not be reintroduced by the fix.
590
+ //
591
+ // The subscription is never torn down. The listener is held by `auth` and closes over `realtime`,
592
+ // both owned by this client, so the cycle is collected whole when the client is dropped.
593
+ onIdentityChange(auth, () => {
594
+ void realtime.reauthenticate()
595
+ })
596
+
556
597
  return {
557
598
  url: config.url,
558
599
  serviceRoleKey: config.serviceRoleKey,
@@ -1,10 +1,11 @@
1
1
  import type { QueryResult } from "./types.js"
2
2
  import { sha256Hex } from "./sha256-hex.js"
3
+ import { bearerToken } from "./query.js"
3
4
 
4
5
  export interface QueryCacheOptions {
5
6
  /** Client-side TTL in milliseconds. */
6
7
  ttl: number
7
- /** When true, send `X-Supatype-Cache: max-age=N` so the server caches the response too. */
8
+ /** When true, send `X-Supatype-Cache: max-age=N` for server-side Valkey caching. */
8
9
  server?: boolean | undefined
9
10
  /** When true (with server), request shared public cache scope when allowed for the table. */
10
11
  public?: boolean | undefined
@@ -26,14 +27,6 @@ interface JwtPayload {
26
27
  role?: string
27
28
  }
28
29
 
29
- function bearerOrApikey(headers: Record<string, string>): string {
30
- const auth = headers["Authorization"] ?? headers["authorization"] ?? ""
31
- if (auth.startsWith("Bearer ")) {
32
- return auth.slice("Bearer ".length)
33
- }
34
- return headers["apikey"] ?? headers["Apikey"] ?? ""
35
- }
36
-
37
30
  function parseJwtPayload(token: string): JwtPayload | null {
38
31
  const parts = token.split(".")
39
32
  if (parts.length !== 3) return null
@@ -51,7 +44,7 @@ export function identityFingerprint(
51
44
  scope: "public" | "user",
52
45
  ): string {
53
46
  if (scope === "public") return "global"
54
- const token = bearerOrApikey(headers)
47
+ const token = bearerToken(headers)
55
48
  if (!token) return "anon"
56
49
  const claims = parseJwtPayload(token)
57
50
  const role = claims?.role?.trim() || "authenticated"
package/src/query.ts CHANGED
@@ -64,13 +64,29 @@ function withMeta<T>(
64
64
  /** Resolves auth (and other) headers at request time so token refresh can run first. */
65
65
  export type HeadersProvider = () => Promise<Record<string, string>>
66
66
 
67
- function asHeadersProvider(
67
+ export function asHeadersProvider(
68
68
  headers: Record<string, string> | HeadersProvider,
69
69
  ): HeadersProvider {
70
70
  if (typeof headers === "function") return headers
71
71
  return () => Promise.resolve(headers)
72
72
  }
73
73
 
74
+ /**
75
+ * The caller's own token out of a header set: the session's bearer, else the apikey.
76
+ *
77
+ * One home for a rule three places had implemented separately. The realtime socket had the
78
+ * precedence the other way round, which is how it came to authenticate as anon on every
79
+ * connection: `apikey` is always set, so it never reached the Authorization header.
80
+ *
81
+ * Header names are matched in both casings because `config.headers` is caller-supplied and
82
+ * lowercase is just as valid over the wire.
83
+ */
84
+ export function bearerToken(headers: Record<string, string>): string {
85
+ const authorization = headers["Authorization"] ?? headers["authorization"] ?? ""
86
+ if (authorization.startsWith("Bearer ")) return authorization.slice("Bearer ".length)
87
+ return headers["apikey"] ?? headers["Apikey"] ?? ""
88
+ }
89
+
74
90
  async function fetchWithOptional401Retry(
75
91
  url: string,
76
92
  init: RequestInit,
@@ -133,7 +149,7 @@ export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
133
149
  }
134
150
  }
135
151
 
136
- /** Enable GET caching. Use `{ server: true }` to cache the response on the server too. */
152
+ /** Enable GET caching. Use `{ server: true }` for Valkey-backed server cache. */
137
153
  cache(options: QueryCacheOptions): this {
138
154
  this.cacheOptions = options
139
155
  return this
package/src/realtime.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { asHeadersProvider, bearerToken, type HeadersProvider } from "./query.js"
2
+
1
3
  export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
2
4
 
3
5
  export interface RealtimePayload<TRow> {
@@ -86,18 +88,100 @@ type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadca
86
88
 
87
89
  export class RealtimeClient {
88
90
  private readonly url: string
89
- private readonly headers: Record<string, string>
91
+ private readonly getHeaders: HeadersProvider
90
92
  private ws: WebSocket | null = null
91
93
  private channels = new Map<string, ChannelState>()
92
94
  private reconnectTimer: ReturnType<typeof setTimeout> | null = null
93
95
  private reconnectAttempts = 0
94
96
  private maxReconnectAttempts = 10
95
97
  private baseReconnectDelay = 1000
96
-
97
- constructor(url: string, headers: Record<string, string>) {
98
+ /** The token the live socket was opened with, so an auth change can tell whether it still holds. */
99
+ private currentToken: string | undefined
100
+ /**
101
+ * The connect in flight, used as its own identity.
102
+ *
103
+ * A counter was tried first and produced a socket that never came back: abandoning an attempt
104
+ * bumped the counter but left this field set, so the replacement connect returned at the
105
+ * one-at-a-time guard, and the abandoned attempt then bailed on the counter. Nothing was
106
+ * connected and nothing was scheduled. Clearing this field both abandons an attempt and unblocks
107
+ * the next one, so the two cannot disagree.
108
+ */
109
+ private attempt: Promise<void> | null = null
110
+
111
+ /**
112
+ * `auth` is either a headers provider or a fixed set of headers: the same pair `QueryBuilder` and
113
+ * `MutationBuilder` accept, normalised by the same helper.
114
+ *
115
+ * The provider is what `createClient` passes, and it is why this takes two shapes. A fixed set of
116
+ * headers is read once at construction, so a socket opened before anybody signed in stayed anon
117
+ * for the life of the page: on a table that is not anon-readable it reported SUBSCRIBED and then
118
+ * delivered nothing, which is indistinguishable from a quiet table.
119
+ */
120
+ constructor(url: string, auth: Record<string, string> | HeadersProvider) {
98
121
  // Convert http(s) URL to ws(s) URL
99
122
  this.url = url.replace(/^http/, "ws")
100
- this.headers = headers
123
+ this.getHeaders = asHeadersProvider(auth)
124
+ }
125
+
126
+ /** The token this socket should authenticate with, or undefined when there is none. */
127
+ private async resolveToken(): Promise<string | undefined> {
128
+ const token = bearerToken(await this.getHeaders())
129
+ return token === "" ? undefined : token
130
+ }
131
+
132
+ /**
133
+ * Re-open the socket if the token it was opened with is no longer the current one.
134
+ *
135
+ * `createClient` calls this on every auth change. Without it the token preference above would
136
+ * still not be enough: every binding subscribes on mount, which is before the user has signed in,
137
+ * so the socket that matters is always one that was opened while signed out.
138
+ */
139
+ async reauthenticate(): Promise<void> {
140
+ if (this.ws === null && this.attempt === null) return
141
+ let token: string | undefined
142
+ try {
143
+ token = await this.resolveToken()
144
+ } catch {
145
+ return
146
+ }
147
+ if (token === this.currentToken) return
148
+ // Passed on rather than resolved a second time, so the socket opens with the token that
149
+ // justified opening it. Resolving twice left `currentToken` describing a token nobody checked.
150
+ this.cycleConnection(token)
151
+ }
152
+
153
+ /** Abandon the current socket and immediately open a replacement, keeping every channel. */
154
+ private cycleConnection(token: string | undefined): void {
155
+ this.abandonSocket("reauthenticating")
156
+ for (const state of this.channels.values()) {
157
+ state.subscribed = false
158
+ }
159
+ this.ensureConnection(token)
160
+ }
161
+
162
+ /**
163
+ * Drop the socket and any connect in flight, without deciding what happens next.
164
+ *
165
+ * Handlers are detached before closing, because `onclose` schedules a backoff reconnect that
166
+ * would otherwise race whatever the caller does instead.
167
+ */
168
+ private abandonSocket(reason: string): void {
169
+ this.attempt = null
170
+ if (this.reconnectTimer !== null) {
171
+ clearTimeout(this.reconnectTimer)
172
+ this.reconnectTimer = null
173
+ }
174
+ const old = this.ws
175
+ this.ws = null
176
+ this.currentToken = undefined
177
+ if (old !== null) {
178
+ old.onopen = null
179
+ old.onmessage = null
180
+ old.onclose = null
181
+ old.onerror = null
182
+ old.close(1000, reason)
183
+ }
184
+ this.reconnectAttempts = 0
101
185
  }
102
186
 
103
187
  channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
@@ -184,17 +268,16 @@ export class RealtimeClient {
184
268
  }
185
269
  }
186
270
 
187
- /** Disconnect the WebSocket entirely. */
271
+ /**
272
+ * Disconnect the WebSocket entirely.
273
+ *
274
+ * Shares `abandonSocket` with the re-authentication path, which is what stops an explicit
275
+ * disconnect from scheduling its own reconnect: the close handler is detached first. It also
276
+ * cancels a connect still waiting on its token, which would otherwise install a socket after the
277
+ * caller asked for none.
278
+ */
188
279
  disconnect(): void {
189
- if (this.reconnectTimer) {
190
- clearTimeout(this.reconnectTimer)
191
- this.reconnectTimer = null
192
- }
193
- if (this.ws) {
194
- this.ws.close(1000, "client disconnect")
195
- this.ws = null
196
- }
197
- this.reconnectAttempts = 0
280
+ this.abandonSocket("client disconnect")
198
281
  }
199
282
 
200
283
  // ─── Internal ──────────────────────────────────────────────────────────
@@ -215,18 +298,65 @@ export class RealtimeClient {
215
298
  return state
216
299
  }
217
300
 
218
- private ensureConnection(): void {
219
- if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
220
- return
301
+ /** True while a socket exists and is usable. */
302
+ private isLive(): boolean {
303
+ if (this.ws === null) return false
304
+ return this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING
305
+ }
306
+
307
+ private ensureConnection(token?: string | undefined): void {
308
+ // One connect at a time: resolving the token is asynchronous, so two subscribes in the same
309
+ // tick would otherwise each open a socket and the second would orphan the first.
310
+ if (this.isLive() || this.attempt !== null) return
311
+
312
+ let attempt: Promise<void>
313
+ const isCurrent = (): boolean => this.attempt === attempt
314
+ // Started on a microtask so `this.attempt` is assigned before `openSocket` can ask whether it
315
+ // is still the current one. Called directly, the path that already has a token reaches that
316
+ // question with no await in front of it, compares against a handle nobody had stored yet, and
317
+ // abandons itself.
318
+ attempt = Promise.resolve().then(() => this.openSocket(isCurrent, token))
319
+ this.attempt = attempt
320
+ void attempt.finally(() => {
321
+ // Only if it is still ours. An attempt abandoned mid-flight must not clear the handle of the
322
+ // replacement that took its place.
323
+ if (this.attempt === attempt) this.attempt = null
324
+ })
325
+ }
326
+
327
+ /**
328
+ * Resolve a token, then open the socket with it.
329
+ *
330
+ * Split out of ensureConnection because the token is asynchronous: the session may have to be
331
+ * refreshed before it is known. `epoch` is read before the await so a socket abandoned in the
332
+ * meantime, by disconnect() or by reauthenticate(), does not install itself afterwards.
333
+ */
334
+ private async openSocket(
335
+ isCurrent: () => boolean,
336
+ known?: string | undefined,
337
+ ): Promise<void> {
338
+ let token = known
339
+ if (token === undefined) {
340
+ try {
341
+ token = await this.resolveToken()
342
+ } catch {
343
+ // A token that cannot be resolved is not a reason to open an unauthenticated socket: the
344
+ // server would accept it and deliver nothing, which reads as a broken table rather than a
345
+ // failed sign-in. Let the backoff try again.
346
+ if (isCurrent() && this.channels.size > 0) this.scheduleReconnect()
347
+ return
348
+ }
221
349
  }
350
+ // Abandoned while the token was resolving, by disconnect() or by a re-authentication that has
351
+ // already started its own attempt. Installing this socket now would orphan that one.
352
+ if (!isCurrent()) return
222
353
 
223
- // Build URL with token from apikey header
224
- const token = this.headers["apikey"] ?? this.headers["Authorization"]?.replace("Bearer ", "")
354
+ this.currentToken = token
225
355
  const wsUrl = token ? `${this.url}?token=${encodeURIComponent(token)}` : this.url
356
+ const ws = new WebSocket(wsUrl)
357
+ this.ws = ws
226
358
 
227
- this.ws = new WebSocket(wsUrl)
228
-
229
- this.ws.onopen = () => {
359
+ ws.onopen = () => {
230
360
  this.reconnectAttempts = 0
231
361
  // Re-subscribe all channels
232
362
  for (const state of this.channels.values()) {
@@ -236,7 +366,7 @@ export class RealtimeClient {
236
366
  }
237
367
  }
238
368
 
239
- this.ws.onmessage = (event) => {
369
+ ws.onmessage = (event) => {
240
370
  try {
241
371
  const msg = JSON.parse(String(event.data)) as ServerMessage
242
372
  this.handleServerMessage(msg)
@@ -245,7 +375,7 @@ export class RealtimeClient {
245
375
  }
246
376
  }
247
377
 
248
- this.ws.onclose = () => {
378
+ ws.onclose = () => {
249
379
  this.ws = null
250
380
  // Mark all channels as unsubscribed
251
381
  for (const state of this.channels.values()) {
@@ -257,7 +387,7 @@ export class RealtimeClient {
257
387
  }
258
388
  }
259
389
 
260
- this.ws.onerror = () => {
390
+ ws.onerror = () => {
261
391
  // onclose will fire after onerror
262
392
  }
263
393
  }
@@ -379,10 +509,21 @@ export class RealtimeClient {
379
509
  }
380
510
  }
381
511
 
512
+ // `table` and `schema` travel with the subscription, rather than being inferred from the
513
+ // channel name at the other end.
514
+ //
515
+ // They were resolved here and then dropped, and the server falls back to reading the channel
516
+ // name as `schema:table`. So a subscription worked only when the channel happened to be named
517
+ // after its table, which is what `from(table).subscribe()` does. Anything else -- a channel
518
+ // called `lobby-chat` carrying `table: "chat_message"`, which is what `useSubscription` exists
519
+ // to let you write -- registered against a table no change can match. The socket reported
520
+ // SUBSCRIBED and delivered nothing, which is indistinguishable from a quiet table.
382
521
  this.sendMessage({
383
522
  type: "subscribe",
384
523
  channel: state.name,
385
524
  event: firstListener?.event ?? "*",
525
+ ...(firstListener?.table !== undefined && { table: firstListener.table }),
526
+ ...(firstListener?.schema !== undefined && { schema: firstListener.schema }),
386
527
  filter: Object.keys(filter).length > 0 ? filter : undefined,
387
528
  })
388
529
  }
package/src/storage.ts CHANGED
@@ -156,6 +156,22 @@ export class BucketClient {
156
156
  return { data: { publicUrl } }
157
157
  }
158
158
 
159
+ /**
160
+ * Resolve what the storage API returned against this client's base URL.
161
+ *
162
+ * `getPublicUrl` hands back something fetchable; this used to hand back the server's response
163
+ * verbatim, and the server answers with a path (`/object/sign/...`). So one of the two URL
164
+ * methods returned a URL and the other returned half of one, which fails at the caller as
165
+ * `TypeError: Failed to parse URL` rather than anywhere near here.
166
+ *
167
+ * Absolute answers are passed through untouched, so a deployment whose storage API returns a
168
+ * full URL (a CDN, a signed S3 link) is not mangled by being prefixed a second time.
169
+ */
170
+ private absoluteObjectUrl(value: string): string {
171
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return value
172
+ return `${this.url.replace(/\/$/, "")}/${value.replace(/^\//, "")}`
173
+ }
174
+
159
175
  async createSignedUrl(
160
176
  path: string,
161
177
  expiresIn: number,
@@ -170,7 +186,7 @@ export class BucketClient {
170
186
  return { data: null, error: { message: String(err["message"] ?? err["error"] ?? "Failed to create signed URL"), status: res.status } }
171
187
  }
172
188
  const json = await res.json() as { signedURL: string }
173
- return { data: { signedUrl: json.signedURL }, error: null }
189
+ return { data: { signedUrl: this.absoluteObjectUrl(json.signedURL) }, error: null }
174
190
  }
175
191
 
176
192
  async createSignedUrls(
@@ -0,0 +1,70 @@
1
+ import { vi } from "vitest"
2
+
3
+ /**
4
+ * A stand-in WebSocket for the realtime suites.
5
+ *
6
+ * Shared because two suites drive the same socket lifecycle, and that lifecycle has just grown a
7
+ * one-at-a-time connect guard and a detach-before-close path. Two copies of the fake would have to
8
+ * learn each of those separately, and the first one to forget would pass while describing a client
9
+ * that no longer exists.
10
+ *
11
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
12
+ */
13
+ export interface MockWebSocketInstance {
14
+ url: string
15
+ readyState: number
16
+ onopen: ((event: Event) => void) | null
17
+ onclose: ((event: CloseEvent) => void) | null
18
+ onmessage: ((event: MessageEvent) => void) | null
19
+ onerror: ((event: Event) => void) | null
20
+ send: ReturnType<typeof vi.fn>
21
+ close: ReturnType<typeof vi.fn>
22
+ }
23
+
24
+ export function createMockWebSocketClass(): {
25
+ MockWebSocket: typeof WebSocket
26
+ instances: MockWebSocketInstance[]
27
+ } {
28
+ const instances: MockWebSocketInstance[] = []
29
+
30
+ class MockWebSocket {
31
+ static OPEN = 1
32
+ static CONNECTING = 0
33
+ static CLOSED = 3
34
+
35
+ url: string
36
+ readyState = 0
37
+ onopen: ((event: Event) => void) | null = null
38
+ onclose: ((event: CloseEvent) => void) | null = null
39
+ onmessage: ((event: MessageEvent) => void) | null = null
40
+ onerror: ((event: Event) => void) | null = null
41
+ send = vi.fn()
42
+ close = vi.fn()
43
+
44
+ constructor(url: string) {
45
+ this.url = url
46
+ instances.push(this as unknown as MockWebSocketInstance)
47
+
48
+ // Auto-open after a microtask
49
+ queueMicrotask(() => {
50
+ this.readyState = 1 // OPEN
51
+ this.onopen?.({} as Event)
52
+ })
53
+ }
54
+ }
55
+
56
+ return { MockWebSocket: MockWebSocket as unknown as typeof WebSocket, instances }
57
+ }
58
+
59
+ /** Simulate a server message arriving on a WebSocket instance. */
60
+ export function simulateServerMessage(
61
+ ws: MockWebSocketInstance,
62
+ msg: Record<string, unknown>,
63
+ ): void {
64
+ ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
65
+ }
66
+
67
+ /** The token a socket was opened with, read back out of its URL. */
68
+ export function tokenOf(ws: MockWebSocketInstance): string | null {
69
+ return new URL(ws.url.replace(/^ws/, "http")).searchParams.get("token")
70
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Which auth transitions a data hook should re-run on.
3
+ *
4
+ * The bindings' queries fetch once when their component mounts, which is before anybody has signed
5
+ * in, so on a table guarded by a logged-in policy that fetch reads nothing and the view stayed
6
+ * empty until something else called refetch. They now re-run on identity change, and this is the
7
+ * narrowing that makes that affordable: `onAuthStateChange` also fires at registration and on every
8
+ * token refresh, and re-running on those would double every mount's fetch and then refetch on a
9
+ * timer for as long as the page stayed open.
10
+ */
11
+
12
+ import { describe, it, expect, vi } from "vitest"
13
+ import { onIdentityChange, type IdentitySource } from "../src/identity.js"
14
+ import type { AuthChangeEvent, Session } from "../src/types.js"
15
+
16
+ /** An auth client stand-in whose emissions the test drives by hand. */
17
+ function fakeAuth(): {
18
+ source: IdentitySource
19
+ emit: (event: AuthChangeEvent, session: Session | null) => void
20
+ unsubscribed: () => number
21
+ } {
22
+ let listener: ((event: AuthChangeEvent, session: Session | null) => void) | null = null
23
+ let unsubscribes = 0
24
+ return {
25
+ source: {
26
+ onAuthStateChange(callback) {
27
+ listener = callback
28
+ return { data: { subscription: { unsubscribe: () => { unsubscribes += 1 } } } }
29
+ },
30
+ },
31
+ emit: (event, session) => listener?.(event, session),
32
+ unsubscribed: () => unsubscribes,
33
+ }
34
+ }
35
+
36
+ function sessionFor(userId: string, accessToken = "token"): Session {
37
+ return {
38
+ accessToken,
39
+ tokenType: "bearer",
40
+ expiresIn: 3600,
41
+ refreshToken: "refresh",
42
+ user: {
43
+ id: userId,
44
+ email: `${userId}@example.com`,
45
+ role: "authenticated",
46
+ app_metadata: {},
47
+ user_metadata: {},
48
+ created_at: "2024-01-01T00:00:00Z",
49
+ updated_at: "2024-01-01T00:00:00Z",
50
+ },
51
+ } as Session
52
+ }
53
+
54
+ describe("onIdentityChange", () => {
55
+ it("does not fire on the emission onAuthStateChange makes at registration", () => {
56
+ const auth = fakeAuth()
57
+ const onChange = vi.fn()
58
+ onIdentityChange(auth.source, onChange)
59
+
60
+ // AuthClient calls back synchronously when a listener registers. Treating that as a change
61
+ // would refetch immediately after the fetch the caller has already made on mount.
62
+ auth.emit("SIGNED_OUT", null)
63
+
64
+ expect(onChange).not.toHaveBeenCalled()
65
+ })
66
+
67
+ it("fires when a signed-out page signs in", () => {
68
+ const auth = fakeAuth()
69
+ const onChange = vi.fn()
70
+ onIdentityChange(auth.source, onChange)
71
+ auth.emit("SIGNED_OUT", null)
72
+
73
+ auth.emit("SIGNED_IN", sessionFor("user-1"))
74
+
75
+ expect(onChange).toHaveBeenCalledTimes(1)
76
+ })
77
+
78
+ it("does not fire on a token refresh for the same user", () => {
79
+ const auth = fakeAuth()
80
+ const onChange = vi.fn()
81
+ onIdentityChange(auth.source, onChange)
82
+ auth.emit("SIGNED_IN", sessionFor("user-1", "first"))
83
+
84
+ auth.emit("TOKEN_REFRESHED", sessionFor("user-1", "second"))
85
+ auth.emit("TOKEN_REFRESHED", sessionFor("user-1", "third"))
86
+
87
+ expect(onChange).not.toHaveBeenCalled()
88
+ })
89
+
90
+ it("fires on sign out", () => {
91
+ const auth = fakeAuth()
92
+ const onChange = vi.fn()
93
+ onIdentityChange(auth.source, onChange)
94
+ auth.emit("SIGNED_IN", sessionFor("user-1"))
95
+
96
+ auth.emit("SIGNED_OUT", null)
97
+
98
+ expect(onChange).toHaveBeenCalledTimes(1)
99
+ })
100
+
101
+ it("fires when one user replaces another", () => {
102
+ const auth = fakeAuth()
103
+ const onChange = vi.fn()
104
+ onIdentityChange(auth.source, onChange)
105
+ auth.emit("SIGNED_IN", sessionFor("user-1"))
106
+
107
+ auth.emit("SIGNED_IN", sessionFor("user-2"))
108
+
109
+ expect(onChange).toHaveBeenCalledTimes(1)
110
+ })
111
+
112
+ it("unsubscribes the underlying listener when torn down", () => {
113
+ const auth = fakeAuth()
114
+ const stop = onIdentityChange(auth.source, vi.fn())
115
+
116
+ stop()
117
+
118
+ expect(auth.unsubscribed()).toBe(1)
119
+ })
120
+ })