@supatype/client 0.9.2 → 0.10.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 (99) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +98 -75
  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 +4 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +38 -13
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +3 -0
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +1 -0
  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 +6 -2
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +5 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/public-env.d.ts +13 -0
  35. package/dist/public-env.d.ts.map +1 -0
  36. package/dist/public-env.js +23 -0
  37. package/dist/public-env.js.map +1 -0
  38. package/dist/query-cache.d.ts +2 -1
  39. package/dist/query-cache.d.ts.map +1 -1
  40. package/dist/query-cache.js.map +1 -1
  41. package/dist/query.js +1 -1
  42. package/dist/query.js.map +1 -1
  43. package/dist/realtime-refusals.d.ts +35 -0
  44. package/dist/realtime-refusals.d.ts.map +1 -0
  45. package/dist/realtime-refusals.js +73 -0
  46. package/dist/realtime-refusals.js.map +1 -0
  47. package/dist/realtime.d.ts +70 -2
  48. package/dist/realtime.d.ts.map +1 -1
  49. package/dist/realtime.js +198 -18
  50. package/dist/realtime.js.map +1 -1
  51. package/dist/runtime-env.d.ts +2 -0
  52. package/dist/runtime-env.d.ts.map +1 -1
  53. package/dist/runtime-env.js +5 -0
  54. package/dist/runtime-env.js.map +1 -1
  55. package/dist/table-subscription.d.ts +23 -9
  56. package/dist/table-subscription.d.ts.map +1 -1
  57. package/dist/table-subscription.js +155 -23
  58. package/dist/table-subscription.js.map +1 -1
  59. package/dist/types.d.ts +29 -1
  60. package/dist/types.d.ts.map +1 -1
  61. package/dist/types.js.map +1 -1
  62. package/package.json +2 -2
  63. package/src/auth.ts +40 -12
  64. package/src/bindings.ts +3 -0
  65. package/src/channel-watch.ts +86 -0
  66. package/src/errors.ts +54 -0
  67. package/src/exact-values.ts +101 -13
  68. package/src/field-kinds-registry.ts +2 -3
  69. package/src/index.ts +13 -1
  70. package/src/public-env.ts +22 -0
  71. package/src/query-cache.ts +2 -1
  72. package/src/query.ts +1 -1
  73. package/src/realtime-refusals.ts +100 -0
  74. package/src/realtime.ts +256 -20
  75. package/src/runtime-env.ts +6 -0
  76. package/src/table-subscription.ts +186 -30
  77. package/src/types.ts +35 -1
  78. package/tests/auth-restore-user.test.ts +84 -0
  79. package/tests/auth.test.ts +11 -0
  80. package/tests/channel-watch-private.test.ts +105 -0
  81. package/tests/channel-watch.test.ts +97 -0
  82. package/tests/exact-response.test.ts +101 -0
  83. package/tests/exact-values.test.ts +57 -0
  84. package/tests/field-kinds-registry.test.ts +12 -0
  85. package/tests/helpers/close-event.ts +12 -0
  86. package/tests/helpers/fake-client.ts +38 -0
  87. package/tests/public-env.test.ts +43 -0
  88. package/tests/query-cache.test.ts +1 -1
  89. package/tests/realtime-connection.test.ts +228 -0
  90. package/tests/realtime-exact-values.test.ts +42 -0
  91. package/tests/realtime-private-channels.test.ts +377 -0
  92. package/tests/realtime-refusal-error.test.ts +2 -1
  93. package/tests/realtime-typed-channels.test.ts +49 -0
  94. package/tests/runtime-env.test.ts +14 -0
  95. package/tests/table-subscription-rows.test.ts +136 -0
  96. package/tests/table-subscription.test.ts +4 -3
  97. package/tsconfig.tsbuildinfo +1 -1
  98. package/type-tests/declared-channels.ts +30 -0
  99. package/type-tests/tsconfig.json +4 -0
@@ -93,3 +93,104 @@ describe("parseRowsExactly", () => {
93
93
  expect(out.ok).toBe(true)
94
94
  })
95
95
  })
