@supatype/client 0.3.5 → 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,85 @@
1
+ import { describe, expect, it, vi } from "vitest"
2
+ import { getErrorDocumentation } from "../src/error-codes-doc.js"
3
+ import { PostgrestErrorCodes } from "../src/errors.js"
4
+ import { MutationBuilder, QueryBuilder } from "../src/query.js"
5
+
6
+ /**
7
+ * The codes PostgREST 14 answers with, recorded from a live `postgrest/postgrest:v14.18` against
8
+ * Postgres 17, and the constant a caller would compare each one with.
9
+ *
10
+ * Two of these moved in PostgREST 13: an expired token is `PGRST303` (it was `PGRST301`), and a
11
+ * missing table is `PGRST205` (it was the SQLSTATE `42P01`). A database error is passed through
12
+ * under its SQLSTATE, with no `PGRST` prefix, so a constant spelled `PGRST23505` never matched a
13
+ * unique violation in any release.
14
+ */
15
+ const RECORDED: Array<{ case: string; status: number; code: string; constant: string }> = [
16
+ { case: "expired JWT", status: 401, code: "PGRST303", constant: PostgrestErrorCodes.JWT_EXPIRED },
17
+ { case: "JWT with a bad signature", status: 401, code: "PGRST301", constant: PostgrestErrorCodes.JWT_INVALID },
18
+ { case: "missing table", status: 404, code: "PGRST205", constant: PostgrestErrorCodes.UNDEFINED_TABLE },
19
+ { case: "insert into an unknown column", status: 400, code: "PGRST204", constant: PostgrestErrorCodes.SCHEMA_CACHE_MISS },
20
+ { case: "single() with no rows", status: 406, code: "PGRST116", constant: PostgrestErrorCodes.NOT_FOUND },
21
+ { case: "row-level security denial, signed in", status: 403, code: "42501", constant: PostgrestErrorCodes.PERMISSION_DENIED },
22
+ { case: "foreign key violation", status: 409, code: "23503", constant: PostgrestErrorCodes.FK_VIOLATION },
23
+ { case: "unique violation", status: 409, code: "23505", constant: PostgrestErrorCodes.UNIQUE_VIOLATION },
24
+ { case: "not-null violation", status: 400, code: "23502", constant: PostgrestErrorCodes.NOT_NULL_VIOLATION },
25
+ { case: "check violation", status: 400, code: "23514", constant: PostgrestErrorCodes.CHECK_VIOLATION },
26
+ { case: "invalid input syntax", status: 400, code: "22P02", constant: PostgrestErrorCodes.INVALID_INPUT },
27
+ { case: "filter on an unknown column", status: 400, code: "42703", constant: PostgrestErrorCodes.UNDEFINED_COLUMN },
28
+ ]
29
+
30
+ /** PostgREST 14's message for a `vnd.pgrst.object+json` request that did not find one row. */
31
+ const SINGLE_ROW_MESSAGE = "Cannot coerce the result to a single JSON object"
32
+
33
+ describe("PostgREST error codes", () => {
34
+ it.each(RECORDED)("$case: the constant is the code PostgREST answers", ({ code, constant }) => {
35
+ expect(constant).toBe(code)
36
+ })
37
+
38
+ it.each(RECORDED)("$case: the documentation has an entry for the code", ({ code, status }) => {
39
+ const entry = getErrorDocumentation(code)
40
+ expect(entry?.category).toBe("postgrest")
41
+ expect(entry?.httpStatus).toBe(status)
42
+ })
43
+ })
44
+
45
+ describe("single() without exactly one row", () => {
46
+ const emptyArray = (): Response =>
47
+ new Response("[]", { status: 200, headers: { "Content-Type": "application/json" } })
48
+
49
+ it("a read words it as PostgREST does", async () => {
50
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
51
+ const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {}).single()
52
+ vi.unstubAllGlobals()
53
+ expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
54
+ })
55
+
56
+ it("a write words it as PostgREST does", async () => {
57
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
58
+ const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).single()
59
+ vi.unstubAllGlobals()
60
+ expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
61
+ })
62
+ })
63
+
64
+ describe("a field validator's refusal", () => {
65
+ // Recorded from the kitchen-sink stack: what the gateway answers when `validate-chat-body` refuses.
66
+ const refused = (): Response =>
67
+ new Response(
68
+ JSON.stringify({ field: "body", message: "That reads as shouting.", error: "That reads as shouting." }),
69
+ { status: 422, headers: { "Content-Type": "application/json" } },
70
+ )
71
+
72
+ it("keeps the field on a read", async () => {
73
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
74
+ const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {})
75
+ vi.unstubAllGlobals()
76
+ expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
77
+ })
78
+
79
+ it("keeps the field on a write, which is where a validator runs", async () => {
80
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
81
+ const { error } = await new MutationBuilder("http://x", "/rest/v1/t", { body: "HELLO" }, "POST", {})
82
+ vi.unstubAllGlobals()
83
+ expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
84
+ })
85
+ })
@@ -1,118 +1,117 @@
1
- import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
2
- import { QueryBuilder } from "../src/query.js"
3
- import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
4
-
5
- describe("query-cache", () => {
6
- it("identityFingerprint differs for different subs", () => {
7
- const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
8
- const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
9
- const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
10
- const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
11
- expect(a).not.toBe(b)
12
- })
13
-
14
- it("identityFingerprint stable for same sub across token strings", () => {
15
- const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
16
- const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
17
- const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
18
- expect(a).toBe(b)
19
- })
20
-
21
- it("public scope uses global fingerprint", () => {
22
- expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
23
- })
24
-
25
- it("buildCacheKey is stable", () => {
26
- const h = { Authorization: "Bearer x" }
27
- const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
28
- const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
29
- expect(k1).toBe(k2)
30
- })
31
-
32
- it("QueryCache expires entries", () => {
33
- vi.useFakeTimers()
34
- const cache = new QueryCache()
35
- cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
36
- expect(cache.get("k")?.data).toEqual([{ id: 1 }])
37
- vi.advanceTimersByTime(1001)
38
- expect(cache.get("k")).toBeNull()
39
- vi.useRealTimers()
40
- })
41
- })
42
-
43
- describe("QueryBuilder.cache", () => {
44
- const fetchMock = vi.fn()
45
-
46
- beforeEach(() => {
47
- fetchMock.mockReset()
48
- vi.stubGlobal("fetch", fetchMock)
49
- })
50
-
51
- afterEach(() => {
52
- vi.unstubAllGlobals()
53
- })
54
-
55
- it("returns cached result without second fetch", async () => {
56
- fetchMock.mockResolvedValue(
57
- new Response(JSON.stringify([{ id: 1 }]), {
58
- status: 200,
59
- headers: { "Content-Type": "application/json" },
60
- }),
61
- )
62
-
63
- const cache = new QueryCache()
64
- const qb = new QueryBuilder<{ id: number }>(
65
- "http://localhost:9999",
66
- "/rest/v1/posts",
67
- { Authorization: "Bearer anon" },
68
- "*",
69
- cache,
70
- ).cache({ ttl: 60_000 })
71
-
72
- // Counted per table URL rather than across every request, because the client also fetches the
73
- // project's column types once so it can keep bigInt, decimal and money columns exact. That
74
- // request is cached per project and is not what this test is about.
75
- const tableCalls = (): number =>
76
- fetchMock.mock.calls.filter((call) => String(call[0]).includes("/rest/v1/posts")).length
77
-
78
- const r1 = await qb
79
- expect(r1.data).toEqual([{ id: 1 }])
80
- expect(tableCalls()).toBe(1)
81
-
82
- const r2 = await qb
83
- expect(r2.data).toEqual([{ id: 1 }])
84
- expect(r2.meta?.cacheStatus).toBe("HIT")
85
- expect(tableCalls()).toBe(1)
86
- })
87
-
88
- it("sends X-Supatype-Cache when server: true", async () => {
89
- fetchMock.mockResolvedValue(
90
- new Response(JSON.stringify([]), {
91
- status: 200,
92
- headers: {
93
- "Content-Type": "application/json",
94
- "X-Supatype-Cache-Status": "MISS",
95
- },
96
- }),
97
- )
98
-
99
- await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
100
- .cache({ ttl: 30_000, server: true })
101
-
102
- const init = fetchMock.mock.calls[0]?.[1] as RequestInit
103
- expect(init.headers).toMatchObject({ "X-Supatype-Cache": "max-age=30" })
104
- })
105
-
106
- it("sends public directive when server and public", async () => {
107
- fetchMock.mockResolvedValue(
108
- new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
109
- )
110
-
111
- await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
112
- .cache({ ttl: 30_000, server: true, public: true })
113
-
114
- const init = fetchMock.mock.calls[0]?.[1] as RequestInit
115
- expect(init.headers).toMatchObject({ "X-Supatype-Cache": "max-age=30, public" })
116
- })
117
- })
1
+ import { describe, it, expect, beforeEach, vi, afterEach } from "vitest"
2
+ import { QueryBuilder } from "../src/query.js"
3
+ import { QueryCache, buildCacheKey, identityFingerprint } from "../src/query-cache.js"
4
+ import { fetchCall, fetchCalls, header, mockFetch } from "./support/fetch-mock.js"
5
+
6
+ describe("query-cache", () => {
7
+ it("identityFingerprint differs for different subs", () => {
8
+ const payloadA = btoa(JSON.stringify({ sub: "a", role: "authenticated" }))
9
+ const payloadB = btoa(JSON.stringify({ sub: "b", role: "authenticated" }))
10
+ const a = identityFingerprint({ Authorization: `Bearer x.${payloadA}.y` }, "user")
11
+ const b = identityFingerprint({ Authorization: `Bearer x.${payloadB}.y` }, "user")
12
+ expect(a).not.toBe(b)
13
+ })
14
+
15
+ it("identityFingerprint stable for same sub across token strings", () => {
16
+ const payload = btoa(JSON.stringify({ sub: "user-1", role: "authenticated" }))
17
+ const a = identityFingerprint({ Authorization: `Bearer aaa.${payload}.sig1` }, "user")
18
+ const b = identityFingerprint({ Authorization: `Bearer bbb.${payload}.sig2` }, "user")
19
+ expect(a).toBe(b)
20
+ })
21
+
22
+ it("public scope uses global fingerprint", () => {
23
+ expect(identityFingerprint({ Authorization: "Bearer x" }, "public")).toBe("global")
24
+ })
25
+
26
+ it("buildCacheKey is stable", () => {
27
+ const h = { Authorization: "Bearer x" }
28
+ const k1 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
29
+ const k2 = buildCacheKey("GET", "http://localhost/rest/v1/posts", h)
30
+ expect(k1).toBe(k2)
31
+ })
32
+
33
+ it("QueryCache expires entries", () => {
34
+ vi.useFakeTimers()
35
+ const cache = new QueryCache()
36
+ cache.set("k", { data: [{ id: 1 }], error: null, count: 1 }, 1000)
37
+ expect(cache.get("k")?.data).toEqual([{ id: 1 }])
38
+ vi.advanceTimersByTime(1001)
39
+ expect(cache.get("k")).toBeNull()
40
+ vi.useRealTimers()
41
+ })
42
+ })
43
+
44
+ describe("QueryBuilder.cache", () => {
45
+ const fetchMock = mockFetch()
46
+
47
+ beforeEach(() => {
48
+ fetchMock.mockReset()
49
+ vi.stubGlobal("fetch", fetchMock)
50
+ })
51
+
52
+ afterEach(() => {
53
+ vi.unstubAllGlobals()
54
+ })
55
+
56
+ it("returns cached result without second fetch", async () => {
57
+ fetchMock.mockResolvedValue(
58
+ new Response(JSON.stringify([{ id: 1 }]), {
59
+ status: 200,
60
+ headers: { "Content-Type": "application/json" },
61
+ }),
62
+ )
63
+
64
+ const cache = new QueryCache()
65
+ const qb = new QueryBuilder<{ id: number }>(
66
+ "http://localhost:9999",
67
+ "/rest/v1/posts",
68
+ { Authorization: "Bearer anon" },
69
+ "*",
70
+ cache,
71
+ ).cache({ ttl: 60_000 })
72
+
73
+ // Counted per table URL rather than across every request, because the client also fetches the
74
+ // project's column types once so it can keep bigInt, decimal and money columns exact. That
75
+ // request is cached per project and is not what this test is about.
76
+ const tableCalls = (): number =>
77
+ fetchCalls(fetchMock).filter(({ url }) => url.includes("/rest/v1/posts")).length
78
+
79
+ const r1 = await qb
80
+ expect(r1.data).toEqual([{ id: 1 }])
81
+ expect(tableCalls()).toBe(1)
82
+
83
+ const r2 = await qb
84
+ expect(r2.data).toEqual([{ id: 1 }])
85
+ expect(r2.meta?.cacheStatus).toBe("HIT")
86
+ expect(tableCalls()).toBe(1)
87
+ })
88
+
89
+ it("sends X-Supatype-Cache when server: true", async () => {
90
+ fetchMock.mockResolvedValue(
91
+ new Response(JSON.stringify([]), {
92
+ status: 200,
93
+ headers: {
94
+ "Content-Type": "application/json",
95
+ "X-Supatype-Cache-Status": "MISS",
96
+ },
97
+ }),
98
+ )
99
+
100
+ await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
101
+ .cache({ ttl: 30_000, server: true })
102
+
103
+ expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30")
104
+ })
105
+
106
+ it("sends public directive when server and public", async () => {
107
+ fetchMock.mockResolvedValue(
108
+ new Response(JSON.stringify([]), { status: 200, headers: { "Content-Type": "application/json" } }),
109
+ )
110
+
111
+ await new QueryBuilder("http://localhost:9999", "/rest/v1/posts", {}, "*")
112
+ .cache({ ttl: 30_000, server: true, public: true })
113
+
114
+ expect(header(fetchCall(fetchMock).init, "X-Supatype-Cache")).toBe("max-age=30, public")
115
+ })
116
+ })
118
117
 
