@supatype/client 0.3.6 → 0.7.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 (205) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +58 -31
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/dist/auth-redirect.d.ts +48 -0
  6. package/dist/auth-redirect.d.ts.map +1 -0
  7. package/dist/auth-redirect.js +70 -0
  8. package/dist/auth-redirect.js.map +1 -0
  9. package/dist/auth.d.ts +78 -4
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +373 -274
  12. package/dist/auth.js.map +1 -1
  13. package/dist/bindings.d.ts +16 -0
  14. package/dist/bindings.d.ts.map +1 -0
  15. package/dist/bindings.js +13 -0
  16. package/dist/bindings.js.map +1 -0
  17. package/dist/caller-types.d.ts +18 -0
  18. package/dist/caller-types.d.ts.map +1 -0
  19. package/dist/caller-types.js +22 -0
  20. package/dist/caller-types.js.map +1 -0
  21. package/dist/draft-create.d.ts +12 -0
  22. package/dist/draft-create.d.ts.map +1 -0
  23. package/dist/draft-create.js +47 -0
  24. package/dist/draft-create.js.map +1 -0
  25. package/dist/draft-models-registry.d.ts +27 -0
  26. package/dist/draft-models-registry.d.ts.map +1 -0
  27. package/dist/draft-models-registry.js +61 -0
  28. package/dist/draft-models-registry.js.map +1 -0
  29. package/dist/error-codes-doc.d.ts +1 -1
  30. package/dist/error-codes-doc.d.ts.map +1 -1
  31. package/dist/error-codes-doc.js +42 -34
  32. package/dist/error-codes-doc.js.map +1 -1
  33. package/dist/errors.d.ts +102 -60
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +69 -28
  36. package/dist/errors.js.map +1 -1
  37. package/dist/exact-response.d.ts.map +1 -1
  38. package/dist/exact-response.js +2 -1
  39. package/dist/exact-response.js.map +1 -1
  40. package/dist/exact-values.d.ts +2 -0
  41. package/dist/exact-values.d.ts.map +1 -1
  42. package/dist/exact-values.js +12 -10
  43. package/dist/exact-values.js.map +1 -1
  44. package/dist/fetch-with-retry.d.ts +21 -6
  45. package/dist/fetch-with-retry.d.ts.map +1 -1
  46. package/dist/fetch-with-retry.js +67 -53
  47. package/dist/fetch-with-retry.js.map +1 -1
  48. package/dist/field-kinds-registry.d.ts +11 -3
  49. package/dist/field-kinds-registry.d.ts.map +1 -1
  50. package/dist/field-kinds-registry.js +10 -6
  51. package/dist/field-kinds-registry.js.map +1 -1
  52. package/dist/filters.d.ts +51 -0
  53. package/dist/filters.d.ts.map +1 -0
  54. package/dist/filters.js +117 -0
  55. package/dist/filters.js.map +1 -0
  56. package/dist/generated-client.d.ts +7 -0
  57. package/dist/generated-client.d.ts.map +1 -0
  58. package/dist/generated-client.js +7 -0
  59. package/dist/generated-client.js.map +1 -0
  60. package/dist/graphql-document.d.ts +39 -0
  61. package/dist/graphql-document.d.ts.map +1 -0
  62. package/dist/graphql-document.js +228 -0
  63. package/dist/graphql-document.js.map +1 -0
  64. package/dist/graphql-json.d.ts +56 -0
  65. package/dist/graphql-json.d.ts.map +1 -0
  66. package/dist/graphql-json.js +220 -0
  67. package/dist/graphql-json.js.map +1 -0
  68. package/dist/graphql-transport.d.ts +28 -0
  69. package/dist/graphql-transport.d.ts.map +1 -0
  70. package/dist/graphql-transport.js +77 -0
  71. package/dist/graphql-transport.js.map +1 -0
  72. package/dist/index.d.ts +103 -40
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +153 -157
  75. package/dist/index.js.map +1 -1
  76. package/dist/json.d.ts +61 -0
  77. package/dist/json.d.ts.map +1 -0
  78. package/dist/json.js +83 -0
  79. package/dist/json.js.map +1 -0
  80. package/dist/jwt.d.ts +16 -0
  81. package/dist/jwt.d.ts.map +1 -0
  82. package/dist/jwt.js +37 -0
  83. package/dist/jwt.js.map +1 -0
  84. package/dist/live-preview.d.ts +23 -0
  85. package/dist/live-preview.d.ts.map +1 -0
  86. package/dist/live-preview.js +28 -0
  87. package/dist/live-preview.js.map +1 -0
  88. package/dist/mutation-request.d.ts +17 -0
  89. package/dist/mutation-request.d.ts.map +1 -0
  90. package/dist/mutation-request.js +41 -0
  91. package/dist/mutation-request.js.map +1 -0
  92. package/dist/preview.d.ts.map +1 -1
  93. package/dist/preview.js +8 -6
  94. package/dist/preview.js.map +1 -1
  95. package/dist/query-cache.d.ts.map +1 -1
  96. package/dist/query-cache.js +19 -13
  97. package/dist/query-cache.js.map +1 -1
  98. package/dist/query.d.ts +108 -29
  99. package/dist/query.d.ts.map +1 -1
  100. package/dist/query.js +294 -224
  101. package/dist/query.js.map +1 -1
  102. package/dist/realtime.d.ts +20 -2
  103. package/dist/realtime.d.ts.map +1 -1
  104. package/dist/realtime.js +105 -12
  105. package/dist/realtime.js.map +1 -1
  106. package/dist/select-types.d.ts +99 -0
  107. package/dist/select-types.d.ts.map +1 -0
  108. package/dist/select-types.js +2 -0
  109. package/dist/select-types.js.map +1 -0
  110. package/dist/storage.d.ts +81 -11
  111. package/dist/storage.d.ts.map +1 -1
  112. package/dist/storage.js +129 -37
  113. package/dist/storage.js.map +1 -1
  114. package/dist/table-subscription.d.ts +69 -0
  115. package/dist/table-subscription.d.ts.map +1 -0
  116. package/dist/table-subscription.js +93 -0
  117. package/dist/table-subscription.js.map +1 -0
  118. package/dist/types.d.ts +84 -5
  119. package/dist/types.d.ts.map +1 -1
  120. package/dist/types.js +6 -1
  121. package/dist/types.js.map +1 -1
  122. package/package.json +6 -2
  123. package/src/auth-redirect.ts +90 -0
  124. package/src/auth.ts +421 -280
  125. package/src/bindings.ts +22 -0
  126. package/src/caller-types.ts +27 -0
  127. package/src/draft-create.ts +51 -0
  128. package/src/draft-models-registry.ts +81 -0
  129. package/src/error-codes-doc.ts +44 -35
  130. package/src/errors.ts +72 -28
  131. package/src/exact-response.ts +2 -1
  132. package/src/exact-values.ts +16 -9
  133. package/src/fetch-with-retry.ts +80 -70
  134. package/src/field-kinds-registry.ts +22 -9
  135. package/src/filters.ts +133 -0
  136. package/src/generated-client.ts +6 -0
  137. package/src/graphql-document.ts +234 -0
  138. package/src/graphql-json.ts +243 -0
  139. package/src/graphql-transport.ts +97 -0
  140. package/src/index.ts +272 -201
  141. package/src/json.ts +117 -0
  142. package/src/jwt.ts +37 -0
  143. package/src/live-preview.ts +37 -0
  144. package/src/mutation-request.ts +66 -0
  145. package/src/preview.ts +9 -11
  146. package/src/query-cache.ts +19 -16
  147. package/src/query.ts +389 -270
  148. package/src/realtime.ts +116 -13
  149. package/src/select-types.ts +184 -0
  150. package/src/storage.ts +214 -43
  151. package/src/table-subscription.ts +160 -0
  152. package/src/types.ts +90 -5
  153. package/tests/auth-error-codes.test.ts +53 -0
  154. package/tests/auth-errors.test.ts +84 -0
  155. package/tests/auth-events.test.ts +136 -0
  156. package/tests/auth-url-session.test.ts +204 -0
  157. package/tests/auth.test.ts +122 -26
  158. package/tests/count.test.ts +60 -0
  159. package/tests/data-plane-auth.test.ts +21 -46
  160. package/tests/draft-insert.integration.test.ts +118 -0
  161. package/tests/draft-insert.test.ts +225 -0
  162. package/tests/draft-profile.test.ts +55 -84
  163. package/tests/draft-update.integration.test.ts +122 -0
  164. package/tests/draft-update.test.ts +174 -0
  165. package/tests/dynamic-headers.test.ts +45 -0
  166. package/tests/entry-points.test.ts +42 -0
  167. package/tests/exact-response.test.ts +4 -4
  168. package/tests/exact-values.test.ts +14 -25
  169. package/tests/field-kinds-registry.test.ts +3 -3
  170. package/tests/filters.test.ts +146 -0
  171. package/tests/graphql-json.test.ts +199 -0
  172. package/tests/helpers/mock-websocket.ts +44 -11
  173. package/tests/helpers/oauth-binding.ts +92 -0
  174. package/tests/helpers/signup-binding.ts +73 -0
  175. package/tests/helpers/socket-swap.ts +139 -0
  176. package/tests/mfa-totp-integration.test.ts +13 -20
  177. package/tests/postgrest-error-codes.test.ts +85 -0
  178. package/tests/query-cache.test.ts +116 -117
  179. package/tests/query.test.ts +29 -31
  180. package/tests/rate-limit-integration.test.ts +4 -12
  181. package/tests/realtime-exact-values.test.ts +2 -4
  182. package/tests/realtime-presence.test.ts +75 -0
  183. package/tests/realtime-session-auth.test.ts +2 -4
  184. package/tests/realtime-swap-status.test.ts +62 -0
  185. package/tests/retry-integration.test.ts +3 -8
  186. package/tests/retry-policy.test.ts +166 -0
  187. package/tests/rpc-resend.test.ts +24 -0
  188. package/tests/server-bodies.test.ts +139 -0
  189. package/tests/serverless.test.ts +2 -2
  190. package/tests/signed-url-absolute.test.ts +2 -5
  191. package/tests/storage-object-shape.test.ts +101 -0
  192. package/tests/storage-quota-integration.test.ts +3 -2
  193. package/tests/storage-reference-url.test.ts +51 -0
  194. package/tests/storage-upload-browser.test.ts +71 -0
  195. package/tests/storage-upload-limit-integration.test.ts +12 -22
  196. package/tests/subscribe-frame.test.ts +5 -11
  197. package/tests/support/fetch-mock.ts +64 -0
  198. package/tests/support/storage-object.ts +37 -0
  199. package/tests/table-subscribe.test.ts +13 -13
  200. package/tests/table-subscription.test.ts +105 -0
  201. package/tests/table-transport.test.ts +94 -0
  202. package/tests/tsconfig.json +1 -1
  203. package/tests/types.test.ts +153 -1
  204. package/tsconfig.json +1 -1
  205. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,71 @@
