@supatype/client 0.9.1 → 0.10.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 (118) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +112 -72
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/CHANGELOG.md +123 -20
  5. package/README.md +18 -0
  6. package/dist/auth.d.ts +13 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +53 -13
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +4 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +2 -1
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/channel-watch.d.ts +42 -0
  15. package/dist/channel-watch.d.ts.map +1 -0
  16. package/dist/channel-watch.js +59 -0
  17. package/dist/channel-watch.js.map +1 -0
  18. package/dist/errors.d.ts +40 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +31 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/exact-values.d.ts +18 -5
  23. package/dist/exact-values.d.ts.map +1 -1
  24. package/dist/exact-values.js +76 -12
  25. package/dist/exact-values.js.map +1 -1
  26. package/dist/field-kinds-registry.d.ts +1 -1
  27. package/dist/field-kinds-registry.d.ts.map +1 -1
  28. package/dist/field-kinds-registry.js +20 -2
  29. package/dist/field-kinds-registry.js.map +1 -1
  30. package/dist/index.d.ts +7 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +6 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/latest-rows.d.ts +15 -0
  35. package/dist/latest-rows.d.ts.map +1 -1
  36. package/dist/latest-rows.js +14 -7
  37. package/dist/latest-rows.js.map +1 -1
  38. package/dist/public-env.d.ts +13 -0
  39. package/dist/public-env.d.ts.map +1 -0
  40. package/dist/public-env.js +23 -0
  41. package/dist/public-env.js.map +1 -0
  42. package/dist/query-cache.d.ts +2 -1
  43. package/dist/query-cache.d.ts.map +1 -1
  44. package/dist/query-cache.js.map +1 -1
  45. package/dist/query.d.ts +7 -0
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +12 -4
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime-refusals.d.ts +35 -0
  50. package/dist/realtime-refusals.d.ts.map +1 -0
  51. package/dist/realtime-refusals.js +73 -0
  52. package/dist/realtime-refusals.js.map +1 -0
  53. package/dist/realtime.d.ts +87 -8
  54. package/dist/realtime.d.ts.map +1 -1
  55. package/dist/realtime.js +304 -51
  56. package/dist/realtime.js.map +1 -1
  57. package/dist/runtime-env.d.ts +2 -0
  58. package/dist/runtime-env.d.ts.map +1 -1
  59. package/dist/runtime-env.js +45 -5
  60. package/dist/runtime-env.js.map +1 -1
  61. package/dist/table-subscription.d.ts +27 -11
  62. package/dist/table-subscription.d.ts.map +1 -1
  63. package/dist/table-subscription.js +159 -25
  64. package/dist/table-subscription.js.map +1 -1
  65. package/dist/types.d.ts +34 -1
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js.map +1 -1
  68. package/package.json +2 -2
  69. package/src/auth.ts +55 -12
  70. package/src/bindings.ts +4 -1
  71. package/src/channel-watch.ts +86 -0
  72. package/src/errors.ts +54 -0
  73. package/src/exact-values.ts +101 -13
  74. package/src/field-kinds-registry.ts +2 -3
  75. package/src/index.ts +14 -2
  76. package/src/latest-rows.ts +24 -7
  77. package/src/public-env.ts +22 -0
  78. package/src/query-cache.ts +2 -1
  79. package/src/query.ts +12 -4
  80. package/src/realtime-refusals.ts +100 -0
  81. package/src/realtime.ts +385 -56
  82. package/src/runtime-env.ts +53 -5
  83. package/src/table-subscription.ts +190 -32
  84. package/src/types.ts +40 -1
  85. package/tests/auth-restore-user.test.ts +84 -0
  86. package/tests/auth-sso.test.ts +32 -1
  87. package/tests/auth.test.ts +11 -0
  88. package/tests/channel-watch-private.test.ts +105 -0
  89. package/tests/channel-watch.test.ts +97 -0
  90. package/tests/exact-response.test.ts +101 -0
  91. package/tests/exact-values.test.ts +57 -0
  92. package/tests/examples-runtime-env.test.ts +135 -0
  93. package/tests/field-kinds-registry.test.ts +12 -0
  94. package/tests/helpers/close-event.ts +12 -0
  95. package/tests/helpers/fake-client.ts +38 -0
  96. package/tests/helpers/mock-websocket.ts +22 -0
  97. package/tests/helpers/reactive-options-binding.ts +99 -0
  98. package/tests/public-env.test.ts +43 -0
  99. package/tests/query-cache.test.ts +1 -1
  100. package/tests/query.test.ts +39 -2
  101. package/tests/realtime-connection.test.ts +228 -0
  102. package/tests/realtime-exact-values.test.ts +42 -0
  103. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  104. package/tests/realtime-private-channels.test.ts +377 -0
  105. package/tests/realtime-refusal-error.test.ts +80 -0
  106. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  107. package/tests/realtime-session-auth.test.ts +0 -1
  108. package/tests/realtime-shared-channel.test.ts +9 -27
  109. package/tests/realtime-typed-channels.test.ts +49 -0
  110. package/tests/runtime-env-expo.test.ts +58 -0
  111. package/tests/runtime-env.test.ts +49 -0
  112. package/tests/subscribe-frame.test.ts +48 -0
  113. package/tests/table-subscription-rows.test.ts +136 -0
  114. package/tests/table-subscription.test.ts +4 -3
  115. package/tsconfig.json +2 -1
  116. package/tsconfig.tsbuildinfo +1 -1
  117. package/type-tests/declared-channels.ts +30 -0
  118. package/type-tests/tsconfig.json +4 -0
