@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,225 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
2
+ import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "../src/index.js"
3
+ import { runMutation } from "../src/bindings.js"
4
+ import { fetchCalls, header, jsonBody, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
5
+
6
+ // An insert on a model that keeps drafts is created through `supatype.create_record` and read back
7
+ // from the draft view. A plain insert asking for the row back is refused there by a read rule that
8
+ // hides unpublished records (Postgres checks the returned row against it before anything has made
9
+ // the new row visible to its author), so these pin which request goes out, and that the caller gets
10
+ // the row an insert returns.
11
+
12
+ const BASE = "http://localhost:18473"
13
+ const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
14
+ const ROW = { id: ID, title: "Mine", body: { en: "hi" }, published_at: null }
15
+ const CREATED = { record_id: ID, version: 1, status: "draft", created_at: "2026-10-18T10:00:00Z" }
16
+
17
+ /** PostgREST's answer to a plain insert asking for an unpublished row back, recorded from v14.18. */
18
+ const REFUSED = { code: "42501", details: null, hint: null, message: 'new row violates row-level security policy for table "posts"' }
19
+
20
+ /**
21
+ * Answers as the database does for an editor whose read rule hides unpublished records:
22
+ * `create_record` makes the record, the draft view reads it, and a plain insert asking for the row
23
+ * back is refused.
24
+ */
25
+ function draftsServer(): FetchMock {
26
+ return mockFetch((input, init) => {
27
+ const url = requestUrl(input)
28
+ if (url.endsWith("/rest/v1/rpc/create_record")) return Promise.resolve(jsonResponse(CREATED))
29
+ if (init?.method === "POST") return Promise.resolve(jsonResponse(REFUSED, 403))
30
+ return Promise.resolve(jsonResponse([ROW]))
31
+ })
32
+ }
33
+
34
+ const ID_A = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
35
+ const ID_B = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
36
+
37
+ /** Postgres's refusal of a record with no title, as PostgREST passes it on. */
38
+ const NOT_NULL = { code: "23502", details: null, hint: null, message: 'null value in column "title" violates not-null constraint' }
39
+
40
+ /**
41
+ * Answers `create_records` with two new records, and the draft view with their rows in the other
42
+ * order, as a database is free to: the client must put them back in the order they were sent.
43
+ */
44
+ function batchServer(): FetchMock {
45
+ return mockFetch((input) => {
46
+ const url = requestUrl(input)
47
+ if (url.endsWith("/rest/v1/rpc/create_records")) {
48
+ return Promise.resolve(jsonResponse([{ ...CREATED, record_id: ID_A }, { ...CREATED, record_id: ID_B }]))
49
+ }
50
+ return Promise.resolve(
51
+ jsonResponse([
52
+ { title: "B", __supatype_created_key: ID_B },
53
+ { title: "A", __supatype_created_key: ID_A },
54
+ ]),
55
+ )
56
+ })
57
+ }
58
+
59
+ function serve(fetch: FetchMock): FetchMock {
60
+ vi.stubGlobal("fetch", fetch)
61
+ return fetch
62
+ }
63
+
64
+ // Untyped, as a project whose schema the test fixtures do not describe.
65
+ const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key" })
66
+
67
+ describe("insert on a model that keeps drafts", () => {
68
+ beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
69
+ afterEach(() => {
70
+ forgetRegisteredDraftModels()
71
+ vi.unstubAllGlobals()
72
+ })
73
+
74
+ it("creates the record through supatype.create_record", async () => {
75
+ const fetch = serve(draftsServer())
76
+ await client().from("posts").insert({ title: "Mine", body: { en: "hi" } })
77
+ const [create] = fetchCalls(fetch)
78
+ expect(create?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
79
+ expect(create?.init.method).toBe("POST")
80
+ expect(header(create?.init ?? {}, "Content-Profile")).toBe("supatype")
81
+ expect(jsonBody(create?.init ?? {})).toEqual({ model_table: "posts", data: { title: "Mine", body: { en: "hi" } } })
82
+ })
83
+
84
+ it("reads the new record back from the draft view, by its key, with the insert's select", async () => {
85
+ const fetch = serve(draftsServer())
86
+ await client().from("posts").insert({ title: "Mine" }).select("id, title")
87
+ const readBack = fetchCalls(fetch)[1]
88
+ const url = new URL(readBack?.url ?? "")
89
+ expect(url.pathname).toBe("/rest/v1/posts")
90
+ expect(url.searchParams.get("id")).toBe(`in.(${ID})`)
91
+ expect(url.searchParams.get("select")).toBe("id, title")
92
+ expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
93
+ })
94
+
95
+ it("returns the row as a plain insert would", async () => {
96
+ serve(draftsServer())
97
+ const { data, error, count } = await client().from("posts").insert({ title: "Mine" })
98
+ expect(error).toBeNull()
99
+ expect(data).toEqual([ROW])
100
+ expect(count).toBe(1)
101
+ })
102
+
103
+ it("answers single() with the one row", async () => {
104
+ serve(draftsServer())
105
+ const { data, error } = await client().from("posts").insert({ title: "Mine" }).select().single()
106
+ expect(error).toBeNull()
107
+ expect(data).toEqual(ROW)
108
+ })
109
+
110
+ it("treats a one-row array as one record", async () => {
111
+ const fetch = serve(draftsServer())
112
+ const { data } = await client().from("posts").insert([{ title: "Mine" }])
113
+ expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
114
+ expect(jsonBody(fetchCalls(fetch)[0]?.init ?? {})["data"]).toEqual({ title: "Mine" })
115
+ expect(data).toEqual([ROW])
116
+ })
117
+
118
+ it("passes create_record's refusal through and reads nothing back", async () => {
119
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse(REFUSED, 403))))
120
+ const { data, error } = await client().from("posts").insert({ title: "Mine" })
121
+ expect(data).toBeNull()
122
+ expect(error).toMatchObject({ code: "42501", status: 403 })
123
+ expect(fetchCalls(fetch)).toHaveLength(1)
124
+ })
125
+
126
+ it("creates several rows in one supatype.create_records call, which is all or nothing", async () => {
127
+ const fetch = serve(batchServer())
128
+ await client().from("posts").insert([{ title: "A" }, { title: "B" }])
129
+ const [create] = fetchCalls(fetch)
130
+ expect(create?.url).toBe(`${BASE}/rest/v1/rpc/create_records`)
131
+ expect(header(create?.init ?? {}, "Content-Profile")).toBe("supatype")
132
+ expect(jsonBody(create?.init ?? {})).toEqual({ model_table: "posts", data: [{ title: "A" }, { title: "B" }] })
133
+ })
134
+
135
+ it("reads several rows back by their keys, with the insert's select and a key to order them by", async () => {
136
+ const fetch = serve(batchServer())
137
+ await client().from("posts").insert([{ title: "A" }, { title: "B" }]).select("title")
138
+ const url = new URL(fetchCalls(fetch)[1]?.url ?? "")
139
+ expect(url.searchParams.get("id")).toBe(`in.(${ID_A},${ID_B})`)
140
+ expect(url.searchParams.get("select")).toBe("title,__supatype_created_key:id")
141
+ })
142
+
143
+ it("returns several rows in the order they were sent, as the select asked for them", async () => {
144
+ serve(batchServer())
145
+ const { data, error, count } = await client().from("posts").insert([{ title: "A" }, { title: "B" }]).select("title")
146
+ expect(error).toBeNull()
147
+ expect(data).toEqual([{ title: "A" }, { title: "B" }])
148
+ expect(count).toBe(2)
149
+ })
150
+
151
+ it("passes create_records' refusal through and reads nothing back", async () => {
152
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse(NOT_NULL, 400))))
153
+ const { data, error } = await client().from("posts").insert([{ title: "A" }, { title: null }])
154
+ expect(data).toBeNull()
155
+ expect(error).toMatchObject({ code: "23502", status: 400 })
156
+ expect(fetchCalls(fetch)).toHaveLength(1)
157
+ })
158
+
159
+ it("leaves an empty insert a plain write, which creates nothing", async () => {
160
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([], 201))))
161
+ const { data } = await client().from("posts").insert([])
162
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
163
+ expect(data).toEqual([])
164
+ })
165
+
166
+ it("hands the caller the gateway's hint when a plain write is refused", async () => {
167
+ const hint = "This model keeps drafts: create records with supatype.create_record."
168
+ serve(mockFetch(() => Promise.resolve(jsonResponse({ ...REFUSED, hint }, 403))))
169
+ const { error } = await client().from("posts").upsert({ title: "A" })
170
+ expect(error).toMatchObject({ code: "42501", status: 403, hint })
171
+ })
172
+
173
+ it("hands the caller the detail line naming a unique violation's columns, on a write and a call", async () => {
174
+ // Studio's Duplicate learns which copied value collided from this line; it was dropped.
175
+ const details = "Key (slug)=(intro) already exists."
176
+ const UNIQUE = { code: "23505", details, hint: null, message: 'duplicate key value violates unique constraint "posts_slug_key"' }
177
+ serve(mockFetch(() => Promise.resolve(jsonResponse(UNIQUE, 409))))
178
+ const write = await client().from("posts").upsert({ title: "A" })
179
+ const call = await client().rpc("create_record", { model_table: "posts", data: {} })
180
+ expect(write.error).toMatchObject({ code: "23505", details })
181
+ expect(call.error).toMatchObject({ code: "23505", details })
182
+ })
183
+
184
+ it("leaves upsert a plain write, since create_record cannot say what a conflict does", async () => {
185
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([ROW], 201))))
186
+ await client().from("posts").upsert({ id: ID, title: "Mine" })
187
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
188
+ })
189
+
190
+ it("reaches the framework bindings, which insert through runMutation", async () => {
191
+ const fetch = serve(draftsServer())
192
+ const outcome = await runMutation(client(), "posts", "insert", { title: "Mine" })
193
+ expect(fetchCalls(fetch)[0]?.url).toBe(`${BASE}/rest/v1/rpc/create_record`)
194
+ expect(outcome.data).toEqual([ROW])
195
+ })
196
+ })
197
+
198
+ describe("insert on a model that keeps no drafts", () => {
199
+ afterEach(() => {
200
+ forgetRegisteredDraftModels()
201
+ vi.unstubAllGlobals()
202
+ })
203
+
204
+ it("is a plain insert asking for the row back", async () => {
205
+ registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
206
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1 }], 201))))
207
+ await client().from("tags").insert({ label: "news" })
208
+ const [only] = fetchCalls(fetch)
209
+ expect(only?.url).toBe(`${BASE}/rest/v1/tags`)
210
+ expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
211
+ })
212
+
213
+ it("is a plain insert when nothing was registered, as for a client built without the generated file", async () => {
214
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([ROW], 201))))
215
+ await client().from("posts").insert({ title: "Mine" })
216
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
217
+ })
218
+
219
+ it("ignores a document from a newer generator", async () => {
220
+ registerDraftModels({ version: 2, tables: { posts: { primaryKey: "id" } } })
221
+ const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([ROW], 201))))
222
+ await client().from("posts").insert({ title: "Mine" })
223
+ expect(fetchCalls(fetch).map((call) => call.url)).toEqual([`${BASE}/rest/v1/posts`])
224
+ })
225
+ })
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
2
2
  import { QueryBuilder } from "../src/query.js"