1
+ /**
2
+ * An upload from a browser file input sends the file's bytes, as the file's type, untouched.
3
+ *
4
+ * Found in manual testing: a profile picture uploaded from the kitchen-sink Account screen was
5
+ * stored as 0 bytes. The cause was the file on disk (a 0-byte `test.jpg`), not the client, but the
6
+ * browser path had no test: every upload test here sent a string or a Buffer from Node. These pin
7
+ * what the browser path relies on, a `File` handed to `fetch` as the body, read by nothing first,
8
+ * typed from `File.type` and carrying every byte.
9
+ */
10
+ import { describe, expect, it } from "vitest"
11
+ import { StorageClient } from "../src/storage.js"
12
+ import type { RequestTransport } from "../src/fetch-with-retry.js"
13
+
14
+ const URL_BASE = "http://localhost:18473/storage/v1"
15
+ const JPEG_BYTES = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0xff, 0xd9])
16
+
17
+ interface Sent {
18
+ url: string
19
+ method: string | undefined
20
+ headers: Headers
21
+ body: BodyInit | null | undefined
22
+ }
23
+
24
+ /** A transport that records the request and answers as the storage service does. */
25
+ function recording(): { transport: RequestTransport; sent: Sent[] } {
26
+ const sent: Sent[] = []
27
+ const transport: RequestTransport = async (url, init) => {
28
+ sent.push({ url, method: init.method, headers: new Headers(init.headers), body: init.body })
29
+ return new Response(JSON.stringify({ Key: "speaker-headshots/avatars/a.jpg" }), { status: 200 })
30
+ }
31
+ return { transport, sent }
32
+ }
33
+
34
+ function bucket(transport: RequestTransport) {
35
+ return new StorageClient(URL_BASE, () => Promise.resolve({ apikey: "anon" }), transport).from("speaker-headshots")
36
+ }
37
+
38
+ describe("BucketClient.upload with a browser File", () => {
39
+ it("sends the File itself as the body, with every byte still in it", async () => {
40
+ const { transport, sent } = recording()
41
+ const file = new File([JPEG_BYTES], "avatar.jpg", { type: "image/jpeg" })
42
+
43
+ const { error } = await bucket(transport).upload("avatars/a.jpg", file, { upsert: true })
44
+
45
+ expect(error).toBeNull()
46
+ expect(sent).toHaveLength(1)
47
+ expect(sent[0]!.method).toBe("POST")
48
+ expect(sent[0]!.url).toBe(`${URL_BASE}/object/speaker-headshots/avatars/a.jpg`)
49
+ expect(sent[0]!.body).toBe(file)
50
+ // What fetch would put on the wire for that body.
51
+ const wire = new Uint8Array(await new Response(sent[0]!.body).arrayBuffer())
52
+ expect(wire).toEqual(JPEG_BYTES)
53
+ })
54
+
55
+ it("types the request from File.type and keeps x-upsert", async () => {
56
+ const { transport, sent } = recording()
57
+ await bucket(transport).upload("avatars/a.jpg", new File([JPEG_BYTES], "a.jpg", { type: "image/jpeg" }), {
58
+ upsert: true,
59
+ })
60
+ expect(sent[0]!.headers.get("Content-Type")).toBe("image/jpeg")
61
+ expect(sent[0]!.headers.get("x-upsert")).toBe("true")
62
+ })
63
+
64
+ it("sends a Blob's bytes too, typed by the caller", async () => {
65
+ const { transport, sent } = recording()
66
+ const blob = new Blob([JPEG_BYTES], { type: "image/jpeg" })
67
+ await bucket(transport).upload("avatars/b.jpg", blob, { contentType: "image/jpeg" })
68
+ expect(sent[0]!.headers.get("Content-Type")).toBe("image/jpeg")
69
+ expect(new Uint8Array(await new Response(sent[0]!.body).arrayBuffer())).toEqual(JPEG_BYTES)
70
+ })
71
+ })
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { describe, it, expect, vi, beforeEach } from "vitest"
8
8
  import { StorageClient } from "../src/storage.js"