96
+
97
+ describe("parseRowsExactly with array columns", () => {
98
+ const arrays = {
99
+ version: 1 as const,
100
+ tables: { ledger: { ids: "bigint[]" as const, rates: "numeric[]" as const, grid: "bigint[]" as const } },
101
+ }
102
+
103
+ it("keeps a bigint[] past 2^53 in a list response", () => {
104
+ registerFieldKinds(arrays)
105
+ const out = parseRowsExactly('[{"ids":[9007199254740993,1,-9007199254740995]}]', "ledger")
106
+
107
+ expect(out.ok).toBe(true)
108
+ expect(out.ok && out.value).toEqual([{ ids: [9007199254740993n, 1n, -9007199254740995n] }])
109
+ })
110
+
111
+ it("keeps a bigint[] past 2^53 in a single-object response", () => {
112
+ registerFieldKinds(arrays)
113
+ const out = parseRowsExactly('{"ids":[9007199254740993]}', "ledger")
114
+
115
+ expect(out.ok).toBe(true)
116
+ expect(out.ok && out.value).toEqual({ ids: [9007199254740993n] })
117
+ })
118
+
119
+ it("keeps trailing zeros in a numeric[] as exact strings", () => {
120
+ registerFieldKinds(arrays)
121
+ const out = parseRowsExactly('[{"rates":[1.10,2.500,12345678901234567890.1234]}]', "ledger")
122
+
123
+ expect(out.ok).toBe(true)
124
+ expect(out.ok && out.value).toEqual([{ rates: ["1.10", "2.500", "12345678901234567890.1234"] }])
125
+ })
126
+
127
+ it("keeps a numeric[] in a single-object response", () => {
128
+ registerFieldKinds(arrays)
129
+ const out = parseRowsExactly('{"rates":[1.10]}', "ledger")
130
+
131
+ expect(out.ok && out.value).toEqual({ rates: ["1.10"] })
132
+ })
133
+
134
+ it("leaves nulls inside and around the array as null", () => {
135
+ registerFieldKinds(arrays)
136
+ const out = parseRowsExactly('[{"ids":[9007199254740993,null]},{"ids":null},{"ids":[]}]', "ledger")
137
+
138
+ expect(out.ok && out.value).toEqual([{ ids: [9007199254740993n, null] }, { ids: null }, { ids: [] }])
139
+ })
140
+
141
+ it("keeps a multi-dimensional bigint[]", () => {
142
+ registerFieldKinds(arrays)
143
+ const out = parseRowsExactly('[{"grid":[[9007199254740993,2],[3,null]]}]', "ledger")
144
+
145
+ expect(out.ok && out.value).toEqual([{ grid: [[9007199254740993n, 2n], [3n, null]] }])
146
+ })
147
+
148
+ it("leaves arrays in columns that are not registered exact kinds alone", () => {
149
+ registerFieldKinds(arrays)
150
+ const out = parseRowsExactly('[{"tags":[1,2],"ids":[1]}]', "ledger")
151
+
152
+ expect(out.ok && out.value).toEqual([{ tags: [1, 2], ids: [1n] }])
153
+ })
154
+
155
+ it("still reads a document with only the single kinds", () => {
156
+ registerFieldKinds({ version: 1, tables: { ledger: { views: "bigint" } } })
157
+ const out = parseRowsExactly('[{"views":9007199254740993,"ids":[1,2]}]', "ledger")
158
+
159
+ expect(out.ok && out.value).toEqual([{ views: 9007199254740993n, ids: [1, 2] }])
160
+ })
161
+ })
162
+
163
+ describe("parseRowsExactly with arrays", () => {
164
+ it("refuses an unregistered column whose array holds a lossy number, naming the column", () => {
165
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
166
+ const out = parseRowsExactly('[{"tags":[9007199254740993]}]', "job_post")
167
+
168
+ expect(out.ok).toBe(false)
169
+ expect(!out.ok && out.columns).toEqual(["tags"])
170
+ expect(!out.ok && out.message).toContain("tags")
171
+ })
172
+
173
+ it("passes an unregistered array that is safe", () => {
174
+ registerFieldKinds({ version: 1, tables: { job_post: { views: "bigint" } } })
175
+ const out = parseRowsExactly('[{"tags":[1,2,3]}]', "job_post")
176
+
177
+ expect(out.ok).toBe(true)
178
+ expect(out.ok && out.value).toEqual([{ tags: [1, 2, 3] }])
179
+ })
180
+
181
+ it("still protects a registered bigint[] column rather than refusing it", () => {
182
+ registerFieldKinds({ version: 1, tables: { job_post: { ids: "bigint[]" } } })
183
+ const out = parseRowsExactly('[{"ids":[9007199254740993,2]}]', "job_post")
184
+
185
+ expect(out.ok).toBe(true)
186
+ expect(out.ok && out.value).toEqual([{ ids: [9007199254740993n, 2n] }])
187
+ })
188
+
189
+ it("still protects a registered numeric[] column rather than refusing it", () => {
190
+ registerFieldKinds({ version: 1, tables: { job_post: { rates: "numeric[]" } } })
191
+ const out = parseRowsExactly('[{"rates":[12345678901234567890.1234]}]', "job_post")
192
+
193
+ expect(out.ok).toBe(true)
194
+ expect(out.ok && out.value).toEqual([{ rates: ["12345678901234567890.1234"] }])
195
+ })
196
+ })
@@ -158,3 +158,60 @@ describe("stringifyWithBigInts", () => {
158
158
  expect(stringifyWithBigInts({ rows: [{ views: 1n }] })).toBe('{"rows":[{"views":"1"}]}')
159
159
  })