@@ -9,7 +9,7 @@
9
9
 
10
10
  import { describe, it, expect, beforeEach, afterEach } from "vitest"
11
11
  import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
12
- import { sentFrames, simulateServerMessage } from "./helpers/mock-websocket.js"
12
+ import { ackNewestJoin, deliverInsert, sentFrames, simulateServerMessage, subscribeFrames } from "./helpers/mock-websocket.js"
13
13
  import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
14
14
 
15
15
  const CHANNEL = "x"
@@ -20,16 +20,6 @@ function unsubscribeFrames(): Array<Record<string, unknown>> {
20
20
  return sentFrames(harness.socket()).filter((frame) => frame["type"] === "unsubscribe" && frame["channel"] === CHANNEL)
21
21
  }
22
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
23
  beforeEach(() => {
34
24
  harness = createSocketSwapHarness()
35
25
  })
@@ -46,7 +36,7 @@ describe("two handles on one channel name", () => {
46
36
  harness.ackJoins()
47
37
 
48
38
  a.unsubscribe()
49
- deliverInsert(1)
39
+ deliverInsert(harness.socket(), CHANNEL, 1)
50
40
 
51
41
  expect(first).toEqual([])
52
42
  expect(second.map((p) => p.new)).toEqual([{ id: 1 }])
@@ -117,21 +107,13 @@ describe("rows on a channel whose joining handle has left", () => {
117
107
  harness.ackJoins()
118
108
 
119
109
  a.unsubscribe()
120
- deliverInsert(1)
110
+ deliverInsert(harness.socket(), CHANNEL, 1)
121
111
 
122
112
  expect(audit).toEqual([])
123
113
  expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
124
114
  })
125
115
  })
