@supatype/client 0.7.0 → 0.9.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.
Files changed (67) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +69 -56
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +28 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +17 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +41 -10
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +1 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/graphql-transport.d.ts +2 -2
  13. package/dist/graphql-transport.d.ts.map +1 -1
  14. package/dist/graphql-transport.js.map +1 -1
  15. package/dist/index.d.ts +16 -13
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +33 -21
  18. package/dist/index.js.map +1 -1
  19. package/dist/mutation-request.d.ts +17 -4
  20. package/dist/mutation-request.d.ts.map +1 -1
  21. package/dist/mutation-request.js +16 -14
  22. package/dist/mutation-request.js.map +1 -1
  23. package/dist/query.d.ts +40 -16
  24. package/dist/query.d.ts.map +1 -1
  25. package/dist/query.js +81 -21
  26. package/dist/query.js.map +1 -1
  27. package/dist/realtime.d.ts +38 -1
  28. package/dist/realtime.d.ts.map +1 -1
  29. package/dist/realtime.js +201 -82
  30. package/dist/realtime.js.map +1 -1
  31. package/dist/storage.d.ts.map +1 -1
  32. package/dist/storage.js +10 -3
  33. package/dist/storage.js.map +1 -1
  34. package/dist/types.d.ts +14 -0
  35. package/dist/types.d.ts.map +1 -1
  36. package/package.json +5 -2
  37. package/src/auth.ts +43 -10
  38. package/src/bindings.ts +1 -1
  39. package/src/graphql-transport.ts +2 -2
  40. package/src/index.ts +40 -26
  41. package/src/mutation-request.ts +32 -18
  42. package/src/query.ts +102 -37
  43. package/src/realtime.ts +222 -82
  44. package/src/storage.ts +11 -3
  45. package/src/types.ts +14 -0
  46. package/tests/auth.test.ts +65 -0
  47. package/tests/data-plane-auth.test.ts +1 -6
  48. package/tests/draft-insert.test.ts +9 -9
  49. package/tests/draft-update.test.ts +5 -5
  50. package/tests/helpers/socket-swap.ts +3 -0
  51. package/tests/minimal-writes.test.ts +118 -0
  52. package/tests/postgrest-error-codes.test.ts +1 -1
  53. package/tests/query.test.ts +3 -3
  54. package/tests/realtime-ack-ref.test.ts +112 -0
  55. package/tests/realtime-session-auth.test.ts +1 -4
  56. package/tests/realtime-shared-channel.test.ts +209 -0
  57. package/tests/rpc-resend.test.ts +33 -8
  58. package/tests/server-bodies.test.ts +48 -0
  59. package/tests/storage-quota-integration.test.ts +4 -7
  60. package/tests/storage-upload-limit-integration.test.ts +5 -9
  61. package/tests/storage-url-encoding.test.ts +52 -0
  62. package/tests/supatype-prepare.test.ts +139 -0
  63. package/tests/support/blob.ts +10 -0
  64. package/tests/support/jwt.ts +4 -0
  65. package/tests/table-subscribe.test.ts +28 -1
  66. package/tests/unauthorized-resend.test.ts +107 -0
  67. package/tsconfig.tsbuildinfo +1 -1
@@ -92,9 +92,9 @@ describe("insert on a model that keeps drafts", () => {
92
92
  expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
93
93
  })
94
94
 