3
3
  import { DRAFT_SCHEMA } from "../src/types.js"
4
4
  import { createClient } from "../src/index.js"
5
+ import { fetchCall, fetchCalls, fetchReturning, header, jsonResponse, requestUrl } from "./support/fetch-mock.js"
5
6
 
6
7
  // Reading a draft changes one thing about the request: which schema answers it. Same table name,
7
8
  // same row type, one header. These tests pin that the header is actually sent, because a silently
@@ -10,25 +11,11 @@ import { createClient } from "../src/index.js"
10
11
  const BASE = "http://localhost:18473"
11
12
  const HEADERS: Record<string, string> = { apikey: "anon-key" }
12
13
 
13
- function captureHeaders(): {
14
- headers: () => Record<string, string>
15
- fetch: ReturnType<typeof vi.fn>
16
- } {
17
- const fetch = vi.fn().mockResolvedValue({
18
- ok: true,
19
- status: 200,
20
- json: vi.fn().mockResolvedValue([]),
21
- text: vi.fn().mockResolvedValue("[]"),
22
- headers: { get: () => null },
23
- })
14
+ /** A fetch answering every request with no rows, and a reader for the first request's headers. */
15
+ function captureHeaders(): { header: (name: string) => string | null } {
16
+ const fetch = fetchReturning([])
24
17
  vi.stubGlobal("fetch", fetch)
25
- return {
26
- fetch,
27
- headers: () => {
28
- const init = (fetch.mock.calls[0] as [string, { headers: Record<string, string> }])[1]
29
- return init.headers
30
- },
31
- }
18
+ return { header: (name) => header(fetchCall(fetch).init, name) }
32
19
  }
33
20
 
34
21
  const SESSION_JWT =
@@ -44,20 +31,20 @@ describe("the draft profile", () => {
44
31
  await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id", undefined, undefined, {
45
32
  profile: DRAFT_SCHEMA,
46
33
  })
47
- expect(captured.headers()["Accept-Profile"]).toBe("draft")
34
+ expect(captured.header("Accept-Profile")).toBe("draft")
48
35
  })