126
116
 
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
117
  /**
136
118
  * When the handle whose listener made the join leaves and no remaining listener is for that join,
137
119
  * the channel joins again for the oldest remaining listener. It used to stay registered for the
@@ -150,15 +132,15 @@ describe("a channel whose joining handle leaves while the others listen to anoth
150
132
  harness.ackJoins()
151
133
 
152
134
  a.unsubscribe()
153
- const joins = subscribeFrames()
135
+ const joins = subscribeFrames(harness.socket(), CHANNEL)
154
136
  expect(joins).toHaveLength(2)
155
137
  expect(joins[1]).toMatchObject({ schema: "public", table: "messages", event: "INSERT", filter: { room: "eq.1" } })
156
138
  // A join on a channel already joined replaces it on the server; leaving first would drop the
157
139
  // presence this socket tracks there.
158
140
  expect(unsubscribeFrames()).toEqual([])
159
141
 
160
- ackJoin(CHANNEL)
161
- deliverInsert(1)
142
+ ackNewestJoin(harness.socket(), CHANNEL)
143
+ deliverInsert(harness.socket(), CHANNEL, 1)
162
144
  expect(messages.map((p) => [p.table, p.new])).toEqual([["messages", { id: 1 }]])
163
145
  expect(statuses).toEqual(["SUBSCRIBED", "SUBSCRIBING", "SUBSCRIBED"])
164
146
  })
@@ -172,9 +154,9 @@ describe("a channel whose joining handle leaves while the others listen to anoth
172
154
 
173
155
  a.unsubscribe()
174
156
  // Sent before the server took the new join: an audit_log row.
175
- deliverInsert(1)
176
- ackJoin(CHANNEL)
177
- deliverInsert(2)
157
+ deliverInsert(harness.socket(), CHANNEL, 1)
158
+ ackNewestJoin(harness.socket(), CHANNEL)
159
+ deliverInsert(harness.socket(), CHANNEL, 2)
178
160
  expect(messages.map((p) => p.new)).toEqual([{ id: 2 }])
179
161
  })
180
162
  })
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Typed channel names: a declared pattern autocompletes as a template literal type, and every
3
+ * other string is still a valid name, since an `open` server admits it.
4
+ *
5
+ * Most of this file is checked by `tsc` (the package's typecheck script), not by vitest: a
6
+ * `@ts-expect-error` that stops being an error fails the typecheck.
7
+ */
8
+ import { describe, it, expect } from "vitest"
9
+ import type { ChannelName, DeclaredTopic, DeclaredTopics } from "../src/index.js"
10
+
11
+ interface Declared {
12
+ "lot:{id}": { params: { id: string } }
13
+ "lobby:*": { params: Record<string, never> }
14
+ "org:{org}:room:{n}": { params: { org: string; n: number } }
15
+ plain: { params: Record<string, never> }
16
+ }
17
+
18
+ type Topic = DeclaredTopics<Declared>
19
+
20
+ const ok = (topic: Topic): Topic => topic
21
+
22
+ describe("DeclaredTopics", () => {
23
+ it("accepts a topic built from each declared pattern", () => {
24
+ const topics = [
25
+ ok("lot:7f3c"),
26
+ ok("lobby:anything"),
27
+ ok("org:acme:room:12"),
28
+ ok("plain"),
29
+ ]
30
+ expect(topics).toHaveLength(4)
31
+ })
32
+
33
+ it("rejects a topic no declaration can match", () => {
34
+ // @ts-expect-error not a declared topic
35
+ ok("auction:1")
36
+ // @ts-expect-error an Integer parameter takes a number, not words
37
+ ok("org:acme:room:twelve")
38
+ // @ts-expect-error the literal prefix must be there
39
+ ok("other:7f3c")
40
+ expect(true).toBe(true)
41
+ })
42
+
43
+ it("is never for a project that declares nothing, so ChannelName stays an open string", () => {
44
+ const none: DeclaredTopics<Record<never, never>> extends never ? true : false = true
45
+ const open: ChannelName = "anything:at:all"
46
+ const declared: DeclaredTopic extends string ? true : false = true
47
+ expect([none, open, declared]).toEqual([true, "anything:at:all", true])
48
+ })
49
+ })
@@ -0,0 +1,58 @@
1
+ /**
2
+ * 0.9.2 release test (N-S14): an Expo web export with no values threw `MissingClientValuesError`
3
+ * telling the developer to add the script tag to `index.html`, which an Expo Router app does not
4
+ * have. Its page comes from `app/+html.tsx`, so that is the file the error names. The client tells
5
+ * an Expo page by `globalThis.expo`, which Expo's runtime sets on the web as on a phone; the CLI's
6
+ * `EXPO_PUBLIC_` names are read by the app's own code, which the client never sees.
7
+ */
8
+
9
+ import { afterEach, describe, expect, it, vi } from "vitest"
10
+ import { createClient, MissingClientValuesError } from "../src/index.js"
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllGlobals()
14
+ })
15
+
16
+ /** A page with no `/supatype-env.js` script and no `__SUPATYPE_ENV__`, Expo's when `expo` is set. */
17
+ function page(expo: boolean): void {
18
+ vi.stubGlobal("window", globalThis)
19
+ vi.stubGlobal("document", { scripts: [] })
20
+ if (expo) vi.stubGlobal("expo", { modules: {} })
21
+ vi.stubGlobal("fetch", vi.fn(() => Promise.reject(new Error("no request may be sent"))))
22
+ }
23
+
24
+ async function firstCallMessage(): Promise<string> {
25
+ try {
26
+ await createClient({}).from("posts").select()
27
+ } catch (err) {
28
+ if (err instanceof MissingClientValuesError) return err.message
29
+ throw err
30
+ }
31
+ throw new Error("expected the first call to fail")
32
+ }
33
+
34
+ describe("the missing-values error in an Expo app", () => {
35
+ it("names app/+html.tsx, not index.html", async () => {
36
+ page(true)
37
+ const message = await firstCallMessage()
38
+ expect(message).toContain("app/+html.tsx")
39
+ expect(message).toContain('<script src="/supatype-env.js" />')
40
+ expect(message).not.toContain("index.html")
41
+ expect(message).not.toContain("vite-ignore")
42
+ })
43
+
44
+ it("says a native build takes the values at build time, under Expo's names", async () => {
45
+ page(true)
46
+ const message = await firstCallMessage()
47
+ expect(message).toContain("EXPO_PUBLIC_SUPATYPE_URL")
48
+ expect(message).toContain("A native build has no page")
49
+ expect(message).toContain("supatype build -- <your build command>")
50
+ })
51
+
52
+ it("still names index.html in a page that is not Expo's", async () => {
53
+ page(false)
54
+ const message = await firstCallMessage()
55
+ expect(message).toContain('add <script src="/supatype-env.js" vite-ignore></script> to index.html')
56
+ expect(message).not.toContain("+html.tsx")
57
+ })
58
+ })
@@ -222,3 +222,52 @@ describe("the page's __SUPATYPE_ENV__", () => {
222
222
  expect(message).toContain("VITE_SUPATYPE_URL")
223
223
  })