160
160
  })
161
+
162
+ describe("array columns", () => {
163
+ const arrayFields: ExactFields = { ids: "bigint[]", rates: "numeric[]", views: "bigint" }
164
+
165
+ it("quotes every element of an exact-kind array, which JSON.parse would otherwise round", () => {
166
+ const body = '[{"ids":[9007199254740993,2],"rates":[1.10,0.0100]}]'
167
+ expect(JSON.parse(body)).toEqual([{ ids: [9007199254740992, 2], rates: [1.1, 0.01] }])
168
+
169
+ expect(JSON.parse(quoteExactNumbers(body, arrayFields))).toEqual([
170
+ { ids: ["9007199254740993", "2"], rates: ["1.10", "0.0100"] },
171
+ ])
172
+ })
173
+
174
+ it("quotes elements of nested arrays and leaves null alone", () => {
175
+ const body = '{"ids":[[9007199254740993,null],[-5]]}'
176
+ expect(JSON.parse(quoteExactNumbers(body, arrayFields))).toEqual({
177
+ ids: [["9007199254740993", null], ["-5"]],
178
+ })
179
+ })
180
+
181
+ it("does not touch arrays belonging to another column or to an embed", () => {
182
+ const body = '[{"other":[9007199254740993],"post":{"ids":[9007199254740993]}}]'
183
+ expect(quoteExactNumbers(body, arrayFields)).toBe(body)
184
+ })
185
+
186
+ it("does not treat a key inside an object in the array as the array column", () => {
187
+ const body = '[{"ids":[{"views":9007199254740993}]}]'
188
+ expect(quoteExactNumbers(body, arrayFields)).toBe(body)
189
+ })
190
+
191
+ it("converts bigint[] elements to bigint and keeps numeric[] as strings", () => {
192
+ const row = { ids: ["9007199254740993", null, ["7"]], rates: ["1.10"], views: "3" }
193
+ expect(coerceExactKinds([row], arrayFields)).toEqual([
194
+ { ids: [9007199254740993n, null, [7n]], rates: ["1.10"], views: 3n },
195
+ ])
196
+ })
197
+ })
198
+
199
+ describe("findLossyNumbers inside arrays", () => {
200
+ it("names a column whose array holds a literal that will not survive the parse", () => {
201
+ expect(findLossyNumbers('[{"ids":[9007199254740993]}]')).toEqual(["ids"])
202
+ })
203
+
204
+ it("names the column for an element at any depth, once", () => {
205
+ const body = '[{"grid":[[1,[9007199254740993]],[9007199254740995]]}]'
206
+ expect(findLossyNumbers(body)).toEqual(["grid"])
207
+ })
208
+
209
+ it("passes an array whose elements all round-trip", () => {
210
+ expect(findLossyNumbers('[{"ids":[1,2,9007199254740992,1.5,null,"x"]}]')).toEqual([])
211
+ })
212
+
213
+ it("applies the same rules to elements: trailing zeros pass, lost digits do not", () => {
214
+ expect(findLossyNumbers('[{"rates":[19.0000,1e2]}]')).toEqual([])
215
+ expect(findLossyNumbers('[{"rates":[12345678901234567890.1234]}]')).toEqual(["rates"])
216
+ })
217
+ })
@@ -78,3 +78,15 @@ describe("registerFieldKinds", () => {
78
78
  expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint" })
79
79
  })
80
80
  })