49
36
 
50
37
  it("is absent from an ordinary read, so published content is what a caller gets by default", async () => {
51
38
  const captured = captureHeaders()
52
39
  await new QueryBuilder(BASE, "/rest/v1/posts", HEADERS, "id")
53
- expect(captured.headers()["Accept-Profile"]).toBeUndefined()
40
+ expect(captured.header("Accept-Profile")).toBeNull()
54
41
  })
55
42
 
56
43
  it("reaches the request through `from().draft().select()`", async () => {
57
44
  const captured = captureHeaders()
58
45
  const client = createClient({ url: BASE, anonKey: "anon-key" })
59
46
  await client.from("posts").draft().select("id, title")
60
- expect(captured.headers()["Accept-Profile"]).toBe("draft")
47
+ expect(captured.header("Accept-Profile")).toBe("draft")
61
48
  })
62
49
 
63
50
  it("does not leak onto the next query from the same client", async () => {
@@ -67,12 +54,12 @@ describe("the draft profile", () => {
67
54
  const client = createClient({ url: BASE, anonKey: "anon-key" })
68
55
  const drafted = captureHeaders()
69
56
  await client.from("posts").draft().select("id")
70
- expect(drafted.headers()["Accept-Profile"]).toBe("draft")
57
+ expect(drafted.header("Accept-Profile")).toBe("draft")
71
58
 
72
59
  vi.restoreAllMocks()
73
60
  const plain = captureHeaders()
74
61
  await client.from("posts").select("id")
75
- expect(plain.headers()["Accept-Profile"]).toBeUndefined()
62
+ expect(plain.header("Accept-Profile")).toBeNull()
76
63
  })
77
64
 
78
65
  it("leaves the count header alone, since a draft read can still be counted", async () => {
@@ -81,8 +68,8 @@ describe("the draft profile", () => {
81
68
  profile: DRAFT_SCHEMA,
82
69
  count: "exact",
83
70
  })
84
- expect(captured.headers()["Accept-Profile"]).toBe("draft")
85
- expect(captured.headers()["Prefer"]).toBe("count=exact")
71
+ expect(captured.header("Accept-Profile")).toBe("draft")
72
+ expect(captured.header("Prefer")).toBe("count=exact")
86
73
  })
87
74
  })