224
224
  })
225
+
226
+ /**
227
+ * 0.9.1 release test RB2: the gateway now refuses a path with an empty part, so an address written
228
+ * with a trailing "/" (`SUPATYPE_URL=https://api.example.com/`) must not build `//rest/v1/...`.
229
+ */
230
+ describe("an address ending in /", () => {
231
+ const SERVICE_REQUESTS = FIRST_REQUESTS.filter(([label]) => label !== "a realtime connect")
232
+
233
+ /** Each request's path, from every service, for a client at `address`. */
234
+ async function pathsFor(client: () => SupatypeClient): Promise<string[]> {
235
+ const seen = captureRequests()
236
+ // Each answer is an empty list, which some reject after the request is sent: only the address counts.
237
+ for (const [, request] of SERVICE_REQUESTS) await Promise.resolve(request(client())).catch(() => undefined)
238
+ return seen.map((r) => r.url.slice(r.url.indexOf("/", "https://".length)))
239
+ }
240
+
241
+ it.each(["https://api.example.com/", "https://api.example.com//"])("is used without it when given: %s", async (url) => {
242
+ const paths = await pathsFor(() => createClient({ url, anonKey: "k" }))
243
+ expect(paths).toHaveLength(SERVICE_REQUESTS.length)
244
+ expect(paths.filter((path) => path.includes("//"))).toEqual([])
245
+ expect(createClient({ url, anonKey: "k" }).url).toBe("https://api.example.com")
246
+ })
247
+
248
+ it("is used without it when the page sets it", async () => {
249
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com/", anonKey: "k" })
250
+ const paths = await pathsFor(() => createClient({}))
251
+ expect(paths.filter((path) => path.includes("//"))).toEqual([])
252
+ expect(createClient({}).url).toBe("https://api.example.com")
253
+ })
254
+
255
+ it("keeps a base path the address has", async () => {
256
+ const paths = await pathsFor(() => createClient({ url: "https://example.com/api/", anonKey: "k" }))
257
+ expect(paths[0]).toMatch(/^\/api\/rest\/v1\/posts/)
258
+ })
259
+ })
260
+
261
+ describe("client.anonKey", () => {
262
+ it("is the key as given", () => {
263
+ expect(createClient({ url: "https://a.example.com", anonKey: "given-key" }).anonKey).toBe("given-key")
264
+ })
265
+
266
+ it("is empty until the page sets one, then the page's, read when asked", () => {
267
+ const client = createClient({ url: "", anonKey: undefined })
268
+ expect(client.anonKey).toBe("")
269
+
270
+ vi.stubGlobal("__SUPATYPE_ENV__", DEPLOYED)
271
+ expect(client.anonKey).toBe(DEPLOYED.anonKey)
272
+ })
273
+ })
@@ -102,6 +102,54 @@ describe("the subscribe frame", () => {
102
102
  // always carries a schema, that default overrode the "app" the server would have read.
103
103
  expect(subscribeFrames()[0]!["schema"]).toBe("app")
104
104
  })