81
+
82
+ describe("array kinds", () => {
83
+ it("registers the array kinds a generated document declares", () => {
84
+ registerFieldKinds({ version: 1, tables: { ledger: { ids: "bigint[]", rates: "numeric[]" } } })
85
+ expect(registeredFieldsFor("ledger")).toEqual({ ids: "bigint[]", rates: "numeric[]" })
86
+ })
87
+
88
+ it("ignores a kind it does not know without dropping the ones it does", () => {
89
+ registerFieldKinds({ version: 1, tables: { ledger: { ids: "bigint[]", odd: "uuid[]" } } })
90
+ expect(registeredFieldsFor("ledger")).toEqual({ ids: "bigint[]" })
91
+ })
92
+ })
@@ -0,0 +1,12 @@
1
+ /**
2
+ * A CloseEvent for the suites that drive a socket's `onclose` by hand.
3
+ *
4
+ * Node has no CloseEvent global, and the client never reads the event, so this builds the same
5
+ * shape from a plain Event plus the three CloseEvent fields. No assertion needed: the result is
6
+ * structurally a CloseEvent.
7
+ *
8
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
9
+ */
10
+ export function closeEvent(code = 1006, reason = ""): CloseEvent {
11
+ return Object.assign(new Event("close"), { code, reason, wasClean: false })
12
+ }
@@ -0,0 +1,38 @@
1
+ import type { AnyClient } from "../../src/index.js"
2
+ import type { SocketSwapHarness } from "./socket-swap.js"
3
+
4
+ /**
5
+ * A client for `watchTable`: the harness's realtime client, and a `from(table)` whose reads answer
6
+ * from a queue of row lists and record the filter conditions they were given.
7
+ *
8
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
9
+ */
10
+ function isAnyClient(candidate: unknown): candidate is AnyClient {
11
+ return typeof candidate === "object" && candidate !== null && "realtime" in candidate && "from" in candidate
12
+ }
13
+
14
+ export function fakeClient<TRow>(
15
+ harness: SocketSwapHarness,
16
+ reads: TRow[][] = [],
17
+ ): { client: AnyClient; filters: string[][] } {
18
+ const filters: string[][] = []
19
+ const from = (): unknown => {
20
+ const calls: string[] = []
21
+ filters.push(calls)
22
+ const query: Record<string, unknown> = {
23
+ select: () => query,
24
+ then: (resolve: (answer: { data: TRow[]; error: null }) => void) => resolve({ data: reads.shift() ?? [], error: null }),
25
+ }
26
+ for (const op of ["eq", "neq", "gt", "gte", "lt", "lte"]) {
27
+ query[op] = (column: string, value: unknown) => {
28
+ calls.push(`${column} ${op} ${String(value)}`)
29
+ return query
30
+ }
31
+ }
32
+ return query
33
+ }
34
+ // The stand-in has only what `watchTable` touches, so it is checked as the client at this one place.
35
+ const client: unknown = { realtime: harness.realtime, from }
36
+ if (!isAnyClient(client)) throw new Error("the fake client lost a member watchTable needs")
37
+ return { client, filters }
38
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `publicEnv("NAME")` reads one of the site's own public values from the page's
3
+ * `window.__SUPATYPE_ENV__.env`, which `/supatype-env.js` sets beside the address and anon key.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it, vi } from "vitest"
7
+ import { publicEnv } from "../src/index.js"
8
+
9
+ afterEach(() => {
10
+ vi.unstubAllGlobals()
11
+ })
12
+
13
+ describe("publicEnv", () => {
14
+ it("reads a value the page's script set", () => {
15
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com", anonKey: "k", env: { STRIPE_PK: "pk_live_1" } })
16
+ expect(publicEnv("STRIPE_PK")).toBe("pk_live_1")
17
+ })
18
+
19
+ it("is undefined for a name the site did not set", () => {
20
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com", anonKey: "k", env: { A: "1" } })
21
+ expect(publicEnv("B")).toBeUndefined()
22
+ })
23
+
24
+ it("is undefined before the script ran, and when the server answered with a fault", () => {
25
+ expect(publicEnv("A")).toBeUndefined()
26
+ vi.stubGlobal("__SUPATYPE_ENV__", { error: "public env unavailable" })
27
+ expect(publicEnv("A")).toBeUndefined()
28
+ })
29
+
30
+ it("ignores a value that is not a string, and a name on the prototype", () => {
31
+ vi.stubGlobal("__SUPATYPE_ENV__", { env: { N: 5, O: { x: 1 } } })
32
+ expect(publicEnv("N")).toBeUndefined()
33
+ expect(publicEnv("O")).toBeUndefined()
34
+ expect(publicEnv("toString")).toBeUndefined()
35
+ expect(publicEnv("constructor")).toBeUndefined()
36
+ })
37
+
38
+ it("reads the page again each call, since the script may load after the module", () => {
39
+ expect(publicEnv("A")).toBeUndefined()
40
+ vi.stubGlobal("__SUPATYPE_ENV__", { env: { A: "late" } })
41
+ expect(publicEnv("A")).toBe("late")
42
+ })
43
+ })
@@ -82,7 +82,7 @@ describe("QueryBuilder.cache", () => {
82
82
 
83
83
  const r2 = await qb
84
84
  expect(r2.data).toEqual([{ id: 1 }])
85
- expect(r2.meta?.cacheStatus).toBe("HIT")
85
+ expect(r2.meta?.cacheStatus).toBe("CLIENT")
86
86
  expect(tableCalls()).toBe(1)
87
87
  })