@@ -1,5 +1,6 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest"
2
2
  import { QueryBuilder, MutationBuilder, defaultQueryCache } from "../src/query.js"
3
+ import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
3
4
 
4
5
  // ─── Helpers ─────────────────────────────────────────────────────────────────
5
6
 
@@ -12,25 +13,17 @@ interface Post { id: string; title: string; status: string }
12
13
  function mockFetch(
13
14
  body: unknown,
14
15
  opts: { ok?: boolean; status?: number; contentRange?: string } = {},
15
- ): ReturnType<typeof vi.fn> {
16
+ ): FetchMock {
16
17
  const { ok = true, status = ok ? 200 : 400, contentRange } = opts
17
- return vi.fn().mockResolvedValue({
18
- ok,
19
- status,
20
- json: vi.fn().mockResolvedValue(body),
21
- text: vi.fn().mockResolvedValue(JSON.stringify(body)),
22
- headers: {
23
- get: (key: string) => (key === "content-range" ? (contentRange ?? null) : null),
24
- },
25
- })
18
+ return fetchReturning(body, status, contentRange === undefined ? {} : { "Content-Range": contentRange })
26
19
  }
27
20
 
28
- function captureUrl(): { url: () => string; fetch: ReturnType<typeof vi.fn> } {
21
+ function captureUrl(): { url: () => string; fetch: FetchMock } {
29
22
  const fetch = mockFetch([])
30
23
  vi.stubGlobal("fetch", fetch)
31
24
  return {
32
25
  fetch,
33
- url: () => (fetch.mock.calls[0] as [string, unknown])[0],
26
+ url: () => fetchCall(fetch).url,
34
27
  }
35
28
  }
36
29
 
@@ -126,6 +119,17 @@ describe("QueryBuilder: URL construction", () => {
126
119
  expect(url()).toContain("nullsfirst")
127
120
  })
128
121
 
122
+ // PostgREST reads only the first `order` parameter, so a second one sent separately was dropped
123
+ // without an error and the rows came back ordered by the first column alone.
124
+ it(".order() twice sends one comma-separated order parameter", async () => {
125
+ const { url } = captureUrl()
126
+ await new QueryBuilder<Post>(BASE, PATH, HEADERS)
127
+ .order("created_at", { ascending: false })
128
+ .order("id", { ascending: false })
129
+ const params = new URL(url()).searchParams
130
+ expect(params.getAll("order")).toEqual(["created_at.desc.nullslast,id.desc.nullslast"])
131
+ })
132
+
129
133
  it(".limit() sets limit param", async () => {
130
134
  const { url } = captureUrl()
131
135
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(20)
@@ -136,8 +140,7 @@ describe("QueryBuilder: URL construction", () => {
136
140
  const fetch = mockFetch([])
137
141
  vi.stubGlobal("fetch", fetch)
138
142
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
139
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
140
- expect((opts.headers as Record<string, string>)["Range"]).toBe("10-19")
143
+ expect(header(fetchCall(fetch).init, "Range")).toBe("10-19")
141
144
  })
142
145
 
143
146
  it("multiple chained filters all appear in URL", async () => {
@@ -166,8 +169,7 @@ describe("QueryBuilder: URL construction", () => {
166
169
  await new QueryBuilder<Post>(BASE, PATH, HEADERS, "*", defaultQueryCache, undefined, {
167
170
  count: "exact",
168
171
  })
169
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
170
- expect((opts.headers as Record<string, string>)["Prefer"]).toBe("count=exact")
172
+ expect(header(fetchCall(fetch).init, "Prefer")).toBe("count=exact")
171
173
  })
172
174
 
173
175
  it("select with head issues HEAD request and returns count only", async () => {
@@ -182,8 +184,7 @@ describe("QueryBuilder: URL construction", () => {
182
184
  undefined,
183
185
  { count: "exact", head: true },
184
186
  )
185
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
186
- expect(opts.method).toBe("HEAD")
187
+ expect(fetchCall(fetch).init.method).toBe("HEAD")
187
188
  expect(data).toBeNull()
188
189
  expect(error).toBeNull()
189
190
  expect(count).toBe(42)
@@ -231,8 +232,7 @@ describe("QueryBuilder.single()", () => {
231
232
  const fetch = mockFetch({ id: "1", title: "Hello", status: "published" })
232
233
  vi.stubGlobal("fetch", fetch)
233
234
  await new QueryBuilder<Post>(BASE, PATH, HEADERS).single()
234
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
235
- expect((opts.headers as Record<string, string>)["Accept"]).toContain("pgrst.object+json")
235
+ expect(header(fetchCall(fetch).init, "Accept")).toContain("pgrst.object+json")
236
236
  })
237
237
 
238
238
  it("returns single row", async () => {
@@ -271,9 +271,9 @@ describe("MutationBuilder: insert", () => {
271
271
  const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
272
272
  expect(error).toBeNull()
273
273
  expect(data?.[0]?.id).toBe("1")
274
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
275
- expect(opts.method).toBe("POST")
276
- expect(opts.body as string).toContain("New")
274
+ const { init } = fetchCall(fetch)
275
+ expect(init.method).toBe("POST")
276
+ expect(init.body).toContain("New")
277
277
  })
278
278
 
279
279
  it("returns error on non-ok", async () => {
@@ -291,8 +291,8 @@ describe("MutationBuilder: update / delete", () => {
291
291
  const fetch = mockFetch([{ id: "1", title: "Updated", status: "published" }])
292
292
  vi.stubGlobal("fetch", fetch)
293
293
  await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "Updated" }).eq("id", "1")
294
- const [url, opts] = fetch.mock.calls[0] as [string, RequestInit]
295
- expect(opts.method).toBe("PATCH")
294
+ const { url, init } = fetchCall(fetch)
295
+ expect(init.method).toBe("PATCH")
296
296
  expect(url).toContain("id=eq.1")
297
297
  })
298
298
 
@@ -300,8 +300,8 @@ describe("MutationBuilder: update / delete", () => {
300
300
  const fetch = mockFetch(null, { status: 204 })
301
301
  vi.stubGlobal("fetch", fetch)
302
302
  await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
303
- const [url, opts] = fetch.mock.calls[0] as [string, RequestInit]
304
- expect(opts.method).toBe("DELETE")
303
+ const { url, init } = fetchCall(fetch)
304
+ expect(init.method).toBe("DELETE")
305
305
  expect(url).toContain("id=eq.1")
306
306
  })
307
307
 
@@ -316,8 +316,7 @@ describe("MutationBuilder: update / delete", () => {
316
316
  const fetch = mockFetch([{ id: "1", title: "A", status: "draft" }])
317
317
  vi.stubGlobal("fetch", fetch)
318
318
  await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1", title: "A", status: "draft" }, { upsert: true })
319
- const [, opts] = fetch.mock.calls[0] as [string, RequestInit]
320
- expect((opts.headers as Record<string, string>)["Prefer"]).toContain("merge-duplicates")
319
+ expect(header(fetchCall(fetch).init, "Prefer")).toContain("merge-duplicates")
321
320
  })
322
321
 
323
322
  it("update().eq().select().maybeSingle() returns first row", async () => {
@@ -335,7 +334,6 @@ describe("MutationBuilder: update / delete", () => {
335
334
  .maybeSingle()
336
335
  expect(error).toBeNull()
337
336
  expect(data).toEqual({ id: "1", title: "Updated", status: "published" })
338
- const [url] = fetch.mock.calls[0] as [string, RequestInit]
339
- expect(url).toContain("select=*")
337
+ expect(fetchCall(fetch).url).toContain("select=*")
340
338
  })
341
339
  })
@@ -11,14 +11,8 @@ import { RateLimitError } from "../src/errors.js"
11
11
  // ─── Helpers ─────────────────────────────────────────────────────────────────
12
12
 
13
13
  function mockResponse(status: number, body: unknown = {}, headers?: Record<string, string>): Response {
14
- const headersObj = new Headers(headers)
15
- return {
16
- ok: status >= 200 && status < 300,
17
- status,
18
- json: vi.fn().mockResolvedValue(body),
19
- headers: headersObj,
20
- statusText: status === 429 ? "Too Many Requests" : "OK",
21
- } as unknown as Response
14
+ const statusText = status === 429 ? "Too Many Requests" : "OK"
15
+ return new Response(JSON.stringify(body), { status, statusText, headers: { "Content-Type": "application/json", ...headers } })
22
16
  }
23
17
 
24
18
  // ─── Tests ───────────────────────────────────────────────────────────────────
@@ -126,9 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
126
120
  expect.fail("Should have thrown RateLimitError")
127
121
  } catch (err) {
128
122
  expect(err).toBeInstanceOf(RateLimitError)
129
- expect((err as RateLimitError).retryAfterSeconds).toBe(2)
130
- expect((err as RateLimitError).statusCode).toBe(429)
131
- expect((err as RateLimitError).code).toBe("RATE_LIMITED")
123
+ expect(err).toMatchObject({ retryAfterSeconds: 2, statusCode: 429, code: "RATE_LIMITED" })
132
124
  }
133
125
  vi.useFakeTimers()
134
126
  })
@@ -179,7 +171,7 @@ describe("Task 91: SDK rate limit integration", () => {
179
171
 
180
172
  const res = await promise
181
173
  expect(res.ok).toBe(true)
182
- const data = await res.json()
174
+ const data: unknown = await res.json()
183
175
  expect(data).toEqual(expectedData)
184
176
  })
185
177
  })
@@ -22,17 +22,15 @@ import {
22
22
  const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
23
23
 
24
24
  let instances: MockWebSocketInstance[]
25
- let originalWebSocket: typeof WebSocket
26
25
 
27
26
  beforeEach(() => {
28
27
  const mock = createMockWebSocketClass()
29
28
  instances = mock.instances
30
- originalWebSocket = globalThis.WebSocket
31
- globalThis.WebSocket = mock.MockWebSocket
29
+ vi.stubGlobal("WebSocket", mock.MockWebSocket)
32
30
  })
33
31
 
34
32
  afterEach(() => {
35
- globalThis.WebSocket = originalWebSocket
33
+ vi.unstubAllGlobals()
36
34
  vi.restoreAllMocks()
37
35
  })
38
36
 
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Presence counted from joins and leaves stays true across a socket swap.
3
+ *
4
+ * The server tells a channel's newcomer who is already there as joins, and it does so on every
5
+ * join, including the one each channel makes again on the socket that signing in opens. Leaves
6
+ * for the old socket's members never arrive (that socket is gone), so a page counting joins minus
7
+ * leaves read every member twice after signing in. The client now leaves, for its listeners,
8
+ * everyone it had been told about when the socket that told it goes away.
9
+ */
10
+
11
+ import { describe, it, expect, beforeEach, afterEach } from "vitest"
12
+ import type { PresenceEntry } from "../src/realtime.js"
13
+ import { simulateServerMessage } from "./helpers/mock-websocket.js"
14
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
15
+
16
+ const CHANNEL = "lobby:lobby"
17
+
18
+ let harness: SocketSwapHarness
19
+ let here: number
20
+ let leaves: PresenceEntry[]
21
+
22
+ function newest(): SocketSwapHarness["sockets"][number] {
23
+ const socket = harness.sockets[harness.sockets.length - 1]
24
+ if (socket === undefined) throw new Error("no socket has been opened")
25
+ return socket
26
+ }
27
+
28
+ function serverSays(joins: PresenceEntry[], left: PresenceEntry[] = []): void {
29
+ simulateServerMessage(newest(), { type: "presence", channel: CHANNEL, joins, leaves: left })
30
+ }
31
+
32
+ beforeEach(async () => {
33
+ harness = createSocketSwapHarness()
34
+ here = 0
35
+ leaves = []
36
+ const channel = harness.realtime.channel(CHANNEL)
37
+ channel.onPresence((event) => {
38
+ here += event.joins.length - event.leaves.length
39
+ leaves.push(...event.leaves)
40
+ })
41
+ channel.subscribe()
42
+ await harness.settle()
43
+ harness.ackJoins()
44
+ })
45
+
46
+ afterEach(() => harness.restore())
47
+
48
+ describe("presence across the socket swap on sign-in", () => {
49
+ it("counts each member once after the new socket's join sends the state again", async () => {
50
+ serverSays([{ user_id: "first" }, { user_id: "second" }])
51
+ expect(here).toBe(2)
52
+
53
+ await harness.signIn()
54
+ harness.ackJoins()
55
+ serverSays([{ user_id: "first" }, { user_id: "second" }])
56
+
57
+ expect(here).toBe(2)
58
+ })
59
+
60
+ it("leaves everyone it had been told about when the socket goes away", async () => {
61
+ serverSays([{ user_id: "first" }, { user_id: "second" }])
62
+ serverSays([], [{ user_id: "first" }])
63
+
64
+ await harness.signIn()
65
+
66
+ expect(here).toBe(0)
67
+ expect(leaves).toEqual([{ user_id: "first" }, { user_id: "second" }])
68
+ })
69
+
70
+ it("tells a channel nobody joined nothing when the socket goes away", () => {
71
+ harness.realtime.disconnect()
72
+
73
+ expect(leaves).toEqual([])
74
+ })
75
+ })
@@ -16,6 +16,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
16
16
  import { RealtimeClient } from "../src/realtime.js"
17
17
  import {
18
18
  createMockWebSocketClass,
19
+ subscribedChannels,
19
20
  tokenOf,
20
21
  type MockWebSocketInstance,
21
22
  } from "./helpers/mock-websocket.js"
@@ -128,10 +129,7 @@ describe("realtime authenticates as the session, not as anon", () => {
128
129
  await settle()
129
130
 
130
131
  const replacement = MockWS.instances[1]!
131
- const subscribes = replacement.send.mock.calls
132
- .map(([raw]) => JSON.parse(String(raw)) as { type: string; channel: string })
133
- .filter((m) => m.type === "subscribe")
134
- expect(subscribes.map((m) => m.channel)).toContain("public:task")
132
+ expect(subscribedChannels(replacement)).toContain("public:task")
135
133
  })
136
134
 
137
135
  it("reconnects when the identity changes while the first connect is still resolving its token", async () => {