9
+ import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
9
10
 
10
11
  // ─── Helpers ─────────────────────────────────────────────────────────────────
11
12
 
@@ -22,17 +23,8 @@ function createMockBlob(sizeBytes: number): Blob {
22
23
  return new Blob([data])
23
24
  }
24
25
 
25
- function mockFetchResponse(
26
- status: number,
27
- body: unknown,
28
- ok?: boolean,
29
- ): ReturnType<typeof vi.fn> {
30
- return vi.fn().mockResolvedValue({
31
- ok: ok ?? (status >= 200 && status < 300),
32
- status,
33
- json: vi.fn().mockResolvedValue(body),
34
- headers: new Headers(),
35
- })
26
+ function mockFetchResponse(status: number, body: unknown): FetchMock {
27
+ return fetchReturning(body, status)
36
28
  }
37
29
 
38
30
  // ─── Tests ───────────────────────────────────────────────────────────────────
@@ -73,7 +65,7 @@ describe("Task 92: File upload size limit integration", () => {
73
65
  message: "Payload too large: file exceeds the maximum upload size of 50MB",
74
66
  statusCode: 413,
75
67
  error: "Payload Too Large",
76
- }, false))
68
+ }))
77
69
 
78
70
  const client = freshClient()
79
71
  const blob = createMockBlob(100 * 1024 * 1024) // 100 MB