95
- it("returns the row as a plain insert would", async () => {
95
+ it("returns the row as a plain insert would, once select() asks", async () => {
96
96
  serve(draftsServer())
97
- const { data, error, count } = await client().from("posts").insert({ title: "Mine" })
97
+ const { data, error, count } = await client().from("posts").insert({ title: "Mine" }).select()
98
98
  expect(error).toBeNull()
99
99
  expect(data).toEqual([ROW])
100
100
  expect(count).toBe(1)
@@ -109,7 +109,7 @@ describe("insert on a model that keeps drafts", () => {
109
109
 
110
110
  it("treats a one-row array as one record", async () => {
111
111
  const fetch = serve(draftsServer())
112
- const { data } = await client().from("posts").insert([{ title: "Mine" }])
112
+ const { data } = await client().from("posts").insert([{ title: "Mine" }]).select()
113
113
  expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
114
114
  expect(jsonBody(fetchCalls(fetch)[0]?.init ?? {})["data"]).toEqual({ title: "Mine" })
115
115
  expect(data).toEqual([ROW])
@@ -158,8 +158,8 @@ describe("insert on a model that keeps drafts", () => {
158
158
 
159
159
  it("leaves an empty insert a plain write, which creates nothing", async () => {
160
160
  const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([], 201))))
161
- const { data } = await client().from("posts").insert([])
162
- expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
161
+ const { data } = await client().from("posts").insert([]).select()
162
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts?select=*`])
163
163
  expect(data).toEqual([])
164
164
  })
165
165
 
@@ -189,7 +189,7 @@ describe("insert on a model that keeps drafts", () => {
189
189
 
190
190
  it("reaches the framework bindings, which insert through runMutation", async () => {
191
191
  const fetch = serve(draftsServer())
192
- const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" })
192
+ const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" }, { select: true })
193
193
  expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
194
194
  expect(outcome.data).toEqual([ROW])
195
195
  })
@@ -201,12 +201,12 @@ describe("insert on a model that keeps no drafts", () => {
201
201
  vi.unstubAllGlobals()
202
202
  })
203
203
 
204
- it("is a plain insert asking for the row back", async () => {
204
+ it("is a plain insert, asking for the row back once select() does", async () => {
205
205
  registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
206
206
  const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1 }], 201))))
207
- await client().from("tags").insert({ label: "news" })
207
+ await client().from("tags").insert({ label: "news" }).select()
208
208
  const [only] = fetchCalls(fetch)
209
- expect(only?.url).toBe(`${BASE}/rest/v1/tags`)
209
+ expect(only?.url).toBe(`${BASE}/rest/v1/tags?select=*`)
210
210
  expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
211
211
  })
212
212
 
@@ -96,7 +96,7 @@ describe("update on a model that keeps drafts", () => {
96
96
 
97
97
  it("saves nothing when the filters match no record, as a PATCH that matches nothing", async () => {
98
98
  const fetch = serve(draftsServer([]))
99
- const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
99
+ const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID).select()
100
100
  expect(fetchCalls(fetch)).toHaveLength(1)
101
101
  expect({ data, error, count }).toEqual({ data: [], error: null, count: 0 })
102
102
  })
@@ -116,7 +116,7 @@ describe("update on a model that keeps drafts", () => {
116
116
 
117
117
  it("reaches the framework bindings, which update through runMutation", async () => {
118
118
  const fetch = serve(draftsServer())
119
- const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { id: ID }, { publish: true })
119
+ const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { filter: { id: ID }, publish: true, select: true })
120
120
  expect(fetchCalls(fetch)[1]?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
121
121
  expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
122
122
  expect(outcome.data).toEqual([DRAFT])
@@ -129,14 +129,14 @@ describe("update on a model that keeps no drafts", () => {
129
129
  vi.unstubAllGlobals()
130
130
  })
131
131
 
132
- it("is a plain PATCH asking for the rows back", async () => {
132
+ it("is a plain PATCH, asking for the rows back once select() does", async () => {
133
133
  registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
134
134
  const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1, label: "news" }]))))
135
- const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1)
135
+ const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1).select()
136
136
  const [only] = fetchCalls(fetch)
137
137
  expect(fetchCalls(fetch)).toHaveLength(1)
138
138
  expect(only?.init.method).toBe("PATCH")
139
- expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1`)
139
+ expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1&select=*`)
140
140
  expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
141
141
  expect(data).toEqual([{ id: 1, label: "news" }])
142
142
  })
@@ -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}`)
@@ -0,0 +1,118 @@
1
+ import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"
2
+ import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase, type QueryResult } from "../src/index.js"
3
+ import { fetchCalls, header, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
4
+
5
+ // A write asks for no rows back unless `.select()` says to, as postgrest-js does. Returning a row
6
+ // needs SELECT on it, so a table whose rules let a caller create but not read refused every insert
7
+ // that asked: an anon order form, say, answered 401 42501 for a row it was allowed to write.
8
+
9
+ const BASE = "http://localhost:18473"
10
+ const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
11
+ const ROW = { id: ID, title: "Mine" }
12
+
13
+ /** PostgREST answering a write that asked for nothing back: 201 or 204, and no body. */
14
+ function minimalServer(): FetchMock {
15
+ return mockFetch((_input, init) => {
16
+ const prefer = header(init ?? {}, "Prefer") ?? ""
17
+ if (prefer.includes("return=representation")) return Promise.resolve(jsonResponse([ROW], 201))
18
+ return Promise.resolve(new Response(null, { status: init?.method === "POST" ? 201 : 204 }))
19
+ })
20
+ }
21
+
22
+ function serve(fetch: FetchMock): FetchMock {
23
+ vi.stubGlobal("fetch", fetch)
24
+ return fetch
25
+ }
26
+
27
+ const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key", auth: { persistSession: false } })
28
+
29
+ describe("a write without select()", () => {
30
+ afterEach(() => vi.unstubAllGlobals())
31
+
32
+ it("insert asks for no representation and resolves to no rows", async () => {
33
+ const fetch = serve(minimalServer())
34
+ const result = await client().from("orders").insert({ title: "Mine" })
35
+ expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBeNull()
36
+ expect(result).toEqual({ data: null, error: null, count: null })
37
+ })
38
+
39
+ it("update asks for no representation and resolves to no rows", async () => {
40
+ const fetch = serve(minimalServer())
41
+ const result = await client().from("orders").update({ title: "Edited" }).eq("id", ID)
42
+ expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBeNull()
43
+ expect(result).toEqual({ data: null, error: null, count: null })
44
+ })
45
+
46
+ it("upsert keeps only its conflict resolution", async () => {
47
+ const fetch = serve(minimalServer())
48
+ const result = await client().from("orders").upsert({ id: ID, title: "Mine" })
49
+ expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBe("resolution=merge-duplicates")
50
+ expect(result.data).toBeNull()
51
+ })
52
+
53
+ it("delete resolves to no rows", async () => {
54
+ serve(minimalServer())
55
+ const result = await client().from("orders").delete().eq("id", ID)
56
+ expect(result).toEqual({ data: null, error: null, count: null })
57
+ })
58
+ })
59
+
60
+ describe("a write with select()", () => {
61
+ afterEach(() => vi.unstubAllGlobals())
62
+
63
+ it("asks for the representation and resolves to the rows", async () => {
64
+ const fetch = serve(minimalServer())
65
+ const { data, count } = await client().from("orders").insert({ title: "Mine" }).select()
66
+ expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBe("return=representation")
67
+ expect({ data, count }).toEqual({ data: [ROW], count: 1 })
68
+ })
69
+ })
70
+
71
+ describe("a drafts-model write without select()", () => {
72
+ beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
73
+ afterEach(() => {
74
+ forgetRegisteredDraftModels()
75
+ vi.unstubAllGlobals()
76
+ })
77
+
78
+ /** create_record and save_drafts answer with the record keys; a table read names the matches. */
79
+ function draftsServer(): FetchMock {
80
+ return mockFetch((input) => {
81
+ const url = requestUrl(input)
82
+ if (url.endsWith("/rpc/create_record")) return Promise.resolve(jsonResponse({ record_id: ID, version: 1 }))
83
+ if (url.endsWith("/rpc/save_drafts")) return Promise.resolve(jsonResponse([{ record_id: ID, version: 2 }]))
84
+ return Promise.resolve(jsonResponse([ROW]))
85
+ })
86
+ }
87
+
88
+ it("insert creates the record and reads nothing back", async () => {
89
+ const fetch = serve(draftsServer())
90
+ const result = await client().from("posts").insert({ title: "Mine" })
91
+ expect(fetchCalls(fetch).map(({ url }) => url)).toEqual([`${BASE}/rest/v1/rpc/create_record`])
92
+ expect(result).toEqual({ data: null, error: null, count: null })
93
+ })
94
+
95
+ it("update saves the drafts and reads none of them back", async () => {
96
+ const fetch = serve(draftsServer())
97
+ const result = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
98
+ expect(fetchCalls(fetch).map(({ url }) => new URL(url).pathname)).toEqual(["/rest/v1/posts", "/rest/v1/rpc/save_drafts"])
99
+ expect(result).toEqual({ data: null, error: null, count: null })
100
+ })
101
+ })
102
+
103
+ // Checked by `tsc -p tests/tsconfig.json`, not by vitest.
104
+ type Order = { Row: { id: string; title: string }; Insert: { title: string }; Update: { title?: string } }
105
+ type Shop = { public: { Tables: { orders: Order } } }
106
+
107
+ describe("the types of a write", () => {
108
+ it("resolve to null without select(), to rows with it, and allow single() only after it", () => {
109
+ const typed = createClient<Shop>({ url: BASE, anonKey: "anon-key" })
110
+ expectTypeOf(typed.from("orders").insert({ title: "x" })).resolves.toEqualTypeOf<QueryResult<null>>()
111
+ expectTypeOf(typed.from("orders").insert({ title: "x" }).select("id")).resolves.toEqualTypeOf<QueryResult<{ id: string }[]>>()
112
+ void typed.from("orders").insert({ title: "x" }).select().single()
113
+ // @ts-expect-error a write returns no row until select() asks for one
114
+ void typed.from("orders").insert({ title: "x" }).single()
115
+ // @ts-expect-error a write returns no row until select() asks for one
116
+ void typed.from("orders").update({ title: "x" }).eq("id", ID).maybeSingle()
117
+ })
118
+ })
@@ -55,7 +55,7 @@ describe("single() without exactly one row", () => {
55
55
 
56
56
  it("a write words it as PostgREST does", async () => {
57
57
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
58
- const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).single()
58
+ const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).select().single()
59
59
  vi.unstubAllGlobals()
60
60
  expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
61
61
  })
@@ -268,7 +268,7 @@ describe("MutationBuilder: insert", () => {
268
268
  it("sends POST with body", async () => {
269
269
  const fetch = mockFetch([{ id: "1", title: "New", status: "draft" }])
270
270
  vi.stubGlobal("fetch", fetch)
271
- const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
271
+ const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" }).select()
272
272
  expect(error).toBeNull()
273
273
  expect(data?.[0]?.id).toBe("1")
274
274
  const { init } = fetchCall(fetch)
@@ -305,9 +305,9 @@ describe("MutationBuilder: update / delete", () => {
305
305
  expect(url).toContain("id=eq.1")
306
306
  })
307
307
 
308
- it("204 No Content returns empty data array", async () => {
308
+ it("204 No Content to delete().select() returns an empty data array", async () => {
309
309
  vi.stubGlobal("fetch", mockFetch(null, { status: 204 }))
310
- const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
310
+ const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1").select()
311
311
  expect(error).toBeNull()
312
312
  expect(data).toEqual([])
313
313
  })
@@ -0,0 +1,112 @@
1
+ /**
2
+ * A server reply is matched to the join that asked for it, not to whatever join on that channel
3
+ * name happens to be pending when it arrives.
4
+ *
5
+ * Replies used to be read by channel name alone. Two joins on one name close together (a rejoin
6
+ * after the joining handle leaves, or a leave followed at once by a new join) each got the other's
7
+ * answer: the first join's acknowledgement reported SUBSCRIBED for a second join the server went on
8
+ * to refuse, and the first join's refusal put a handle whose own join succeeded into CHANNEL_ERROR.
9
+ *
10
+ * The fake server here answers every frame in the order it was sent, as the real one does, and
11
+ * echoes the frame's `ref` when it carried one.
12
+ */
13
+
14
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
15
+ import type { ChannelStatus } from "../src/realtime.js"
16
+ import { channelOf, sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
17
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
18
+
19
+ const CHANNEL = "x"
20
+ const BAD_FILTER = "status=like.open"
21
+
22
+ let harness: SocketSwapHarness
23
+ let answered = 0
24
+
25
+ /** The server's reply to one subscribe or unsubscribe frame, with a join's ref when it had one. */
26
+ function replyTo(frame: Record<string, unknown>, echoRef: boolean): Record<string, unknown> {
27
+ const channel = channelOf(frame)
28
+ if (frame["type"] === "unsubscribe") return { type: "system", status: "ok", message: `unsubscribed from ${channel}` }
29
+ const ref = echoRef && typeof frame["ref"] === "string" ? { ref: frame["ref"] } : {}
30
+ const filter = frame["filter"]
31
+ const refused = typeof filter === "object" && filter !== null && "status" in filter
32
+ if (refused) return { type: "system", status: "error", message: `invalid filter ${BAD_FILTER}`, channel, ...ref }
33
+ return { type: "system", status: "ok", message: `subscribed to ${channel}`, ...ref }
34
+ }
35
+
36
+ /** Answer every join and leave sent since the last call, in the order they went out. */
37
+ function answerInOrder({ echoRef = true }: { echoRef?: boolean } = {}): void {
38
+ const pending = sentFrames(harness.socket())
39
+ .filter((frame) => frame["type"] === "subscribe" || frame["type"] === "unsubscribe")
40
+ .slice(answered)
41
+ answered += pending.length
42
+ for (const frame of pending) simulateServerMessage(harness.socket(), replyTo(frame, echoRef))
43
+ }
44
+
45
+ beforeEach(() => {
46
+ harness = createSocketSwapHarness()
47
+ answered = 0
48
+ })
49
+
50
+ afterEach(() => harness.restore())
51
+
52
+ describe("a rejoin sent before the join it replaces is answered", () => {
53
+ it("is not reported SUBSCRIBED by the earlier join's acknowledgement when it is itself refused", async () => {
54
+ const statuses: ChannelStatus[] = []
55
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
56
+ harness.realtime
57
+ .channel(CHANNEL)
58
+ .on("postgres_changes", { event: "*", table: "messages", filter: BAD_FILTER }, () => {})
59
+ .subscribe((s) => statuses.push(s))
60
+ await harness.settle()
61
+
62
+ // The first join is still unanswered when its handle leaves, so the channel joins again.
63
+ a.unsubscribe()
64
+ answerInOrder()
65
+
66
+ expect(statuses).toEqual(["SUBSCRIBING", "CHANNEL_ERROR"])
67
+ // Nothing on this channel is subscribed, so a handle arriving now is not told it is.
68
+ const late: ChannelStatus[] = []
69
+ harness.realtime.channel(CHANNEL).subscribe((s) => late.push(s))
70
+ expect(late).toEqual([])
71
+ })
72
+ })
73
+
74
+ describe("a join sent right after the channel was left", () => {
75
+ function join(filter: string | undefined, onStatus?: (status: ChannelStatus) => void): { unsubscribe(): void } {
76
+ return harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t", filter }, () => {}).subscribe(onStatus)
77
+ }
78
+
79
+ async function leaveThenJoin(firstFilter: string | undefined, secondFilter: string | undefined): Promise<ChannelStatus[]> {
80
+ // Another channel keeps the socket open across the leave.
81
+ harness.realtime.channel("keep").subscribe()
82
+ const first = join(firstFilter)
83
+ await harness.settle()
84
+ first.unsubscribe()
85
+ const statuses: ChannelStatus[] = []
86
+ join(secondFilter, (s) => statuses.push(s))
87
+ answerInOrder()
88
+ return statuses
89
+ }
90
+
91
+ it("is not put into CHANNEL_ERROR by the refusal of the join before it", async () => {
92
+ expect(await leaveThenJoin(BAD_FILTER, undefined)).toEqual(["SUBSCRIBED"])
93
+ })
94
+
95
+ it("is not reported SUBSCRIBED by the acknowledgement of the join before it", async () => {
96
+ expect(await leaveThenJoin(undefined, BAD_FILTER)).toEqual(["CHANNEL_ERROR"])
97
+ })
98
+ })
99
+
100
+ describe("a server that echoes no ref", () => {
101
+ it("still has its replies read by channel name, as before refs existed", async () => {
102
+ const statuses: ChannelStatus[] = []
103
+ harness.realtime.channel(CHANNEL).subscribe((s) => statuses.push(s))
104
+ await harness.settle()
105
+
106
+ const join = sentFrames(harness.socket()).find((frame) => frame["type"] === "subscribe")
107
+ expect(typeof join?.["ref"]).toBe("string")
108
+ answerInOrder({ echoRef: false })
109
+
110
+ expect(statuses).toEqual(["SUBSCRIBED"])
111
+ })
112
+ })
@@ -22,6 +22,7 @@ import {
22
22
  } from "./helpers/mock-websocket.js"
23
23
  import { createClient } from "../src/index.js"
24
24
  import type { Session } from "../src/types.js"
25
+ import { fakeJwt } from "./support/jwt.js"
25
26
 
26
27
  const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
27
28
 
@@ -30,10 +31,6 @@ function bearerHeaders(token: string): Record<string, string> {
30
31
  return { apikey: "anon-key", Authorization: `Bearer ${token}` }
31
32
  }
32
33
 
33
- function fakeJwt(payload: Record<string, unknown>): string {
34
- return `${btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${btoa(JSON.stringify(payload))}.sig`
35
- }
36
-
37
34
  const ANON_KEY = fakeJwt({ role: "anon" })
38
35
  const USER_TOKEN = fakeJwt({
39
36
  role: "authenticated",
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Two handles on one channel name are independent until the last one leaves.
3
+ *
4
+ * `channel(name)` handed every caller the same state: the second `subscribe()` replaced the first
5
+ * one's status callback, and the first `unsubscribe()` told the server to leave and deleted the
6
+ * channel, listeners and all. Two `useSubscription` hooks with one channel name broke each other:
7
+ * when one unmounted, the other stopped receiving changes while still reading SUBSCRIBED.
8
+ */
9
+
10
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
11
+ import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
12
+ import { sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
13
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
14
+
15
+ const CHANNEL = "x"
16
+
17
+ let harness: SocketSwapHarness
18
+
19
+ function unsubscribeFrames(): Array<Record<string, unknown>> {
20
+ return sentFrames(harness.socket()).filter((frame) => frame["type"] === "unsubscribe" && frame["channel"] === CHANNEL)
21
+ }
22
+
23
+ function deliverInsert(id: number): void {
24
+ simulateServerMessage(harness.socket(), {
25
+ type: "change",
26
+ channel: CHANNEL,
27
+ event: "INSERT",
28
+ payload: { old: null, new: { id } },
29
+ timestamp: "2026-10-28T00:00:00Z",
30
+ })
31
+ }
32
+
33
+ beforeEach(() => {
34
+ harness = createSocketSwapHarness()
35
+ })
36
+
37
+ afterEach(() => harness.restore())
38
+
39
+ describe("two handles on one channel name", () => {
40
+ it("keeps the second receiving changes once the first unsubscribes", async () => {
41
+ const first: Array<RealtimePayload<Record<string, unknown>>> = []
42
+ const second: Array<RealtimePayload<Record<string, unknown>>> = []
43
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t" }, (p) => first.push(p)).subscribe()
44
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "t" }, (p) => second.push(p)).subscribe()
45
+ await harness.settle()
46
+ harness.ackJoins()
47
+
48
+ a.unsubscribe()
49
+ deliverInsert(1)
50
+
51
+ expect(first).toEqual([])
52
+ expect(second.map((p) => p.new)).toEqual([{ id: 1 }])
53
+ expect(unsubscribeFrames()).toEqual([])
54
+ })
55
+
56
+ it("tells the server to leave only when the last handle unsubscribes", async () => {
57
+ const a = harness.realtime.channel(CHANNEL).subscribe()
58
+ const b = harness.realtime.channel(CHANNEL).subscribe()
59
+ await harness.settle()
60
+ harness.ackJoins()
61
+
62
+ a.unsubscribe()
63
+ expect(unsubscribeFrames()).toEqual([])
64
+ expect(harness.socket().close).not.toHaveBeenCalled()
65
+
66
+ b.unsubscribe()
67
+ expect(unsubscribeFrames()).toHaveLength(1)
68
+ })
69
+
70
+ it("reports status to each handle's own callback", async () => {
71
+ const first: ChannelStatus[] = []
72
+ const second: ChannelStatus[] = []
73
+ harness.realtime.channel(CHANNEL).subscribe((s) => first.push(s))
74
+ harness.realtime.channel(CHANNEL).subscribe((s) => second.push(s))
75
+ await harness.settle()
76
+ harness.ackJoins()
77
+
78
+ expect(first).toEqual(["SUBSCRIBED"])
79
+ expect(second).toEqual(["SUBSCRIBED"])
80
+ })
81
+
82
+ it("stops a handle's presence and broadcast listeners when it unsubscribes, and only its own", async () => {
83
+ const heard: string[] = []
84
+ const a = harness.realtime.channel(CHANNEL)
85
+ .onBroadcast("ping", () => heard.push("a"))
86
+ .onPresence(() => heard.push("a-presence"))
87
+ .subscribe()
88
+ harness.realtime.channel(CHANNEL)
89
+ .onBroadcast("ping", () => heard.push("b"))
90
+ .onPresence(() => heard.push("b-presence"))
91
+ .subscribe()
92
+ await harness.settle()
93
+ harness.ackJoins()
94
+
95
+ a.unsubscribe()
96
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: CHANNEL, event: "ping", payload: {} })
97
+ simulateServerMessage(harness.socket(), { type: "presence", channel: CHANNEL, joins: [{ user_id: "u" }], leaves: [] })
98
+
99
+ expect(heard).toEqual(["b", "b-presence"])
100
+ })
101
+ })
102
+
103
+ /**
104
+ * The join is made once, with the oldest handle's first row listener, and stays registered for that
105
+ * table after that handle leaves. Rows used to be matched and labelled against whichever listener
106
+ * was first now, so once the oldest handle unsubscribed, the next handle's listener for another
107
+ * table was handed this table's rows under its own table's name.
108
+ */
109
+ describe("rows on a channel whose joining handle has left", () => {
110
+ it("go to listeners for the joined table, labelled with it, and not to one for another table", async () => {
111
+ const audit: Array<RealtimePayload<Record<string, unknown>>> = []
112
+ const messages: Array<RealtimePayload<Record<string, unknown>>> = []
113
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "messages" }, () => {}).subscribe()
114
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, (p) => audit.push(p)).subscribe()
115
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "messages" }, (p) => messages.push(p)).subscribe()
116
+ await harness.settle()
117
+ harness.ackJoins()
118
+
119
+ a.unsubscribe()
120
+ deliverInsert(1)
121
+
122
+ expect(audit).toEqual([])
123
+ expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
124
+ })
125
+ })
126
+
127
+ function subscribeFrames(): Array<Record<string, unknown>> {
128
+ return sentFrames(harness.socket()).filter((frame) => frame["type"] === "subscribe" && frame["channel"] === CHANNEL)
129
+ }
130
+
131
+ function ackJoin(channel: string): void {
132
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: `subscribed to ${channel}` })
133
+ }
134
+
135
+ /**
136
+ * When the handle whose listener made the join leaves and no remaining listener is for that join,
137
+ * the channel joins again for the oldest remaining listener. It used to stay registered for the
138
+ * table the leaver listened to, and the others reported SUBSCRIBED and were sent nothing.
139
+ */
140
+ describe("a channel whose joining handle leaves while the others listen to another table", () => {
141
+ it("joins again for the remaining handle's table, event and filter, and delivers its rows", async () => {
142
+ const statuses: ChannelStatus[] = []
143
+ const messages: Array<RealtimePayload<Record<string, unknown>>> = []
144
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
145
+ harness.realtime
146
+ .channel(CHANNEL)
147
+ .on("postgres_changes", { event: "INSERT", table: "messages", filter: "room=eq.1" }, (p) => messages.push(p))
148
+ .subscribe((s) => statuses.push(s))
149
+ await harness.settle()
150
+ harness.ackJoins()
151
+
152
+ a.unsubscribe()
153
+ const joins = subscribeFrames()
154
+ expect(joins).toHaveLength(2)
155
+ expect(joins[1]).toMatchObject({ schema: "public", table: "messages", event: "INSERT", filter: { room: "eq.1" } })
156
+ // A join on a channel already joined replaces it on the server; leaving first would drop the
157
+ // presence this socket tracks there.
158
+ expect(unsubscribeFrames()).toEqual([])
159
+
160
+ ackJoin(CHANNEL)
161
+ deliverInsert(1)
162
+ expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
163
+ expect(statuses).toEqual(["SUBSCRIBED", "SUBSCRIBING", "SUBSCRIBED"])
164
+ })
165
+
166
+ it("does not hand the new table's listeners a row that arrives before the new join is acknowledged", async () => {
167
+ const messages: Array<RealtimePayload<Record<string, unknown>>> = []
168
+ const a = harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "audit_log" }, () => {}).subscribe()
169
+ harness.realtime.channel(CHANNEL).on("postgres_changes", { event: "*", table: "messages" }, (p) => messages.push(p)).subscribe()
170
+ await harness.settle()
171
+ harness.ackJoins()
172
+
173
+ a.unsubscribe()
174
+ // Sent before the server took the new join: an audit_log row.
175
+ deliverInsert(1)
176
+ ackJoin(CHANNEL)
177
+ deliverInsert(2)
178
+ expect(messages.map((p) => p.new)).toEqual([{ id: 2 }])
179
+ })
180
+ })
181
+
182
+ /**
183
+ * A join sent with no row listener names no table, and the server reads one from the channel name.
184
+ * Rows were matched and labelled against whichever row listener came first instead, so a listener
185
+ * for another table added afterwards was handed the channel's rows under its own table's name.
186
+ */
187
+ describe("rows on a channel joined before any row listener", () => {
188
+ it("belong to the table the channel name gives, as the server reads it", async () => {
189
+ const invoices: Array<RealtimePayload<Record<string, unknown>>> = []
190
+ const orders: Array<RealtimePayload<Record<string, unknown>>> = []
191
+ const name = "public:orders"
192
+ const handle = harness.realtime.channel(name).onBroadcast("ping", () => {}).subscribe()
193
+ await harness.settle()
194
+ harness.ackJoins()
195
+
196
+ handle.on("postgres_changes", { event: "*", table: "invoices" }, (p) => invoices.push(p))
197
+ handle.on("postgres_changes", { event: "*", table: "orders" }, (p) => orders.push(p))
198
+ simulateServerMessage(harness.socket(), {
199
+ type: "change",
200
+ channel: name,
201
+ event: "INSERT",
202
+ payload: { old: null, new: { id: 1 } },
203
+ timestamp: "2026-10-28T00:00:00Z",
204
+ })
205
+
206
+ expect(invoices).toEqual([])
207
+ expect(orders.map((p) => [p.schema, p.table, p.new])).toEqual([["public", "orders", { id: 1 }]])
208
+ })
209
+ })
@@ -1,22 +1,47 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest"
2
- import { createClient } from "../src/index.js"
3
- import { fetchCalls, header, jsonResponse, mockFetch } from "./support/fetch-mock.js"
2
+ import { createClient, type Session } from "../src/index.js"
3
+ import { fetchCalls, header, jsonResponse, mockFetch, requestUrl } from "./support/fetch-mock.js"
4
+ import { fakeJwt } from "./support/jwt.js"
5
+
6
+ // A resend follows only a refresh that replaced a refused session token, so the caller is signed in.
7
+ const NOW = Math.floor(Date.now() / 1000)
8
+ const userJwt = (n: number): string => fakeJwt({ role: "authenticated", sub: "u1", exp: NOW + 3600, n })
9
+
10
+ const USER = { id: "u1", appMetadata: {}, userMetadata: {}, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }
11
+ const SESSION: Session = { accessToken: userJwt(1), tokenType: "bearer", expiresIn: 3600, refreshToken: "rt-1", user: USER }
12
+ const REFRESHED = {
13
+ access_token: userJwt(2),
14
+ refresh_token: "rt-2",
15
+ token_type: "bearer",
16
+ expires_in: 3600,
17
+ user: { id: "u1", app_metadata: {}, user_metadata: {}, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" },
18
+ }
4
19
 
5
20
  describe("rpc: the resend after a 401 is the same request", () => {
6
21
  beforeEach(() => vi.restoreAllMocks())
7
22
 
8
23
  it("keeps Content-Profile and Prefer on the second send", async () => {
9
- const fetch = mockFetch()
10
- .mockResolvedValueOnce(jsonResponse({ message: "JWT expired" }, 401))
11
- .mockResolvedValueOnce(jsonResponse(1, 200))
24
+ let refused = false
25
+ const fetch = mockFetch((input) => {
26
+ if (requestUrl(input).includes("/auth/v1/token")) return Promise.resolve(jsonResponse(REFRESHED))
27
+ if (refused) return Promise.resolve(jsonResponse(1, 200))
28
+ refused = true
29
+ return Promise.resolve(jsonResponse({ code: "PGRST303", message: "JWT expired" }, 401))
30
+ })
12
31
  vi.stubGlobal("fetch", fetch)
13
- const client = createClient({ url: "http://localhost:18473", anonKey: "anon", auth: { persistSession: false } })
32
+ const client = createClient({
33
+ url: "http://localhost:18473",
34
+ anonKey: "anon",
35
+ auth: { persistSession: false, autoRefreshToken: false },
36
+ initialSession: SESSION,
37
+ })
14
38
 
15
39
  const { error } = await client.rpc("publish", undefined, { schema: "supatype", count: "exact" })
16
40
 
17
41
  expect(error).toBeNull()
18
- expect(fetch).toHaveBeenCalledTimes(2)
19
- for (const { init } of fetchCalls(fetch)) {
42
+ const sends = fetchCalls(fetch).filter(({ url }) => url.includes("/rpc/publish"))
43
+ expect(sends).toHaveLength(2)
44
+ for (const { init } of sends) {
20
45
  expect(header(init, "Content-Profile")).toBe("supatype")
21
46
  expect(header(init, "Prefer")).toBe("count=exact")
22
47
  }