88
88
 
@@ -0,0 +1,228 @@
1
+ /**
2
+ * The connection-level signal: `isConnected` and `onConnectionChange`, and the reconnect backoff.
3
+ *
4
+ * A channel's status cannot tell a first connect from a reconnect after a drop (both read
5
+ * SUBSCRIBING), so a page that wants to refetch what it missed needs the socket's own state.
6
+ */
7
+
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
9
+ import { RealtimeClient, type RealtimeConnectionState } from "../src/realtime.js"
10
+ import { closeEvent } from "./helpers/close-event.js"
11
+ import { createMockWebSocketClass, type MockWebSocketInstance } from "./helpers/mock-websocket.js"
12
+
13
+ let instances: MockWebSocketInstance[]
14
+ let realtime: RealtimeClient
15
+
16
+ beforeEach(() => {
17
+ const mock = createMockWebSocketClass()
18
+ instances = mock.instances
19
+ vi.stubGlobal("WebSocket", mock.MockWebSocket)
20
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: "Bearer t" }))
21
+ })
22
+
23
+ afterEach(() => {
24
+ realtime.disconnect()
25
+ vi.useRealTimers()
26
+ vi.unstubAllGlobals()
27
+ })
28
+
29
+ /** Node has no CloseEvent; the client never reads the event. */
30
+ const dropEvent = (): CloseEvent => closeEvent()
31
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
32
+ const newest = (): MockWebSocketInstance => {
33
+ const last = instances[instances.length - 1]
34
+ if (last === undefined) throw new Error("no socket has been opened")
35
+ return last
36
+ }
37
+
38
+ function record(): RealtimeConnectionState[] {
39
+ const seen: RealtimeConnectionState[] = []
40
+ realtime.onConnectionChange((state) => seen.push(state))
41
+ return seen
42
+ }
43
+
44
+ describe("isConnected and onConnectionChange", () => {
45
+ it("is disconnected before anything subscribes", () => {
46
+ expect(realtime.isConnected).toBe(false)
47
+ expect(realtime.connectionState).toBe("disconnected")
48
+ })
49
+
50
+ it("reports connecting, then connected, when the first channel subscribes", async () => {
51
+ const seen = record()
52
+ realtime.channel("public:task").subscribe(() => {})
53
+ await settle()
54
+
55
+ expect(seen).toEqual(["connecting", "connected"])
56
+ expect(realtime.isConnected).toBe(true)
57
+ })
58
+
59
+ it("reports a drop as connecting, and connected again once the socket is back", async () => {
60
+ realtime.channel("public:task").subscribe(() => {})
61
+ await settle()
62
+ const seen = record()
63
+
64
+ newest().onclose?.(dropEvent())
65
+ expect(seen).toEqual(["connecting"])
66
+ expect(realtime.isConnected).toBe(false)
67
+
68
+ await vi.waitFor(() => expect(seen).toEqual(["connecting", "connected"]), { timeout: 3000 })
69
+ expect(realtime.isConnected).toBe(true)
70
+ })
71
+
72
+ it("reports disconnected on an explicit disconnect", async () => {
73
+ realtime.channel("public:task").subscribe(() => {})
74
+ await settle()
75
+ const seen = record()
76
+
77
+ realtime.disconnect()
78
+ expect(seen).toEqual(["disconnected"])
79
+ expect(realtime.isConnected).toBe(false)
80
+ })
81
+
82
+ it("reports connecting, not disconnected, across the re-authentication swap", async () => {
83
+ let token = "anon"
84
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: `Bearer ${token}` }))
85
+ realtime.channel("public:task").subscribe(() => {})
86
+ await settle()
87
+ const seen = record()
88
+
89
+ token = "user"
90
+ await realtime.reauthenticate()
91
+ await settle()
92
+
93
+ expect(seen).toEqual(["connecting", "connected"])
94
+ })
95
+
96
+ it("stops calling a listener once it unsubscribes, and ignores a second unsubscribe", async () => {
97
+ const seen: RealtimeConnectionState[] = []
98
+ const off = realtime.onConnectionChange((state) => seen.push(state))
99
+ off()
100
+ off()
101
+ realtime.channel("public:task").subscribe(() => {})
102
+ await settle()
103
+
104
+ expect(seen).toEqual([])
105
+ })
106
+
107
+ it("keeps notifying the others when one listener throws", async () => {
108
+ const seen: RealtimeConnectionState[] = []
109
+ realtime.onConnectionChange(() => {
110
+ throw new Error("listener bug")
111
+ })
112
+ realtime.onConnectionChange((state) => seen.push(state))
113
+ realtime.channel("public:task").subscribe(() => {})
114
+ await settle()
115
+
116
+ expect(seen).toEqual(["connecting", "connected"])
117
+ })
118
+
119
+ it("does not change what a channel reports", async () => {
120
+ const statuses: string[] = []
121
+ realtime.channel("public:task").subscribe((status) => statuses.push(status))
122
+ await settle()
123
+ newest().onclose?.(dropEvent())
124
+
125
+ expect(statuses).toEqual(["SUBSCRIBING"])
126
+ })
127
+ })
128
+
129
+ describe("reconnect backoff", () => {
130
+ it("doubles from one second and holds at 30 seconds", async () => {
131
+ vi.useFakeTimers()
132
+ // A socket that never opens, so the attempt counter is never reset.
133
+ const dead: MockWebSocketInstance[] = []
134
+ class DeadSocket {
135
+ static OPEN = 1
136
+ static CONNECTING = 0
137
+ static CLOSED = 3
138
+ readyState = 0
139
+ onopen = null
140
+ onclose: ((event: CloseEvent) => void) | null = null
141
+ onmessage = null
142
+ onerror = null
143
+ send = vi.fn<(data: string) => void>()
144
+ close = vi.fn<() => void>()
145
+ constructor(readonly url: string) {
146
+ dead.push(this)
147
+ }
148
+ }
149
+ vi.stubGlobal("WebSocket", DeadSocket)
150
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: "Bearer t" }))
151
+ const spy = vi.spyOn(globalThis, "setTimeout")
152
+
153
+ realtime.channel("public:task").subscribe(() => {})
154
+ await vi.advanceTimersByTimeAsync(0)
155
+ const delays: number[] = []
156
+ for (let i = 0; i < 10; i++) {
157
+ const before = spy.mock.calls.length
158
+ dead[dead.length - 1]?.onclose?.(dropEvent())
159
+ const delay = spy.mock.calls.slice(before).map((c) => Number(c[1])).find((d) => d >= 1000)
160
+ delays.push(delay ?? -1)
161
+ await vi.advanceTimersByTimeAsync(delay ?? 0)
162
+ }
163
+
164
+ expect(delays).toEqual([1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000, 30000, 30000])
165
+ })
166
+ })
167
+
168
+ describe("a socket that fails before it opens and never closes", () => {
169
+ // Node's built-in WebSocket, against a gateway answering 502 while realtime restarts, fires
170
+ // error and then nothing: readyState stays CONNECTING. Waiting for a close that never comes
171
+ // left the client counting that socket as live, so it never tried again (seen on 0.9.3).
172
+ it("drops the socket on the error and reconnects", async () => {
173
+ realtime.channel("public:task").subscribe(() => {})
174
+ await settle()
175
+ const seen = record()
176
+ const first = newest()
177
+ first.readyState = 0
178
+ first.onerror?.(new Event("error"))
179
+
180
+ expect(seen).toEqual(["connecting"])
181
+ await vi.waitFor(() => expect(instances.length).toBe(2), { timeout: 3000 })
182
+ await vi.waitFor(() => expect(seen).toEqual(["connecting", "connected"]), { timeout: 3000 })
183
+ })
184
+
185
+ it("leaves an open socket's error to its close", async () => {
186
+ realtime.channel("public:task").subscribe(() => {})
187
+ await settle()
188
+ const seen = record()
189
+ newest().onerror?.(new Event("error"))
190
+ await settle()
191
+
192
+ expect(seen).toEqual([])
193
+ expect(instances.length).toBe(1)
194
+ })
195
+ })
196
+
197
+ describe("a socket that never finishes its handshake", () => {
198
+ // Seen on 0.9.3 self-host: realtime restarted under a held socket, the new one stayed
199
+ // CONNECTING with no error and no close, and the client waited on it for good.
200
+ it("is given up after the connect timeout and replaced", async () => {
201
+ vi.useFakeTimers()
202
+ const made: Array<{ readyState: number; close: () => void }> = []
203
+ class SilentSocket {
204
+ static OPEN = 1
205
+ static CONNECTING = 0
206
+ static CLOSED = 3
207
+ readyState = 0
208
+ onopen = null
209
+ onclose = null
210
+ onmessage = null
211
+ onerror = null
212
+ send = vi.fn<(data: string) => void>()
213
+ close = vi.fn<() => void>()
214
+ constructor(readonly url: string) {
215
+ made.push(this)
216
+ }
217
+ }
218
+ vi.stubGlobal("WebSocket", SilentSocket)
219
+ realtime = new RealtimeClient("ws://localhost:4000/realtime", async () => ({ Authorization: "Bearer t" }))
220
+ realtime.channel("public:task").subscribe(() => {})
221
+ await vi.advanceTimersByTimeAsync(0)
222
+ expect(made.length).toBe(1)
223
+
224
+ await vi.advanceTimersByTimeAsync(11_000)
225
+ expect(made[0]?.close).toHaveBeenCalled()
226
+ expect(made.length).toBe(2)
227
+ })
228
+ })
@@ -157,3 +157,45 @@ describe("a change from a table with nothing exact", () => {
157
157
  expect(row?.["externalId"]).toBe(9007199254740992)
158
158
  })