@@ -88,7 +80,7 @@ describe("Task 92: File upload size limit integration", () => {
88
80
  it("error message mentions the size limit", async () => {
89
81
  vi.stubGlobal("fetch", mockFetchResponse(413, {
90
82
  message: "Payload too large: file exceeds the maximum upload size of 50MB",
91
- }, false))
83
+ }))
92
84
 
93
85
  const client = freshClient()
94
86
  const { error } = await client.from("uploads").upload("huge.zip", createMockBlob(200 * 1024 * 1024))
@@ -99,7 +91,7 @@ describe("Task 92: File upload size limit integration", () => {
99
91
  it("returns 413 for just-over-limit file", async () => {
100
92
  vi.stubGlobal("fetch", mockFetchResponse(413, {
101
93
  message: "Payload too large: file exceeds the maximum upload size of 50MB",
102
- }, false))
94
+ }))
103
95
 
104
96
  const client = freshClient()
105
97
  const blob = createMockBlob(50 * 1024 * 1024 + 1) // 50 MB + 1 byte
@@ -118,9 +110,9 @@ describe("Task 92: File upload size limit integration", () => {
118
110
  const client = freshClient()
119
111
  await client.from("bucket").upload("file.txt", createMockBlob(100))
120
112
 
121
- const [url, opts] = fetchSpy.mock.calls[0] as [string, RequestInit]
113
+ const { url, init } = fetchCall(fetchSpy)
122
114
  expect(url).toBe(`${STORAGE_URL}/object/bucket/file.txt`)
123
- expect(opts.method).toBe("POST")
115
+ expect(init.method).toBe("POST")
124
116
  })
125
117
 
126
118
  it("includes content-type header", async () => {
@@ -132,8 +124,7 @@ describe("Task 92: File upload size limit integration", () => {
132
124
  contentType: "image/jpeg",
133
125
  })
134
126
 
135
- const [, opts] = fetchSpy.mock.calls[0] as [string, RequestInit]
136
- expect((opts.headers as Record<string, string>)["Content-Type"]).toBe("image/jpeg")
127
+ expect(header(fetchCall(fetchSpy).init, "Content-Type")).toBe("image/jpeg")
137
128
  })
138
129
 
139
130
  it("sends x-upsert header when upsert option is true", async () => {
@@ -143,8 +134,7 @@ describe("Task 92: File upload size limit integration", () => {
143
134
  const client = freshClient()
144
135
  await client.from("bucket").upload("file.txt", createMockBlob(100), { upsert: true })
145
136
 
146
- const [, opts] = fetchSpy.mock.calls[0] as [string, RequestInit]
147
- expect((opts.headers as Record<string, string>)["x-upsert"]).toBe("true")
137
+ expect(header(fetchCall(fetchSpy).init, "x-upsert")).toBe("true")
148
138
  })
149
139
  })
150
140
 
@@ -152,7 +142,7 @@ describe("Task 92: File upload size limit integration", () => {
152
142
  it("handles 400 Bad Request", async () => {
153
143
  vi.stubGlobal("fetch", mockFetchResponse(400, {
154
144
  message: "Invalid file name",
155
- }, false))
145
+ }))
156
146
 
157
147
  const client = freshClient()
158
148
  const { error } = await client.from("bucket").upload("", createMockBlob(100))
@@ -164,7 +154,7 @@ describe("Task 92: File upload size limit integration", () => {
164
154
  it("handles 401 Unauthorized", async () => {
165
155
  vi.stubGlobal("fetch", mockFetchResponse(401, {
166
156
  message: "Unauthorized",
167
- }, false))
157
+ }))
168
158
 
169
159
  const client = freshClient()
170
160
  const { error } = await client.from("private-bucket").upload("secret.doc", createMockBlob(100))
@@ -15,6 +15,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
15
15
  import { RealtimeClient } from "../src/realtime.js"
16
16
  import {
17
17
  createMockWebSocketClass,
18
+ sentFrames,
18
19
  simulateServerMessage,
19
20
  type MockWebSocketInstance,
20
21
  } from "./helpers/mock-websocket.js"
@@ -22,26 +23,21 @@ import {
22
23
  const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
23
24
 
24
25
  let instances: MockWebSocketInstance[]
25
- let originalWebSocket: typeof WebSocket
26
26
 
27
27
  beforeEach(() => {
28
28
  const mock = createMockWebSocketClass()
29
29
  instances = mock.instances
30
- originalWebSocket = globalThis.WebSocket
31
- globalThis.WebSocket = mock.MockWebSocket
30
+ vi.stubGlobal("WebSocket", mock.MockWebSocket)
32
31
  })
33
32
 
34
33
  afterEach(() => {
35
- globalThis.WebSocket = originalWebSocket
34
+ vi.unstubAllGlobals()
36
35
  vi.restoreAllMocks()
37
36
  })
38
37
 
39
38
  /** Every subscribe frame the client put on the socket. */
40
39
  function subscribeFrames(): Array<Record<string, unknown>> {
41
- return instances
42
- .flatMap((i) => i.send.mock.calls.map((c) => c[0] as string))
43
- .map((raw) => JSON.parse(raw) as Record<string, unknown>)
44
- .filter((m) => m["type"] === "subscribe")
40
+ return instances.flatMap((i) => sentFrames(i)).filter((m) => m["type"] === "subscribe")
45
41
  }
46
42
 
47
43
  describe("the subscribe frame", () => {
@@ -129,9 +125,7 @@ describe("joining again after disconnect()", () => {
129
125
  await settle()
130
126
 
131
127
  expect(instances).toHaveLength(2)
132
- const onNewSocket = instances[1]!.send.mock.calls
133
- .map((c) => JSON.parse(c[0] as string) as Record<string, unknown>)
134
- .filter((m) => m["type"] === "subscribe")
128
+ const onNewSocket = sentFrames(instances[1]!).filter((m) => m["type"] === "subscribe")
135
129
  expect(onNewSocket).toHaveLength(1)
136
130
  })
137
131
  })
@@ -0,0 +1,64 @@
1
+ import { vi, type Mock } from "vitest"
2
+ import { isJsonObject } from "../../src/json.js"
3
+
4
+ /**
5
+ * A typed stand-in for `fetch`, and readers for what it was called with.
6
+ *
7
+ * The suites used to build `vi.fn()` (whose calls are `any[]`) and then assert each call into the
8
+ * shape they expected. Typed as `fetch`, a call is `[input, init?]` and nothing needs asserting: a
9
+ * header is read the way the server reads it (case-insensitively), and a body is parsed and checked.
10
+ *
11
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
12
+ */
13
+ export type FetchMock = Mock<typeof fetch>
14
+
15
+ /** A fetch mock, answering with `impl` when given one. */
16
+ export function mockFetch(impl?: typeof fetch): FetchMock {
17
+ return impl === undefined ? vi.fn<typeof fetch>() : vi.fn<typeof fetch>(impl)
18
+ }
19
+
20
+ /** Statuses a Response may not carry a body with. */
21
+ const NULL_BODY_STATUSES = new Set([101, 204, 205, 304])
22
+
23
+ /** A JSON response, as a server would send it. */
24
+ export function jsonResponse(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
25
+ const text = NULL_BODY_STATUSES.has(status) ? null : JSON.stringify(body)
26
+ return new Response(text, { status, headers: { "Content-Type": "application/json", ...headers } })
27
+ }
28
+
29
+ /** A fetch that answers every call with a fresh copy of the same JSON response. */
30
+ export function fetchReturning(body: unknown, status = 200, headers: Record<string, string> = {}): FetchMock {
31
+ return vi.fn<typeof fetch>(() => Promise.resolve(jsonResponse(body, status, headers)))
32
+ }
33
+
34
+ /** The `n`th call's URL and init, as `fetch` received them. Throws when there was no such call. */
35
+ export function fetchCall(fetch: FetchMock, n = 0): { url: string; init: RequestInit } {
36
+ const call = fetch.mock.calls[n]
37
+ if (call === undefined) throw new Error(`fetch was called ${fetch.mock.calls.length} times, not ${n + 1}`)
38
+ const [input, init] = call
39
+ return { url: requestUrl(input), init: init ?? {} }
40
+ }
41
+
42
+ /** Every call's URL and init, oldest first. */
43
+ export function fetchCalls(fetch: FetchMock): Array<{ url: string; init: RequestInit }> {
44
+ return fetch.mock.calls.map(([input, init]) => ({ url: requestUrl(input), init: init ?? {} }))
45
+ }
46
+
47
+ /** The URL a `fetch` input names. */
48
+ export function requestUrl(input: RequestInfo | URL): string {
49
+ if (typeof input === "string") return input
50
+ return input instanceof URL ? input.href : input.url
51
+ }
52
+
53
+ /** One request header, matched case-insensitively as a server matches it; null when absent. */
54
+ export function header(init: RequestInit, name: string): string | null {
55
+ return new Headers(init.headers).get(name)
56
+ }
57
+
58
+ /** The request's body parsed as a JSON object. Throws when it is not one. */
59
+ export function jsonBody(init: RequestInit): Record<string, unknown> {
60
+ if (typeof init.body !== "string") throw new Error("the request body is not a string")
61
+ const body = JSON.parse(init.body)
62
+ if (!isJsonObject(body)) throw new Error(`the request body is not a JSON object: ${init.body}`)
63
+ return body
64
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * A list entry exactly as the storage service sends one: the entry in
3
+ * packages/storage/tests/fixtures/list-entry.json, the contract every storage server is checked
4
+ * against. storage-object-shape.test.ts keeps the two equal. The suites that need a list answer
5
+ * build from this, so a change to the shape is made in one place.
6
+ *
7
+ * Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
8
+ */
9
+ export const LISTED = {
10
+ id: "c385ffde-42b3-45e5-8981-863515e0dbf6",
11
+ bucket_id: "avatars",
12
+ name: "shape-f9619cfd-f645-4f8d-bb42-3ed73bb0a36d.txt",
13
+ owner: "7ea80d5c-e81e-48e7-8f27-2c2218ac42ac",
14
+ metadata: { size: 4, mimetype: "text/plain" },
15
+ created_at: "2026-10-18T07:52:09.909Z",
16
+ updated_at: "2026-10-18T07:52:09.909Z",
17
+ last_accessed_at: "2026-10-18T07:52:09.909Z",
18
+ size: 4,
19
+ mimetype: "text/plain",
20
+ }
21
+
22
+ /** A subfolder as a list answers it: the `folder` entry of the same contract file. */
23
+ export const FOLDER = {
24
+ id: null,
25
+ bucket_id: "avatars",
26
+ name: "photos",
27
+ owner: null,
28
+ metadata: null,
29
+ created_at: null,
30
+ updated_at: null,
31
+ last_accessed_at: null,
32
+ size: null,
33
+ mimetype: null,
34
+ }
35
+
36
+ /** The same entry with every nullable field null, as for an object stored with no owner or metadata. */
37
+ export const UNOWNED = { ...LISTED, owner: null, metadata: null, size: null, mimetype: null }
@@ -14,7 +14,9 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
14
14
  import { createClient } from "../src/index.js"
15
15
  import type { RealtimePayload } from "../src/realtime.js"
16
16
  import {
17
+ channelOf,
17
18
  createMockWebSocketClass,
19
+ sentFrames,
18
20
  simulateServerMessage,
19
21
  type MockWebSocketInstance,
20
22
  } from "./helpers/mock-websocket.js"
@@ -39,14 +41,12 @@ function newClient(): ReturnType<typeof createClient> {
39
41
  }
40
42
 
41
43
  /** Every frame the client put on any socket, parsed. */
42
- function sentFrames(): Array<Record<string, unknown>> {
43
- return instances
44
- .flatMap((i) => i.send.mock.calls.map((c) => c[0] as string))
45
- .map((raw) => JSON.parse(raw) as Record<string, unknown>)
44
+ function allFrames(): Array<Record<string, unknown>> {
45
+ return instances.flatMap((i) => sentFrames(i))
46
46
  }
47
47
 
48
48
  function framesOfType(type: string): Array<Record<string, unknown>> {
49
- return sentFrames().filter((m) => m["type"] === type)
49
+ return allFrames().filter((m) => m["type"] === type)
50
50
  }
51
51
 
52
52
  /** The only socket opened so far. A second one would mean a subscribe orphaned the first. */
@@ -90,7 +90,7 @@ describe("from(table).subscribe() alone", () => {
90
90
  expect(frame["schema"]).toBe("public")
91
91
  expect(frame["event"]).toBe("*")
92
92
 
93
- simulateServerMessage(ws, changeOn(frame["channel"] as string, "INSERT", { id: 1 }))
93
+ simulateServerMessage(ws, changeOn(channelOf(frame), "INSERT", { id: 1 }))
94
94
  expect(seen).toHaveLength(1)
95
95
  expect(seen[0]!.eventType).toBe("INSERT")
96
96
  expect(seen[0]!.table).toBe("post")
@@ -113,7 +113,7 @@ describe("from(table).subscribe() alone", () => {
113
113
  expect(frame["filter"]).toEqual({ slug: "eq.hello" })
114
114
  expect(frame["event"]).toBe("INSERT")
115
115
 
116
- const channel = frame["channel"] as string
116
+ const channel = channelOf(frame)
117
117
  simulateServerMessage(ws, changeOn(channel, "UPDATE", { id: 1 }))
118
118
  simulateServerMessage(ws, changeOn(channel, "INSERT", { id: 2 }))
119
119
  expect(seen.map((p) => p.new)).toEqual([{ id: 2 }])
@@ -157,7 +157,7 @@ describe("the status callback on the returned channel", () => {
157
157
  const ws = onlySocket()
158
158
  const frames = framesOfType("subscribe")
159
159
  expect(frames).toHaveLength(1)
160
- simulateServerMessage(ws, ack(frames[0]!["channel"] as string))
160
+ simulateServerMessage(ws, ack(channelOf(frames[0])))
161
161
  expect(statuses).toEqual(["SUBSCRIBED"])
162
162
  })
163
163
 
@@ -169,7 +169,7 @@ describe("the status callback on the returned channel", () => {
169
169
  await settle()
170
170
 
171
171
  const ws = onlySocket()
172
- simulateServerMessage(ws, ack(framesOfType("subscribe")[0]!["channel"] as string))
172
+ simulateServerMessage(ws, ack(channelOf(framesOfType("subscribe")[0])))
173
173
 
174
174
  const statuses: string[] = []
175
175
  sub.channel.subscribe((s) => statuses.push(s))
@@ -197,8 +197,8 @@ describe("two subscriptions to the same table on one client", () => {
197
197
  expect(frames[0]!["channel"]).not.toBe(frames[1]!["channel"])
198
198
 
199
199
  // The server addresses each change to the subscription it matched.
200
- simulateServerMessage(ws, changeOn(frames[0]!["channel"] as string, "INSERT", { slug: "a" }))
201
- simulateServerMessage(ws, changeOn(frames[1]!["channel"] as string, "INSERT", { slug: "b" }))
200
+ simulateServerMessage(ws, changeOn(channelOf(frames[0]), "INSERT", { slug: "a" }))
201
+ simulateServerMessage(ws, changeOn(channelOf(frames[1]), "INSERT", { slug: "b" }))
202
202
  expect(first).toEqual([{ slug: "a" }])
203
203
  expect(second).toEqual([{ slug: "b" }])
204
204
  })
@@ -219,7 +219,7 @@ describe("two subscriptions to the same table on one client", () => {
219
219
  { type: "unsubscribe", channel: frameA!["channel"] },
220
220
  ])
221
221
  expect(ws.close).not.toHaveBeenCalled()
222
- simulateServerMessage(ws, changeOn(frameB!["channel"] as string, "INSERT", { id: 7 }))
222
+ simulateServerMessage(ws, changeOn(channelOf(frameB), "INSERT", { id: 7 }))
223
223
  expect(second).toEqual([{ id: 7 }])
224
224
  })
225
225
 
@@ -239,7 +239,7 @@ describe("two subscriptions to the same table on one client", () => {
239
239
  const ws = onlySocket()
240
240
  const frames = framesOfType("subscribe")
241
241
  expect(frames).toHaveLength(2)
242
- const tableChannel = frames.find((f) => f["channel"] !== "public:post")!["channel"] as string
242
+ const tableChannel = channelOf(frames.find((f) => f["channel"] !== "public:post"))
243
243
 
244
244
  raw.unsubscribe()
245
245
  expect(ws.close).not.toHaveBeenCalled()
@@ -0,0 +1,105 @@
1
+ /**
2
+ * `watchTable`, the channel wiring the Vue, Svelte and Solid bindings share.
3
+ *
4
+ * Each binding's own suite drives it through a sign-in; these cover what that does not: every
5
+ * channel status, and the row merge on update and delete.
6
+ */
7
+
8
+ import { describe, it, expect, afterEach } from "vitest"
9
+ import { applyRowChange, subscriptionViewOf, watchTable, type SubscriptionView } from "../src/table-subscription.js"
10
+ import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
11
+ import { simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
12
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
13
+
14
+ interface Row {
15
+ id: number
16
+ title: string
17
+ }
18
+
19
+ function change(eventType: "INSERT" | "UPDATE" | "DELETE", row: Row): RealtimePayload<Row> {
20
+ return {
21
+ eventType,
22
+ new: eventType === "DELETE" ? null : row,
23
+ old: eventType === "INSERT" ? null : row,
24
+ schema: "public",
25
+ table: "task",
26
+ commitTimestamp: "2026-01-01T00:00:00Z",
27
+ }
28
+ }
29
+
30
+ describe("subscriptionViewOf", () => {
31
+ it.each<[ChannelStatus, SubscriptionView["status"], boolean]>([
32
+ ["SUBSCRIBING", "connecting", false],
33
+ ["SUBSCRIBED", "connected", false],
34
+ ["CLOSED", "disconnected", false],
35
+ ["CHANNEL_ERROR", "error", true],
36
+ ["TIMED_OUT", "error", true],
37
+ ])("%s reads %s", (channelStatus, status, hasError) => {
38
+ const view = subscriptionViewOf(channelStatus)
39
+ expect(view.status).toBe(status)
40
+ expect(view.error !== null).toBe(hasError)
41
+ })
42
+ })
43
+
44
+ describe("applyRowChange", () => {
45
+ it("appends an insert, replaces an update and drops a delete, matched on id", () => {
46
+ let rows = applyRowChange<Row>(null, change("INSERT", { id: 1, title: "a" }))
47
+ rows = applyRowChange(rows, change("INSERT", { id: 2, title: "b" }))
48
+ rows = applyRowChange(rows, change("UPDATE", { id: 1, title: "a2" }))
49
+ expect(rows).toEqual([{ id: 1, title: "a2" }, { id: 2, title: "b" }])
50
+
51
+ rows = applyRowChange(rows, change("DELETE", { id: 2, title: "b" }))
52
+ expect(rows).toEqual([{ id: 1, title: "a2" }])
53
+ })
54
+ })
55
+
56
+ describe("watchTable", () => {
57
+ let harness: SocketSwapHarness
58
+
59
+ afterEach(() => harness.restore())
60
+
61
+ /** The channel each subscribe frame on the first socket named, in order. */
62
+ function firstSocketChannels(): string[] {
63
+ const socket = harness.sockets[0]
64
+ if (socket === undefined) throw new Error("no socket has been opened")
65
+ return subscribedChannels(socket)
66
+ }
67
+
68
+ it("hands the binding each change's rows and each status", async () => {
69
+ harness = createSocketSwapHarness()
70
+ const rowsSeen: Row[][] = []
71
+ const statuses: string[] = []
72
+ const stop = watchTable<Row>(harness.realtime, "task", { event: "INSERT" }, {
73
+ rows: (rows) => rowsSeen.push(rows),
74
+ status: (view) => statuses.push(view.status),
75
+ })
76
+ await harness.settle()
77
+ harness.ackJoins()
78
+ simulateServerMessage(harness.sockets[0]!, {
79
+ type: "change",
80
+ channel: firstSocketChannels()[0],
81
+ event: "INSERT",
82
+ payload: { old: null, new: { id: 1, title: "a" } },
83
+ timestamp: "2026-01-01T00:00:00Z",
84
+ })
85
+ stop()
86
+
87
+ expect(statuses).toEqual(["connected"])
88
+ expect(rowsSeen).toEqual([[{ id: 1, title: "a" }]])
89
+ })
90
+
91
+ it("gives two watchers of one table a channel each, as from(table).subscribe() does", async () => {
92
+ harness = createSocketSwapHarness()
93
+ 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)
96
+ await harness.settle()
97
+
98
+ const [a, b] = firstSocketChannels()
99
+ expect(a).toMatch(/^public:task:\d+$/)
100
+ expect(b).toMatch(/^public:task:\d+$/)
101
+ expect(a).not.toBe(b)
102
+ first()
103
+ second()
104
+ })
105
+ })
@@ -0,0 +1,94 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { createClient } from "../src/index.js"
3
+
4
+ const URL_BASE = "http://localhost:18473"
5
+
6
+ function rowsResponse(rows: unknown[], status = 200): Response {
7
+ return new Response(JSON.stringify(rows), { status })
8
+ }
9
+
10
+ /** A fetch that never answers, and gives up only when its signal is aborted. */
11
+ function hangingFetch(): ReturnType<typeof vi.fn> {
12
+ return vi.fn((_url: string, init?: RequestInit) =>
13
+ new Promise<Response>((_resolve, reject) => {
14
+ init?.signal?.addEventListener("abort", () => {
15
+ const err = new Error("aborted")
16
+ err.name = "AbortError"
17
+ reject(err)
18
+ })
19
+ }),
20
+ )
21
+ }
22
+
23
+ function client(opts: { timeout?: number; retry?: boolean } = {}) {
24
+ return createClient({ url: URL_BASE, anonKey: "anon", ...opts })
25
+ }
26
+
27
+ describe("config.timeout applies to table queries and mutations", () => {
28
+ beforeEach(() => vi.restoreAllMocks())
29
+
30
+ it("a select that never answers ends in a timeout error", { timeout: 2000 }, async () => {
31
+ vi.stubGlobal("fetch", hangingFetch())
32
+ const { data, error } = await client({ timeout: 50 }).from("posts").select("*")
33
+ expect(data).toBeNull()
34
+ expect(error?.code).toBe("NETWORK_TIMEOUT")
35
+ })
36
+
37
+ it("an insert that never answers ends in a timeout error", { timeout: 2000 }, async () => {
38
+ vi.stubGlobal("fetch", hangingFetch())
39
+ const { error } = await client({ timeout: 50 }).from("posts").insert({ title: "x", user_id: "u1" })
40
+ expect(error?.code).toBe("NETWORK_TIMEOUT")
41
+ })
42
+
43
+ it("an update that never answers ends in a timeout error", { timeout: 2000 }, async () => {
44
+ vi.stubGlobal("fetch", hangingFetch())
45
+ const { error } = await client({ timeout: 50 }).from("posts").update({ title: "x" }).eq("id", 1)
46
+ expect(error?.code).toBe("NETWORK_TIMEOUT")
47
+ })
48
+ })
49
+
50
+ describe("config.retry applies to reads only", () => {
51
+ beforeEach(() => vi.restoreAllMocks())
52
+
53
+ it("a select retries a transient 503 and returns the rows", { timeout: 5000 }, async () => {
54
+ const fetch = vi.fn()
55
+ .mockResolvedValueOnce(rowsResponse([], 503))
56
+ .mockResolvedValueOnce(rowsResponse([{ id: 1 }]))
57
+ vi.stubGlobal("fetch", fetch)
58
+ const { data, error } = await client().from("posts").select("*")
59
+ expect(error).toBeNull()
60
+ expect(data).toEqual([{ id: 1 }])
61
+ expect(fetch).toHaveBeenCalledTimes(2)
62
+ })
63
+
64
+ it("a select does not retry when retry is false", async () => {
65
+ const fetch = vi.fn().mockResolvedValue(rowsResponse([], 503))
66
+ vi.stubGlobal("fetch", fetch)
67
+ const { error } = await client({ retry: false }).from("posts").select("*")
68
+ expect(error?.status).toBe(503)
69
+ expect(fetch).toHaveBeenCalledTimes(1)
70
+ })
71
+
72
+ it("an insert is never retried, so a write the server may have applied is not repeated", async () => {
73
+ const fetch = vi.fn().mockResolvedValue(rowsResponse([], 503))
74
+ vi.stubGlobal("fetch", fetch)
75
+ const { error } = await client().from("posts").insert({ title: "x", user_id: "u1" })
76
+ expect(error?.status).toBe(503)
77
+ expect(fetch).toHaveBeenCalledTimes(1)
78
+ })
79
+
80
+ it("an insert is not retried after a network failure either", async () => {
81
+ const fetch = vi.fn().mockRejectedValue(new TypeError("fetch failed"))
82
+ vi.stubGlobal("fetch", fetch)
83
+ const { error } = await client().from("posts").insert({ title: "x", user_id: "u1" })
84
+ expect(error).not.toBeNull()
85
+ expect(fetch).toHaveBeenCalledTimes(1)
86
+ })
87
+
88
+ it("a rate-limited read keeps its 429 status", async () => {
89
+ const fetch = vi.fn().mockResolvedValue(rowsResponse([], 429))
90
+ vi.stubGlobal("fetch", fetch)
91
+ const { error } = await client({ retry: false }).from("posts").select("*")
92
+ expect(error?.status).toBe(429)
93
+ })
94
+ })
@@ -5,5 +5,5 @@
5
5
  "composite": false,
6
6
  "rootDir": ".."
7
7
  },
8
- "include": ["./**/*.ts", "../src/**/*.ts"]
8
+ "include": ["../../../ts-reset.d.ts", "./**/*.ts", "../src/**/*.ts"]
9
9
  }