105
+
106
+ it("joins public when a table is named and the channel name has a colon", async () => {
107
+ // 0.9.1 release test (RB4): the documented `.channel("post:42")` with `table: "comment"`
108
+ // took "post" from the channel name as the schema, joined `post.comment`, reported SUBSCRIBED
109
+ // and delivered nothing. The name is read as `schema:table` only when no table is given.
110
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
111
+ client
112
+ .channel("post:42")
113
+ .on("postgres_changes", { event: "INSERT", table: "comment", filter: "post_id=eq.42" }, () => {})
114
+ .subscribe()
115
+ await settle()
116
+
117
+ expect(subscribeFrames()[0]).toMatchObject({ channel: "post:42", schema: "public", table: "comment" })
118
+ })
119
+
120
+ it("keeps a schema the listener states, whatever the channel is called", async () => {
121
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
122
+ client
123
+ .channel("post:42")
124
+ .on("postgres_changes", { event: "*", schema: "app", table: "comment" }, () => {})
125
+ .subscribe()
126
+ await settle()
127
+
128
+ expect(subscribeFrames()[0]).toMatchObject({ schema: "app", table: "comment" })
129
+ })
130
+ })
131
+
132
+ /**
133
+ * 0.9.2 release test round 2 (R2-RB2): the server checks a join's table, and the frame names one on
134
+ * every join, the channel name's reading when no listener gives one. `room:probe` read as
135
+ * room.probe, so broadcast and presence on it were refused. The frame now says which joins want rows.
136
+ */
137
+ describe("whether the join asks for row changes", () => {
138
+ it("says so when a listener wants row changes", async () => {
139
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
140
+ client.channel("lobby-chat").on("postgres_changes", { event: "*", table: "chat_message" }, () => {}).subscribe()
141
+ await settle()
142
+ expect(subscribeFrames()[0]).toMatchObject({ table: "chat_message", changes: true })
143
+ })
144
+
145
+ it("does not, for a channel used only for broadcast and presence", async () => {
146
+ const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
147
+ client.channel("room:probe").onBroadcast("ping", () => {}).onPresence(() => {}).subscribe()
148
+ await settle()
149
+ const frame = subscribeFrames()[0]
150
+ expect(frame).toBeDefined()
151
+ expect(frame).toMatchObject({ changes: false })
152
+ })
105
153
  })
106
154
 