159
159
  })
160
+
161
+ describe("a change carrying array columns of exact values", () => {
162
+ it("gives a bigint[] column native bigints, past 2^53 and nested", async () => {
163
+ const row = await deliver(
164
+ changeFrame(
165
+ { ids: ["9007199254740993", "1", null], grid: [["1", "9007199254740995"]] },
166
+ { ids: "bigint[]", grid: "bigint[]" },
167
+ ),
168
+ )
169
+ expect(row?.["ids"]).toEqual([9007199254740993n, 1n, null])
170
+ expect(row?.["grid"]).toEqual([[1n, 9007199254740995n]])
171
+ })
172
+
173
+ it("leaves a numeric[] as exact strings", async () => {
174
+ const row = await deliver(changeFrame({ rates: ["1.10", "2.500"] }, { rates: "numeric[]" }))
175
+ expect(row?.["rates"]).toEqual(["1.10", "2.500"])
176
+ })
177
+ })
178
+
179
+ describe("a change naming a kind this client does not know", () => {
180
+ it("delivers the frame with the unknown column as sent", async () => {
181
+ // A newer service can name a kind this client predates. Dropping the whole frame would lose a
182
+ // change over one column, so the kind is ignored and the value passes through untouched.
183
+ const row = await deliver(
184
+ changeFrame({ id: "a", tag: "9007199254740993" }, { tag: "quantum" }),
185
+ )
186
+ expect(row).toEqual({ id: "a", tag: "9007199254740993" })
187
+ })
188
+
189
+ it("still coerces the kinds it knows in the same frame", async () => {
190
+ const row = await deliver(
191
+ changeFrame(
192
+ { id: "a", externalId: "9007199254740993", ids: ["1", "2"], rates: ["1.10"], tag: "x" },
193
+ { externalId: "bigint", ids: "bigint[]", rates: "numeric[]", tag: "uuid[]" },
194
+ ),
195
+ )
196
+ expect(row?.["externalId"]).toBe(9007199254740993n)
197
+ expect(row?.["ids"]).toEqual([1n, 2n])
198
+ expect(row?.["rates"]).toEqual(["1.10"])
199
+ expect(row?.["tag"]).toBe("x")
200
+ })
201
+ })