88
75
 
@@ -96,15 +83,15 @@ describe("calling a function outside the default schema", () => {
96
83
  // mistake.
97
84
  const captured = captureHeaders()
98
85
  const client = createClient({ url: BASE, anonKey: "anon-key" })
99
- await client.rpc("publish" as never, { model_table: "posts" } as never, { schema: "supatype" })
100
- expect(captured.headers()["Content-Profile"]).toBe("supatype")
86
+ await client.rpc("publish", { model_table: "posts" }, { schema: "supatype" })
87
+ expect(captured.header("Content-Profile")).toBe("supatype")
101
88
  })
102
89
 
103
90
  it("sends none for a function in the default schema", async () => {
104
91
  const captured = captureHeaders()
105
92
  const client = createClient({ url: BASE, anonKey: "anon-key" })
106
- await client.rpc("calculate_shipping" as never, {} as never)
107
- expect(captured.headers()["Content-Profile"]).toBeUndefined()
93
+ await client.rpc("calculate_shipping", {})
94
+ expect(captured.header("Content-Profile")).toBeNull()
108
95
  })
109
96
  })
110
97
 
@@ -119,43 +106,32 @@ describe("a preview link as the client's credential", () => {
119
106
  * these tests care about is on the *second* request, not the first.
120
107
  */
121
108
  function previewFetch(exchange: { ok: boolean; token?: string; expiresAt?: string }): {
122
- calls: () => Array<[string, { headers: Record<string, string> }]>
123
- queryHeaders: () => Record<string, string>
109
+ queryHeaders: () => string[]
110
+ queryHeader: (name: string) => string | null
124
111
  exchanges: () => number
125
112
  } {
126
- const fetch = vi.fn().mockImplementation((url: string) => {
127
- if (url.endsWith("/preview-links/resolve")) {
128
- return Promise.resolve({
129
- ok: exchange.ok,
130
- status: exchange.ok ? 200 : 404,
131
- json: () =>
132
- Promise.resolve(
133
- exchange.ok
134
- ? { token: exchange.token, expiresAt: exchange.expiresAt }
135
- : { error: "gone" },
136
- ),
137
- headers: { get: () => null },
138
- })
113
+ const isExchange = (url: string): boolean => url.endsWith("/preview-links/resolve")
114
+ const fetchMock = vi.fn<typeof fetch>((input) => {
115
+ if (isExchange(requestUrl(input))) {
116
+ const body = exchange.ok ? { token: exchange.token, expiresAt: exchange.expiresAt } : { error: "gone" }
117
+ return Promise.resolve(jsonResponse(body, exchange.ok ? 200 : 404))
139
118
  }
140
- return Promise.resolve({
141
- ok: true,
142
- status: 200,
143
- json: () => Promise.resolve([]),
144
- text: () => Promise.resolve("[]"),
145
- headers: { get: () => null },
146
- })
119
+ return Promise.resolve(jsonResponse([]))
147
120
  })
148
- vi.stubGlobal("fetch", fetch)
149
- const calls = (): Array<[string, { headers: Record<string, string> }]> =>
150
- fetch.mock.calls as Array<[string, { headers: Record<string, string> }]>
121
+ vi.stubGlobal("fetch", fetchMock)
122
+ const queryInit = (): RequestInit => {
123
+ const call = fetchCalls(fetchMock).find(({ url }) => !isExchange(url))
124
+ if (call === undefined) throw new Error("no query was made")
125
+ return call.init
126
+ }
151
127
  return {
152
- calls,
153
- exchanges: () => calls().filter(([url]) => url.endsWith("/preview-links/resolve")).length,
128
+ exchanges: () => fetchCalls(fetchMock).filter(({ url }) => isExchange(url)).length,
154
129
  queryHeaders: () => {
155
- const call = calls().find(([url]) => !url.endsWith("/preview-links/resolve"))
156
- if (call === undefined) throw new Error("no query was made")
157
- return call[1].headers
130
+ const lines: string[] = []
131
+ new Headers(queryInit().headers).forEach((value, name) => lines.push(`${name}: ${value}`))
132
+ return lines
158
133
  },
134
+ queryHeader: (name) => header(queryInit(), name),
159
135
  }
160
136
  }
161
137
 
@@ -165,7 +141,7 @@ describe("a preview link as the client's credential", () => {
165
141
  const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
166
142
  const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
167
143
  await client.from("posts").draft().select("id")
168
- expect(f.queryHeaders()["Authorization"]).toBe("Bearer exchanged.jwt")
144
+ expect(f.queryHeader("Authorization")).toBe("Bearer exchanged.jwt")
169
145
  })
170
146
 
171
147
  it("never puts the code itself on the query", async () => {
@@ -181,7 +157,7 @@ describe("a preview link as the client's credential", () => {
181
157
  const f = previewFetch({ ok: true, token: "exchanged.jwt", expiresAt: anHour() })
182
158
  const client = createClient({ url: BASE, anonKey: "anon-key", previewCode: "pl_abc.secret" })
183
159
  await client.from("posts").draft().select("id")
184
- expect(f.queryHeaders()["apikey"]).toBe("anon-key")
160
+ expect(f.queryHeader("apikey")).toBe("anon-key")
185
161
  })
186
162
 
187
163
  it("exchanges once for several queries in flight together", async () => {
@@ -235,13 +211,13 @@ describe("a preview link as the client's credential", () => {
235
211
  const captured = captureHeaders()
236
212
  const client = createClient({ url: BASE, anonKey: "anon-key" })
237
213
  await client.from("posts").select("id")
238
- expect(captured.headers()["Authorization"]).toBe("Bearer anon-key")
214
+ expect(captured.header("Authorization")).toBe("Bearer anon-key")
239
215
  })
240
216
  })
241
217
 
242
218
  describe("what storage sends as its credential", () => {
243
- // Storage was handed a plain headers object built when the client was constructed — before
244
- // anybody has signed in. Every storage request therefore carried the anon key for the life of the
219
+ // Storage was handed a plain headers object built when the client was constructed, before
220
+ // anybody had signed in. Every storage request therefore carried the anon key for the life of the
245
221
  // page: an app's per-user storage policies saw `anon` rather than the caller, and through Studio's
246
222
  // proxy the request was refused outright, because an anon key carries no `sub` and the proxy
247
223
  // requires one. The symptom was "Token missing subject claim" on a page that lists buckets.
@@ -249,19 +225,18 @@ describe("what storage sends as its credential", () => {
249
225
  // Every other client on the object already resolved its headers per request. Storage was the one
250
226
  // that did not.
251
227
 
252
- function captureHeaders(): { headers: () => Record<string, string> } {
253
- const fetchMock = vi.fn().mockResolvedValue({
254
- ok: true,
255
- status: 200,
256
- json: vi.fn().mockResolvedValue([]),
257
- text: vi.fn().mockResolvedValue("[]"),
258
- headers: { get: () => null },
259
- })
228
+ /** A fetch that knows the signed-in user and has no buckets, and the bucket request's headers. */
229
+ function captureHeaders(): { header: (name: string) => string | null } {
230
+ const isUser = (url: string): boolean => url.endsWith("/auth/v1/user")
231
+ const fetchMock = vi.fn<typeof fetch>((input) =>
232
+ Promise.resolve(jsonResponse(isUser(requestUrl(input)) ? { id: "u1", role: "authenticated" } : [])),
233
+ )
260
234
  vi.stubGlobal("fetch", fetchMock)
261
235
  return {
262
- headers: () => {
263
- const call = fetchMock.mock.calls[0] as [string, { headers: Record<string, string> }]
264
- return call[1].headers
236
+ header: (name) => {
237
+ const call = fetchCalls(fetchMock).find(({ url }) => !isUser(url))
238
+ if (call === undefined) throw new Error("storage made no request")
239
+ return header(call.init, name)
265
240
  },
266
241
  }
267
242
  }
@@ -271,22 +246,18 @@ describe("what storage sends as its credential", () => {
271
246
  const client = createClient({ url: BASE, anonKey: "anon-key" })
272
247
  // A session arriving after construction, which is the ordinary case: the client is built while
273
248
  // the page loads and the person signs in afterwards.
274
- ;(client.auth as unknown as { currentSession: unknown }).currentSession = {
275
- accessToken: SESSION_JWT,
276
- refreshToken: "r",
277
- expiresAt: Math.floor(Date.now() / 1000) + 3600,
278
- user: { id: "u1" },
279
- }
249
+ const { error } = await client.auth.setSession({ accessToken: SESSION_JWT, refreshToken: "r" })
250
+ expect(error).toBeNull()
280
251
 
281
252
  await client.storage.listBuckets()
282
- expect(captured.headers()["Authorization"]).toBe(`Bearer ${SESSION_JWT}`)
253
+ expect(captured.header("Authorization")).toBe(`Bearer ${SESSION_JWT}`)
283
254
  })
284
255
 
285
256
  it("falls back to the anon key when nobody is signed in", async () => {
286
257
  const captured = captureHeaders()
287
258
  const client = createClient({ url: BASE, anonKey: "anon-key" })
288
259
  await client.storage.listBuckets()
289
- expect(captured.headers()["Authorization"]).toBe("Bearer anon-key")
260
+ expect(captured.header("Authorization")).toBe("Bearer anon-key")
290
261
  })
291
262
 
292
263
  it("uses the service role when the caller holds one", async () => {
@@ -294,6 +265,6 @@ describe("what storage sends as its credential", () => {
294
265
  const captured = captureHeaders()
295
266
  const client = createClient({ url: BASE, anonKey: "anon-key", serviceRoleKey: "service.jwt" })
296
267
  await client.storage.listBuckets()
297
- expect(captured.headers()["Authorization"]).toBe("Bearer service.jwt")
268
+ expect(captured.header("Authorization")).toBe("Bearer service.jwt")
298
269
  })
299
270
  })
@@ -0,0 +1,122 @@
1
+ import { createHmac } from "node:crypto"
2
+ import { createServer, request, type IncomingMessage, type Server, type ServerResponse } from "node:http"
3
+ import type { AddressInfo } from "node:net"
4
+ import { afterAll, beforeAll, describe, expect, it } from "vitest"
5
+ import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase } from "../src/index.js"
6
+
7
+ /**
8
+ * An editor's update on a drafts model, against a real PostgREST and Postgres.
9
+ *
10
+ * The same setup as `draft-insert.integration.test.ts`: `posts` from the engine's `versioned_blog`
11
+ * fixture with read `published_at <= now()` and create and update for the `editor` role, and an API
12
+ * editor with no Studio membership. The update saves a draft and the public keeps reading what was
13
+ * published, until the update asks to publish; a raw `PATCH` of the table is refused by the database.
14
+ *
15
+ * Needs `SUPATYPE_DRAFTS_REST_URL` and `SUPATYPE_DRAFTS_JWT_SECRET`, as that suite does. Skips
16
+ * otherwise.
17
+ */
18
+ const restUrl = process.env["SUPATYPE_DRAFTS_REST_URL"]
19
+ const jwtSecret = process.env["SUPATYPE_DRAFTS_JWT_SECRET"]
20
+ const EDITOR = "11111111-1111-1111-1111-111111111111"
21
+
22
+ /** An HS256 token carrying `claims`, signed as the auth server signs one. */
23
+ function token(claims: Record<string, unknown>): string {
24
+ const part = (value: object): string => Buffer.from(JSON.stringify(value)).toString("base64url")
25
+ const unsigned = `${part({ alg: "HS256", typ: "JWT" })}.${part({ ...claims, exp: Math.floor(Date.now() / 1000) + 600 })}`
26
+ return `${unsigned}.${createHmac("sha256", jwtSecret ?? "").update(unsigned).digest("base64url")}`
27
+ }
28
+
29
+ const ANON_KEY = (): string => token({ role: "anon" })
30
+ const EDITOR_SESSION = (): string => token({ sub: EDITOR, role: "authenticated", app_metadata: { role: "editor" } })
31
+
32
+ /** Forward `/rest/v1/<rest>` to PostgREST's `/<rest>`, as the gateway mounts it. */
33
+ function forward(upstream: URL) {
34
+ return (req: IncomingMessage, res: ServerResponse): void => {
35
+ const path = (req.url ?? "/").replace(/^\/rest\/v1/, "")
36
+ const out = request(new URL(path, upstream), { method: req.method, headers: { ...req.headers, host: upstream.host } }, (answer) => {
37
+ res.writeHead(answer.statusCode ?? 502, answer.headers)
38
+ answer.pipe(res)
39
+ })
40
+ out.on("error", () => res.writeHead(502).end())
41
+ req.pipe(out)
42
+ }
43
+ }
44
+
45
+ describe.skipIf(restUrl === undefined || jwtSecret === undefined)("an API editor's update on a drafts model", () => {
46
+ let proxy: Server
47
+ let base = ""
48
+
49
+ beforeAll(async () => {
50
+ proxy = createServer(forward(new URL(restUrl ?? "")))
51
+ await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve))
52
+ const address: AddressInfo | string | null = proxy.address()
53
+ base = typeof address === "object" && address !== null ? `http://127.0.0.1:${address.port}` : ""
54
+ registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
55
+ })
56
+
57
+ afterAll(async () => {
58
+ forgetRegisteredDraftModels()
59
+ await new Promise<void>((resolve) => proxy.close(() => resolve()))
60
+ })
61
+
62
+ const editor = () =>
63
+ createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY(), headers: { Authorization: `Bearer ${EDITOR_SESSION()}` } })
64
+ const reader = () => createClient<AnyDatabase>({ url: base, anonKey: ANON_KEY() })
65
+
66
+ /** A post the editor has created and published, by its id. */
67
+ async function publishedPost(title: string): Promise<string> {
68
+ const { data } = await editor().from("posts").insert({ title }).select("id").single()
69
+ const id = String(data?.["id"])
70
+ const published = await editor().rpc("publish", { model_table: "posts", record_id: id }, { schema: "supatype" })
71
+ expect(published.error).toBeNull()
72
+ return id
73
+ }
74
+
75
+ it("saves a draft, returns it, and leaves what the public reads alone", async () => {
76
+ const stamp = Date.now()
77
+ const id = await publishedPost(`Published ${stamp}`)
78
+
79
+ const { data, error } = await editor().from("posts").update({ title: `Draft ${stamp}` }).eq("id", id).select("title")
80
+
81
+ expect(error).toBeNull()
82
+ expect(data).toEqual([{ title: `Draft ${stamp}` }])
83
+ const publicly = await reader().from("posts").select("title").eq("id", id)
84
+ expect(publicly).toMatchObject({ data: [{ title: `Published ${stamp}` }], error: null })
85
+ const drafted = await editor().from("posts").draft().select("title").eq("id", id)
86
+ expect(drafted.data).toEqual([{ title: `Draft ${stamp}` }])
87
+ })
88
+
89
+ it("publishes in the same call with { publish: true }, so the public reads the new version", async () => {
90
+ const stamp = Date.now()
91
+ const id = await publishedPost(`Before ${stamp}`)
92
+
93
+ const { error } = await editor().from("posts").update({ title: `After ${stamp}` }, { publish: true }).eq("id", id)
94
+
95
+ expect(error).toBeNull()
96
+ const publicly = await reader().from("posts").select("title").eq("id", id)
97
+ expect(publicly).toMatchObject({ data: [{ title: `After ${stamp}` }], error: null })
98
+ // Recorded as a version, which is what the draft view reads, and that version is the live one.
99
+ const newest = await editor().from("posts").draft().select("title").eq("id", id)
100
+ expect(newest.data).toEqual([{ title: `After ${stamp}` }])
101
+ const again = await editor().rpc("publish", { model_table: "posts", record_id: id }, { schema: "supatype" })
102
+ expect(again.error?.message).toContain("is already live")
103
+ })
104
+
105
+ it("is refused as a raw PATCH, naming drafts and publish", async () => {
106
+ const stamp = Date.now()
107
+ const id = await publishedPost(`Raw ${stamp}`)
108
+
109
+ const res = await fetch(`${base}/rest/v1/posts?id=eq.${id}`, {
110
+ method: "PATCH",
111
+ headers: { apikey: ANON_KEY(), Authorization: `Bearer ${EDITOR_SESSION()}`, "Content-Type": "application/json" },
112
+ body: JSON.stringify({ title: `Patched ${stamp}` }),
113
+ })
114
+ const refusal: unknown = await res.json()
115
+
116
+ expect(res.status).toBe(403)
117
+ expect(refusal).toMatchObject({ code: "42501" })
118
+ expect(JSON.stringify(refusal)).toContain("posts has drafts")
119
+ const publicly = await reader().from("posts").select("title").eq("id", id)
120
+ expect(publicly.data).toEqual([{ title: `Raw ${stamp}` }])
121
+ })
122
+ })