107
155
  describe("joining again after disconnect()", () => {
@@ -0,0 +1,136 @@
1
+ /**
2
+ * The rows a table subscription keeps: seeded from a read, upserted by key, and read again after a
3
+ * drop.
4
+ *
5
+ * `watchTable` started from an empty list and never read the table, and matched on `id` only for an
6
+ * update or a delete. So an UPDATE or DELETE of a row that existed before the subscription did
7
+ * nothing, an INSERT delivered twice listed the row twice, and anything changed while the socket was
8
+ * down was lost for good.
9
+ */
10
+
11
+ import { afterEach, beforeEach, describe, expect, it } from "vitest"
12
+ import { applyRowChange, watchTable } from "../src/bindings.js"
13
+ import type { RealtimePayload } from "../src/index.js"
14
+ import { simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
15
+ import { closeEvent } from "./helpers/close-event.js"
16
+ import { fakeClient } from "./helpers/fake-client.js"
17
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
18
+
19
+ interface Row {
20
+ id: number
21
+ v?: string
22
+ }
23
+
24
+ const change = (eventType: RealtimePayload<Row>["eventType"], row: Row | null, old: Row | null = null): RealtimePayload<Row> => ({
25
+ eventType,
26
+ new: row,
27
+ old,
28
+ schema: "public",
29
+ table: "task",
30
+ commitTimestamp: "2024-01-01T00:00:00Z",
31
+ })
32
+
33
+ describe("applyRowChange", () => {
34
+ it("adds the row of an UPDATE to a row it has not seen", () => {
35
+ expect(applyRowChange<Row>(null, change("UPDATE", { id: 1, v: "b" }, { id: 1 }))).toEqual([{ id: 1, v: "b" }])
36
+ })
37
+
38
+ it("lists a row once when its INSERT arrives twice, keeping the later one", () => {
39
+ const once = applyRowChange<Row>(null, change("INSERT", { id: 1, v: "a" }))
40
+ expect(applyRowChange(once, change("INSERT", { id: 1, v: "b" }))).toEqual([{ id: 1, v: "b" }])
41
+ })
42
+
43
+ it("leaves the rows alone for a DELETE of a row it has not seen", () => {
44
+ const rows = [{ id: 2, v: "x" }]
45
+ expect(applyRowChange(rows, change("DELETE", null, { id: 1 }))).toEqual(rows)
46
+ })
47
+
48
+ it("removes the row a DELETE names by its key", () => {
49
+ expect(applyRowChange([{ id: 1, v: "a" }, { id: 2, v: "b" }], change("DELETE", null, { id: 1 }))).toEqual([{ id: 2, v: "b" }])
50
+ })
51
+
52
+ it("matches on the key columns it is given, a composite one included", () => {
53
+ const rows = [{ org: 1, user: 1, role: "a" }, { org: 1, user: 2, role: "a" }]
54
+ const update: RealtimePayload<(typeof rows)[number]> = {
55
+ ...change("UPDATE", null),
56
+ new: { org: 1, user: 2, role: "b" },
57
+ old: { org: 1, user: 2, role: "a" },
58
+ }
59
+ expect(applyRowChange(rows, update, ["org", "user"])).toEqual([rows[0], { org: 1, user: 2, role: "b" }])
60
+ })
61
+ })
62
+
63
+ let harness: SocketSwapHarness
64
+ beforeEach(() => {
65
+ harness = createSocketSwapHarness()
66
+ })
67
+ afterEach(() => harness.restore())
68
+
69
+ const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5))
70
+
71
+ function watch(reads: Row[][], filter?: string): { seen: Row[][]; stop: () => void; filters: string[][] } {
72
+ const { client, filters } = fakeClient<Row>(harness, reads)
73
+ const seen: Row[][] = []
74
+ const stop = watchTable<Row>(client, "task", filter === undefined ? undefined : { filter }, {
75
+ rows: (rows) => seen.push(rows),
76
+ status: () => undefined,
77
+ })
78
+ return { seen, stop, filters }
79
+ }
80
+
81
+ describe("watchTable seeds its rows", () => {
82
+ it("reads the table once the join is acknowledged and shows those rows", async () => {
83
+ const { seen } = watch([[{ id: 1, v: "a" }]])
84
+ await harness.settle()
85
+ expect(seen).toEqual([])
86
+
87
+ harness.ackJoins()
88
+ await tick()
89
+ expect(seen).toEqual([[{ id: 1, v: "a" }]])
90
+ })
91
+
92
+ it("applies the subscription's filter to that read", async () => {
93
+ const { filters } = watch([[]], "room_id=eq.7,score=gte.10")
94
+ await harness.settle()
95
+ harness.ackJoins()
96
+ await tick()
97
+
98
+ expect(filters[0]).toEqual(["room_id eq 7", "score gte 10"])
99
+ })
100
+
101
+ it("updates a row that existed before it subscribed", async () => {
102
+ const { seen } = watch([[{ id: 1, v: "a" }]])
103
+ await harness.settle()
104
+ harness.ackJoins()
105
+ await tick()
106
+
107
+ simulateServerMessage(harness.socket(), {
108
+ type: "change",
109
+ channel: subscribedChannels(harness.socket())[0],
110
+ event: "UPDATE",
111
+ payload: { old: { id: 1 }, new: { id: 1, v: "b" } },
112
+ timestamp: "2024-01-01T00:00:00Z",
113
+ })
114
+
115
+ expect(seen[seen.length - 1]).toEqual([{ id: 1, v: "b" }])
116
+ })
117
+ })
118
+
119
+ describe("watchTable after a drop", () => {
120
+ it("reads the table again once the join is back, so a change made while down shows up", async () => {
121
+ const { seen } = watch([[{ id: 1, v: "a" }], [{ id: 1, v: "changed while down" }]])
122
+ await harness.settle()
123
+ harness.ackJoins()
124
+ await tick()
125
+ expect(seen[seen.length - 1]).toEqual([{ id: 1, v: "a" }])
126
+
127
+ harness.socket().onclose?.(closeEvent())
128
+ const before = harness.sockets.length
129
+ await new Promise((resolve) => setTimeout(resolve, 1200))
130
+ expect(harness.sockets.length).toBe(before + 1)
131
+ harness.ackJoins()
132
+ await tick()
133
+
134
+ expect(seen[seen.length - 1]).toEqual([{ id: 1, v: "changed while down" }])
135
+ })
136
+ })
@@ -9,6 +9,7 @@ import { describe, it, expect, afterEach } from "vitest"
9
9
  import { applyRowChange, subscriptionViewOf, watchTable, type SubscriptionView } from "../src/table-subscription.js"
10
10
  import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
11
11
  import { simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
12
+ import { fakeClient } from "./helpers/fake-client.js"
12
13
  import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
13
14
 
14
15
  interface Row {
@@ -69,7 +70,7 @@ describe("watchTable", () => {
69
70
  harness = createSocketSwapHarness()
70
71
  const rowsSeen: Row[][] = []
71
72
  const statuses: string[] = []
72
- const stop = watchTable<Row>(harness.realtime, "task", { event: "INSERT" }, {
73
+ const stop = watchTable<Row>(fakeClient<Row>(harness).client, "task", { event: "INSERT" }, {
73
74
  rows: (rows) => rowsSeen.push(rows),
74
75
  status: (view) => statuses.push(view.status),
75
76
  })
@@ -91,8 +92,8 @@ describe("watchTable", () => {
91
92
  it("gives two watchers of one table a channel each, as from(table).subscribe() does", async () => {
92
93
  harness = createSocketSwapHarness()
93
94
  const quiet = { rows: (): void => undefined, status: (): void => undefined }
94
- const first = watchTable<Row>(harness.realtime, "task", undefined, quiet)
95
- const second = watchTable<Row>(harness.realtime, "task", undefined, quiet)
95
+ const first = watchTable<Row>(fakeClient<Row>(harness).client, "task", undefined, quiet)
96
+ const second = watchTable<Row>(fakeClient<Row>(harness).client, "task", undefined, quiet)
96
97
  await harness.settle()
97
98
 
98
99
  const [a, b] = firstSocketChannels()
package/tsconfig.json CHANGED
@@ -4,7 +4,8 @@
4
4
  "outDir": "dist",
5
5
  "rootDir": "src",
6
6
  "composite": true,
7
- "lib": ["ES2022", "DOM"]
7
+ "lib": ["ES2022", "DOM"],
8
+ "noUnusedLocals": true
8
9
  },
9
10
  "include": ["../../ts-reset.d.ts", "src"]
10
11
  }