@supatype/client 0.9.0 → 0.9.2
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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +76 -68
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +82 -0
- package/dist/auth.d.ts +50 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +117 -32
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +3 -0
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -0
- package/dist/bindings.js.map +1 -1
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +7 -0
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +81 -21
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +133 -46
- package/dist/errors.js.map +1 -1
- package/dist/graphql-transport.d.ts +8 -1
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js +5 -5
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -37
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +44 -0
- package/dist/latest-rows.d.ts.map +1 -0
- package/dist/latest-rows.js +58 -0
- package/dist/latest-rows.js.map +1 -0
- package/dist/mutation-request.d.ts +2 -1
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +2 -1
- package/dist/mutation-request.js.map +1 -1
- package/dist/page-env-script.d.ts +12 -0
- package/dist/page-env-script.d.ts.map +1 -0
- package/dist/page-env-script.js +30 -0
- package/dist/page-env-script.js.map +1 -0
- package/dist/preview.d.ts +2 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +7 -3
- package/dist/preview.js.map +1 -1
- package/dist/query.d.ts +18 -5
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +33 -16
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +22 -8
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +121 -41
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +59 -0
- package/dist/runtime-env.d.ts.map +1 -0
- package/dist/runtime-env.js +202 -0
- package/dist/runtime-env.js.map +1 -0
- package/dist/setup-fault.d.ts +13 -0
- package/dist/setup-fault.d.ts.map +1 -0
- package/dist/setup-fault.js +17 -0
- package/dist/setup-fault.js.map +1 -0
- package/dist/storage.d.ts +10 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +22 -13
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +5 -3
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +8 -5
- package/dist/table-subscription.js.map +1 -1
- package/dist/thrown-error.d.ts +16 -0
- package/dist/thrown-error.d.ts.map +1 -0
- package/dist/thrown-error.js +31 -0
- package/dist/thrown-error.js.map +1 -0
- package/dist/types.d.ts +64 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -1
- package/src/auth.ts +121 -36
- package/src/bindings.ts +3 -0
- package/src/error-codes-doc.ts +9 -1
- package/src/errors.ts +155 -57
- package/src/graphql-transport.ts +5 -6
- package/src/index.ts +63 -45
- package/src/latest-rows.ts +95 -0
- package/src/mutation-request.ts +3 -2
- package/src/page-env-script.ts +27 -0
- package/src/preview.ts +8 -4
- package/src/query.ts +38 -19
- package/src/realtime.ts +146 -44
- package/src/runtime-env.ts +262 -0
- package/src/setup-fault.ts +18 -0
- package/src/storage.ts +26 -16
- package/src/table-subscription.ts +8 -6
- package/src/thrown-error.ts +31 -0
- package/src/types.ts +70 -14
- package/tests/auth-errors.test.ts +3 -3
- package/tests/auth-events.test.ts +3 -7
- package/tests/auth-sso.test.ts +291 -0
- package/tests/auth-url-session.test.ts +6 -25
- package/tests/entry-points.test.ts +9 -0
- package/tests/error-family.test.ts +79 -0
- package/tests/examples-runtime-env.test.ts +135 -0
- package/tests/helpers/auth-unmount-binding.ts +63 -0
- package/tests/helpers/mock-websocket.ts +22 -0
- package/tests/helpers/oauth-binding.ts +4 -3
- package/tests/helpers/reactive-options-binding.ts +99 -0
- package/tests/helpers/stale-read-binding.ts +113 -0
- package/tests/helpers/thrown-error-binding.ts +127 -0
- package/tests/postgrest-error-codes.test.ts +4 -4
- package/tests/query.test.ts +39 -2
- package/tests/rate-limit-integration.test.ts +1 -1
- package/tests/realtime-multi-tenant-integration.test.ts +0 -1
- package/tests/realtime-refusal-error.test.ts +79 -0
- package/tests/realtime-rows-after-broadcast.test.ts +205 -0
- package/tests/realtime-session-auth.test.ts +0 -1
- package/tests/realtime-shared-channel.test.ts +9 -27
- package/tests/result-error-class.test.ts +107 -0
- package/tests/retry-policy.test.ts +1 -1
- package/tests/runtime-env-bundle.test.ts +121 -0
- package/tests/runtime-env-expo.test.ts +58 -0
- package/tests/runtime-env-page-script.test.ts +174 -0
- package/tests/runtime-env.test.ts +259 -0
- package/tests/server-bodies.test.ts +3 -3
- package/tests/subscribe-frame.test.ts +48 -0
- package/tests/support/browser.ts +28 -0
- package/tests/support/jwt.ts +5 -0
- package/tests/thrown-error.test.ts +59 -0
- package/tsconfig.json +2 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A build that never received its address and anon key still finds them at run time.
|
|
3
|
+
*
|
|
4
|
+
* When Supatype hosts an app, `<script src="/supatype-env.js">` sets `globalThis.__SUPATYPE_ENV__`
|
|
5
|
+
* to the deployment's `{ url, anonKey }`; a Next.js app gets the same script from the route
|
|
6
|
+
* `@supatype/ssr/next` exports. The client reads it for whichever value it was not given.
|
|
7
|
+
*
|
|
8
|
+
* `createClient` never throws for a missing value. `next build` prerenders every static page, so a
|
|
9
|
+
* client created at module scope runs during the build, which has no values and needs none: it
|
|
10
|
+
* sends nothing. The first request is what needs them, so that is where the check is, and it reads
|
|
11
|
+
* the page again then, because the script may load after the module that created the client.
|
|
12
|
+
* With neither, that request throws one error naming the values, every name to set and each fix.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
16
|
+
import { createClient, MissingClientValuesError, type SupatypeClient } from "../src/index.js"
|
|
17
|
+
|
|
18
|
+
const DEPLOYED = { url: "https://api.example.com", anonKey: "deployed-anon-key" }
|
|
19
|
+
|
|
20
|
+
const FRONTEND_PREFIXES = ["VITE_", "PUBLIC_", "NEXT_PUBLIC_", "EXPO_PUBLIC_"]
|
|
21
|
+
|
|
22
|
+
afterEach(() => {
|
|
23
|
+
vi.unstubAllGlobals()
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
/** Every request's address and apikey, answered with an empty list. */
|
|
27
|
+
function captureRequests(): Array<{ url: string; apikey: string | null }> {
|
|
28
|
+
const seen: Array<{ url: string; apikey: string | null }> = []
|
|
29
|
+
vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {
|
|
30
|
+
seen.push({ url, apikey: new Headers(init?.headers).get("apikey") })
|
|
31
|
+
return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
|
|
32
|
+
})
|
|
33
|
+
return seen
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The error `run` throws or rejects with, or a failure when it settles without one. */
|
|
37
|
+
async function failureOf(run: () => unknown): Promise<unknown> {
|
|
38
|
+
try {
|
|
39
|
+
await run()
|
|
40
|
+
} catch (err) {
|
|
41
|
+
return err
|
|
42
|
+
}
|
|
43
|
+
throw new Error("expected the request to throw")
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The message of the named error `run` fails with. */
|
|
47
|
+
async function namedErrorOf(run: () => unknown): Promise<string> {
|
|
48
|
+
const err = await failureOf(run)
|
|
49
|
+
expect(err).toBeInstanceOf(MissingClientValuesError)
|
|
50
|
+
return err instanceof Error ? err.message : String(err)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Run as a page would: a `window`, which is where the client looks for the page's values. */
|
|
54
|
+
function inBrowser(): void {
|
|
55
|
+
vi.stubGlobal("window", globalThis)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** One request through each service the client fronts, so each is shown to check first. */
|
|
59
|
+
const FIRST_REQUESTS: ReadonlyArray<readonly [string, (client: SupatypeClient) => unknown]> = [
|
|
60
|
+
["a table read", (c) => c.from("posts").select()],
|
|
61
|
+
["a table write", (c) => c.from("posts").delete().eq("id", "1")],
|
|
62
|
+
["an rpc call", (c) => c.rpc("hello")],
|
|
63
|
+
["a sign-in", (c) => c.auth.signInWithPassword({ email: "a@example.com", password: "pw" })],
|
|
64
|
+
["a storage list", (c) => c.storage.from("avatars").list()],
|
|
65
|
+
["a bucket list", (c) => c.storage.listBuckets()],
|
|
66
|
+
["a function call", (c) => c.functions.invoke("hello")],
|
|
67
|
+
["a GraphQL query", (c) => c.graphql("{ __typename }")],
|
|
68
|
+
["a realtime connect", (c) => c.realtime.channel("public:posts").subscribe()],
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
describe("createClient without an address or anon key", () => {
|
|
72
|
+
it("does not throw, so a page prerendered without values still builds", () => {
|
|
73
|
+
expect(() => createClient({})).not.toThrow()
|
|
74
|
+
expect(() => createClient({ url: "", anonKey: undefined })).not.toThrow()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it.each(FIRST_REQUESTS)("throws the named error on %s, and sends nothing", async (_label, request) => {
|
|
78
|
+
const seen = captureRequests()
|
|
79
|
+
await namedErrorOf(() => request(createClient({})))
|
|
80
|
+
expect(seen).toEqual([])
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it("names both values, every frontend name, the server names and each fix", async () => {
|
|
84
|
+
inBrowser()
|
|
85
|
+
const message = await namedErrorOf(() => createClient({}).from("posts").select())
|
|
86
|
+
|
|
87
|
+
expect(message).toContain("API address and anon key")
|
|
88
|
+
for (const prefix of FRONTEND_PREFIXES) {
|
|
89
|
+
expect(message).toContain(`${prefix}SUPATYPE_URL`)
|
|
90
|
+
expect(message).toContain(`${prefix}SUPATYPE_ANON_KEY`)
|
|
91
|
+
}
|
|
92
|
+
expect(message).toContain("supatype build")
|
|
93
|
+
expect(message).toContain('<script src="/supatype-env.js" vite-ignore></script>')
|
|
94
|
+
expect(message).toContain("app/supatype-env.js/route.ts")
|
|
95
|
+
expect(message).toContain("@supatype/ssr/next")
|
|
96
|
+
expect(message).toContain('strategy="beforeInteractive"')
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it("names only the anon key when the address was given", async () => {
|
|
100
|
+
inBrowser()
|
|
101
|
+
const message = await namedErrorOf(() => createClient({ url: "https://built.example.com" }).from("posts").select())
|
|
102
|
+
|
|
103
|
+
expect(message).toContain("no anon key")
|
|
104
|
+
for (const prefix of FRONTEND_PREFIXES) expect(message).toContain(`${prefix}SUPATYPE_ANON_KEY`)
|
|
105
|
+
expect(message).toContain("set SUPATYPE_ANON_KEY")
|
|
106
|
+
expect(message).not.toContain("SUPATYPE_URL")
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it("names only the address when the anon key was given", async () => {
|
|
110
|
+
inBrowser()
|
|
111
|
+
const message = await namedErrorOf(() => createClient({ anonKey: "built-key" }).from("posts").select())
|
|
112
|
+
|
|
113
|
+
expect(message).toContain("no API address")
|
|
114
|
+
for (const prefix of FRONTEND_PREFIXES) expect(message).toContain(`${prefix}SUPATYPE_URL`)
|
|
115
|
+
expect(message).not.toContain("SUPATYPE_ANON_KEY")
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it("does not fall back to the page's own origin for the address", async () => {
|
|
119
|
+
vi.stubGlobal("location", { origin: "https://app.example.com" })
|
|
120
|
+
const seen = captureRequests()
|
|
121
|
+
|
|
122
|
+
const message = await namedErrorOf(() => createClient({ anonKey: "built-key" }).from("posts").select())
|
|
123
|
+
|
|
124
|
+
expect(message).toContain("VITE_SUPATYPE_URL")
|
|
125
|
+
expect(seen).toEqual([])
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
it("does not make up a public file URL with no address", async () => {
|
|
129
|
+
await namedErrorOf(() => createClient({}).storage.from("avatars").getPublicUrl("a.png"))
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
describe("the error on a server, where there is no page", () => {
|
|
134
|
+
it("names the server's variables first, then the build-time names, and no page global", async () => {
|
|
135
|
+
const message = await namedErrorOf(() => createClient({}).from("posts").select())
|
|
136
|
+
|
|
137
|
+
expect(message).not.toContain("window.__SUPATYPE_ENV__")
|
|
138
|
+
const serverNames = message.indexOf("Set SUPATYPE_URL and SUPATYPE_ANON_KEY in the server's environment")
|
|
139
|
+
expect(serverNames).toBeGreaterThan(-1)
|
|
140
|
+
expect(serverNames).toBeLessThan(message.indexOf("VITE_SUPATYPE_URL"))
|
|
141
|
+
expect(message).toContain("createServerClient")
|
|
142
|
+
expect(message).toContain("supatype build")
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("names only the server variable for the value that is missing", async () => {
|
|
146
|
+
const message = await namedErrorOf(() => createClient({ url: "https://api.example.com" }).from("posts").select())
|
|
147
|
+
|
|
148
|
+
expect(message).toContain("Set SUPATYPE_ANON_KEY in the server's environment")
|
|
149
|
+
expect(message).not.toContain("SUPATYPE_URL")
|
|
150
|
+
})
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
describe("the page's __SUPATYPE_ENV__", () => {
|
|
154
|
+
it("supplies both values", async () => {
|
|
155
|
+
vi.stubGlobal("__SUPATYPE_ENV__", DEPLOYED)
|
|
156
|
+
const seen = captureRequests()
|
|
157
|
+
|
|
158
|
+
const client = createClient({})
|
|
159
|
+
await client.from("posts").select()
|
|
160
|
+
|
|
161
|
+
expect(client.url).toBe(DEPLOYED.url)
|
|
162
|
+
expect(seen[0]?.url.startsWith("https://api.example.com/rest/v1/posts")).toBe(true)
|
|
163
|
+
expect(seen[0]?.apikey).toBe(DEPLOYED.anonKey)
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
it("is read at the first request, so a script that loads after the client is created counts", async () => {
|
|
167
|
+
const seen = captureRequests()
|
|
168
|
+
const client = createClient({ url: "", anonKey: undefined })
|
|
169
|
+
expect(client.url).toBe("")
|
|
170
|
+
|
|
171
|
+
vi.stubGlobal("__SUPATYPE_ENV__", DEPLOYED)
|
|
172
|
+
await client.from("posts").select()
|
|
173
|
+
await client.storage.listBuckets()
|
|
174
|
+
|
|
175
|
+
expect(client.url).toBe(DEPLOYED.url)
|
|
176
|
+
expect(seen.map((r) => r.url)).toEqual([
|
|
177
|
+
expect.stringMatching(/^https:\/\/api\.example\.com\/rest\/v1\/posts/),
|
|
178
|
+
"https://api.example.com/storage/v1/bucket",
|
|
179
|
+
])
|
|
180
|
+
expect(seen.every((r) => r.apikey === DEPLOYED.anonKey)).toBe(true)
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it("lets the values the client was given win", async () => {
|
|
184
|
+
vi.stubGlobal("__SUPATYPE_ENV__", DEPLOYED)
|
|
185
|
+
const seen = captureRequests()
|
|
186
|
+
|
|
187
|
+
const client = createClient({ url: "https://built.example.com", anonKey: "built-key" })
|
|
188
|
+
await client.from("posts").select()
|
|
189
|
+
|
|
190
|
+
expect(client.url).toBe("https://built.example.com")
|
|
191
|
+
expect(seen[0]?.apikey).toBe("built-key")
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
it("resolves each value on its own", async () => {
|
|
195
|
+
vi.stubGlobal("__SUPATYPE_ENV__", DEPLOYED)
|
|
196
|
+
const seen = captureRequests()
|
|
197
|
+
|
|
198
|
+
await createClient({ url: "https://built.example.com" }).from("posts").select()
|
|
199
|
+
await createClient({ anonKey: "built-key" }).from("posts").select()
|
|
200
|
+
|
|
201
|
+
expect(seen.map((r) => [new URL(r.url).origin, r.apikey])).toEqual([
|
|
202
|
+
["https://built.example.com", DEPLOYED.anonKey],
|
|
203
|
+
[DEPLOYED.url, "built-key"],
|
|
204
|
+
])
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
it.each([
|
|
208
|
+
["a string", "https://api.example.com"],
|
|
209
|
+
["null", null],
|
|
210
|
+
["an array", [DEPLOYED.url, DEPLOYED.anonKey]],
|
|
211
|
+
["fields of the wrong type", { url: 42, anonKey: { key: "x" } }],
|
|
212
|
+
["empty fields", { url: "", anonKey: "" }],
|
|
213
|
+
])("is ignored when it holds %s", async (_label, value) => {
|
|
214
|
+
vi.stubGlobal("__SUPATYPE_ENV__", value)
|
|
215
|
+
const message = await namedErrorOf(() => createClient({ url: "https://built.example.com" }).from("posts").select())
|
|
216
|
+
expect(message).toContain("anon key")
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
it("is ignored for an address that is not http or https", async () => {
|
|
220
|
+
vi.stubGlobal("__SUPATYPE_ENV__", { url: "javascript:alert(1)", anonKey: "k" })
|
|
221
|
+
const message = await namedErrorOf(() => createClient({}).from("posts").select())
|
|
222
|
+
expect(message).toContain("VITE_SUPATYPE_URL")
|
|
223
|
+
})
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* 0.9.1 release test RB2: the gateway now refuses a path with an empty part, so an address written
|
|
228
|
+
* with a trailing "/" (`SUPATYPE_URL=https://api.example.com/`) must not build `//rest/v1/...`.
|
|
229
|
+
*/
|
|
230
|
+
describe("an address ending in /", () => {
|
|
231
|
+
const SERVICE_REQUESTS = FIRST_REQUESTS.filter(([label]) => label !== "a realtime connect")
|
|
232
|
+
|
|
233
|
+
/** Each request's path, from every service, for a client at `address`. */
|
|
234
|
+
async function pathsFor(client: () => SupatypeClient): Promise<string[]> {
|
|
235
|
+
const seen = captureRequests()
|
|
236
|
+
// Each answer is an empty list, which some reject after the request is sent: only the address counts.
|
|
237
|
+
for (const [, request] of SERVICE_REQUESTS) await Promise.resolve(request(client())).catch(() => undefined)
|
|
238
|
+
return seen.map((r) => r.url.slice(r.url.indexOf("/", "https://".length)))
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
it.each(["https://api.example.com/", "https://api.example.com//"])("is used without it when given: %s", async (url) => {
|
|
242
|
+
const paths = await pathsFor(() => createClient({ url, anonKey: "k" }))
|
|
243
|
+
expect(paths).toHaveLength(SERVICE_REQUESTS.length)
|
|
244
|
+
expect(paths.filter((path) => path.includes("//"))).toEqual([])
|
|
245
|
+
expect(createClient({ url, anonKey: "k" }).url).toBe("https://api.example.com")
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
it("is used without it when the page sets it", async () => {
|
|
249
|
+
vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com/", anonKey: "k" })
|
|
250
|
+
const paths = await pathsFor(() => createClient({}))
|
|
251
|
+
expect(paths.filter((path) => path.includes("//"))).toEqual([])
|
|
252
|
+
expect(createClient({}).url).toBe("https://api.example.com")
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
it("keeps a base path the address has", async () => {
|
|
256
|
+
const paths = await pathsFor(() => createClient({ url: "https://example.com/api/", anonKey: "k" }))
|
|
257
|
+
expect(paths[0]).toMatch(/^\/api\/rest\/v1\/posts/)
|
|
258
|
+
})
|
|
259
|
+
})
|
|
@@ -71,7 +71,7 @@ describe("storage bodies", () => {
|
|
|
71
71
|
it("reports a refusal whose body is null with the fallback message", async () => {
|
|
72
72
|
vi.stubGlobal("fetch", fetchReturning(null, 500))
|
|
73
73
|
const { error } = await storage().from("avatars").upload("a.png", new Blob(["x"]))
|
|
74
|
-
expect(error).toEqual({ message: "Upload failed", status: 500 })
|
|
74
|
+
expect({ ...error }).toEqual({ message: "Upload failed", status: 500 })
|
|
75
75
|
})
|
|
76
76
|
})
|
|
77
77
|
|
|
@@ -170,13 +170,13 @@ describe("a functions worker refusal", () => {
|
|
|
170
170
|
it("reads a handler's lone `error` string as the message, not the code", async () => {
|
|
171
171
|
vi.stubGlobal("fetch", fetchReturning({ error: "Email already taken" }, 400))
|
|
172
172
|
const { error } = await client().functions.invoke("fn")
|
|
173
|
-
expect(error).toEqual({ message: "Email already taken", status: 400 })
|
|
173
|
+
expect({ ...error }).toEqual({ message: "Email already taken", status: 400 })
|
|
174
174
|
})
|
|
175
175
|
|
|
176
176
|
it("reads the message the way every other refusal is read, `msg` and an empty `message` included", async () => {
|
|
177
177
|
vi.stubGlobal("fetch", fetchReturning({ message: "", msg: "Rate limited" }, 429))
|
|
178
178
|
const { error } = await client().functions.invoke("fn")
|
|
179
|
-
expect(error).toEqual({ message: "Rate limited", status: 429 })
|
|
179
|
+
expect({ ...error }).toEqual({ message: "Rate limited", status: 429 })
|
|
180
180
|
})
|
|
181
181
|
|
|
182
182
|
it("leaves the code unset when `error` is not a string", async () => {
|
|
@@ -102,6 +102,54 @@ describe("the subscribe frame", () => {
|
|
|
102
102
|
// always carries a schema, that default overrode the "app" the server would have read.
|
|
103
103
|
expect(subscribeFrames()[0]!["schema"]).toBe("app")
|
|
104
104
|
})
|
|
105
|
+
|
|
106
|
+
it("joins public when a table is named and the channel name has a colon", async () => {
|
|
107
|
+
// 0.9.1 release test (RB4): the documented `.channel("post:42")` with `table: "comment"`
|
|
108
|
+
// took "post" from the channel name as the schema, joined `post.comment`, reported SUBSCRIBED
|
|
109
|
+
// and delivered nothing. The name is read as `schema:table` only when no table is given.
|
|
110
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
111
|
+
client
|
|
112
|
+
.channel("post:42")
|
|
113
|
+
.on("postgres_changes", { event: "INSERT", table: "comment", filter: "post_id=eq.42" }, () => {})
|
|
114
|
+
.subscribe()
|
|
115
|
+
await settle()
|
|
116
|
+
|
|
117
|
+
expect(subscribeFrames()[0]).toMatchObject({ channel: "post:42", schema: "public", table: "comment" })
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it("keeps a schema the listener states, whatever the channel is called", async () => {
|
|
121
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
122
|
+
client
|
|
123
|
+
.channel("post:42")
|
|
124
|
+
.on("postgres_changes", { event: "*", schema: "app", table: "comment" }, () => {})
|
|
125
|
+
.subscribe()
|
|
126
|
+
await settle()
|
|
127
|
+
|
|
128
|
+
expect(subscribeFrames()[0]).toMatchObject({ schema: "app", table: "comment" })
|
|
129
|
+
})
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 0.9.2 release test round 2 (R2-RB2): the server checks a join's table, and the frame names one on
|
|
134
|
+
* every join, the channel name's reading when no listener gives one. `room:probe` read as
|
|
135
|
+
* room.probe, so broadcast and presence on it were refused. The frame now says which joins want rows.
|
|
136
|
+
*/
|
|
137
|
+
describe("whether the join asks for row changes", () => {
|
|
138
|
+
it("says so when a listener wants row changes", async () => {
|
|
139
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
140
|
+
client.channel("lobby-chat").on("postgres_changes", { event: "*", table: "chat_message" }, () => {}).subscribe()
|
|
141
|
+
await settle()
|
|
142
|
+
expect(subscribeFrames()[0]).toMatchObject({ table: "chat_message", changes: true })
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("does not, for a channel used only for broadcast and presence", async () => {
|
|
146
|
+
const client = new RealtimeClient("http://localhost:9999", { apikey: "anon" })
|
|
147
|
+
client.channel("room:probe").onBroadcast("ping", () => {}).onPresence(() => {}).subscribe()
|
|
148
|
+
await settle()
|
|
149
|
+
const frame = subscribeFrames()[0]
|
|
150
|
+
expect(frame).toBeDefined()
|
|
151
|
+
expect(frame).toMatchObject({ changes: false })
|
|
152
|
+
})
|
|
105
153
|
})
|
|
106
154
|
|
|
107
155
|
describe("joining again after disconnect()", () => {
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { vi, type Mock } from "vitest"
|
|
2
|
+
|
|
3
|
+
/** What a stubbed browser records: navigations, address-bar rewrites, and its localStorage. */
|
|
4
|
+
export interface StubbedBrowser {
|
|
5
|
+
assign: Mock<(url: string) => void>
|
|
6
|
+
replaceState: Mock<(state: unknown, unused: string, url: string) => void>
|
|
7
|
+
store: Map<string, string>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A browser at `href`, with a localStorage holding `stored`. Not named `*.test.ts`, so vitest's
|
|
12
|
+
* default include does not collect it as a suite.
|
|
13
|
+
*/
|
|
14
|
+
export function stubBrowser(href: string, stored: Record<string, string> = {}): StubbedBrowser {
|
|
15
|
+
const store = new Map(Object.entries(stored))
|
|
16
|
+
const assign = vi.fn<(url: string) => void>()
|
|
17
|
+
const replaceState = vi.fn<(state: unknown, unused: string, url: string) => void>()
|
|
18
|
+
vi.stubGlobal("window", {
|
|
19
|
+
location: { href, protocol: "https:", assign },
|
|
20
|
+
history: { state: null, replaceState },
|
|
21
|
+
localStorage: {
|
|
22
|
+
getItem: (k: string) => store.get(k) ?? null,
|
|
23
|
+
setItem: (k: string, v: string) => { store.set(k, v) },
|
|
24
|
+
removeItem: (k: string) => { store.delete(k) },
|
|
25
|
+
},
|
|
26
|
+
})
|
|
27
|
+
return { assign, replaceState, store }
|
|
28
|
+
}
|
package/tests/support/jwt.ts
CHANGED
|
@@ -2,3 +2,8 @@
|
|
|
2
2
|
export function fakeJwt(payload: Record<string, unknown>): string {
|
|
3
3
|
return `${btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${btoa(JSON.stringify(payload))}.sig`
|
|
4
4
|
}
|
|
5
|
+
|
|
6
|
+
/** A fake access token that expires in an hour. */
|
|
7
|
+
export function liveAccessToken(): string {
|
|
8
|
+
return fakeJwt({ exp: Math.floor(Date.now() / 1000) + 3600 })
|
|
9
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `reportThrown`: what a binding holds as `error` for a request that threw, and the one console
|
|
3
|
+
* line that says so.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
7
|
+
import { reportThrown } from "../src/thrown-error.js"
|
|
8
|
+
import { MissingClientValuesError, NetworkError, RateLimitError, SupatypeError } from "../src/errors.js"
|
|
9
|
+
|
|
10
|
+
afterEach(() => {
|
|
11
|
+
vi.restoreAllMocks()
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
function quietly(thrown: unknown): ReturnType<typeof reportThrown> {
|
|
15
|
+
vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
16
|
+
return reportThrown("useQuery(\"posts\")", thrown)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
describe("reportThrown", () => {
|
|
20
|
+
it("names the hook and carries the thrown value on one console line", () => {
|
|
21
|
+
const logged = vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
22
|
+
const thrown = new Error("no address")
|
|
23
|
+
reportThrown("useQuery(\"posts\")", thrown)
|
|
24
|
+
expect(logged).toHaveBeenCalledTimes(1)
|
|
25
|
+
expect(logged).toHaveBeenCalledWith("[supatype] useQuery(\"posts\"): the request threw.", thrown)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it("keeps one of the SDK's own errors as it is, so instanceof still names it", () => {
|
|
29
|
+
const thrown = new MissingClientValuesError("no address", ["url"])
|
|
30
|
+
expect(quietly(thrown)).toBe(thrown)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it("holds any other Error as the cause of a SupatypeError with its message", () => {
|
|
34
|
+
const thrown = new Error("no address")
|
|
35
|
+
const held = quietly(thrown)
|
|
36
|
+
expect(held).toBeInstanceOf(SupatypeError)
|
|
37
|
+
expect((held as Error).cause).toBe(thrown)
|
|
38
|
+
expect({ ...(held as object) }).toEqual({ message: "no address" })
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it("gives the SDK's own errors the JSON a failed request answers with", () => {
|
|
42
|
+
expect(JSON.parse(JSON.stringify(quietly(new RateLimitError(3))))).toEqual({
|
|
43
|
+
message: "Rate limited. Retry after 3 seconds.",
|
|
44
|
+
code: "RATE_LIMITED",
|
|
45
|
+
status: 429,
|
|
46
|
+
})
|
|
47
|
+
expect({ ...quietly(new NetworkError("offline")) }).toEqual({ message: "offline", code: "NETWORK_ERROR" })
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it("wraps an Error whose fields do not fit, keeping its message", () => {
|
|
51
|
+
const thrown = Object.assign(new Error("socket hang up"), { code: 104 })
|
|
52
|
+
expect({ ...quietly(thrown) }).toEqual({ message: "socket hang up" })
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it("wraps a thrown string or anything else", () => {
|
|
56
|
+
expect({ ...quietly("bad thing") }).toEqual({ message: "bad thing" })
|
|
57
|
+
expect({ ...quietly({ nope: true }) }).toEqual({ message: "Unknown error" })
|
|
58
|
+
})
|
|
59
|
+
})
|