@supatype/client 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +73 -69
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +110 -0
  5. package/bin/supatype-prepare.js +68 -0
  6. package/dist/auth.d.ts +50 -6
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +132 -40
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +4 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +2 -0
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/error-codes-doc.d.ts +1 -1
  15. package/dist/error-codes-doc.d.ts.map +1 -1
  16. package/dist/error-codes-doc.js +7 -0
  17. package/dist/error-codes-doc.js.map +1 -1
  18. package/dist/errors.d.ts +81 -21
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +133 -46
  21. package/dist/errors.js.map +1 -1
  22. package/dist/graphql-transport.d.ts +10 -3
  23. package/dist/graphql-transport.d.ts.map +1 -1
  24. package/dist/graphql-transport.js +5 -5
  25. package/dist/graphql-transport.js.map +1 -1
  26. package/dist/index.d.ts +23 -16
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +66 -48
  29. package/dist/index.js.map +1 -1
  30. package/dist/latest-rows.d.ts +29 -0
  31. package/dist/latest-rows.d.ts.map +1 -0
  32. package/dist/latest-rows.js +51 -0
  33. package/dist/latest-rows.js.map +1 -0
  34. package/dist/mutation-request.d.ts +19 -5
  35. package/dist/mutation-request.d.ts.map +1 -1
  36. package/dist/mutation-request.js +18 -15
  37. package/dist/mutation-request.js.map +1 -1
  38. package/dist/page-env-script.d.ts +12 -0
  39. package/dist/page-env-script.d.ts.map +1 -0
  40. package/dist/page-env-script.js +30 -0
  41. package/dist/page-env-script.js.map +1 -0
  42. package/dist/preview.d.ts +2 -1
  43. package/dist/preview.d.ts.map +1 -1
  44. package/dist/preview.js +7 -3
  45. package/dist/preview.js.map +1 -1
  46. package/dist/query.d.ts +49 -19
  47. package/dist/query.d.ts.map +1 -1
  48. package/dist/query.js +102 -33
  49. package/dist/query.js.map +1 -1
  50. package/dist/realtime.d.ts +5 -2
  51. package/dist/realtime.d.ts.map +1 -1
  52. package/dist/realtime.js +13 -6
  53. package/dist/realtime.js.map +1 -1
  54. package/dist/runtime-env.d.ts +59 -0
  55. package/dist/runtime-env.d.ts.map +1 -0
  56. package/dist/runtime-env.js +167 -0
  57. package/dist/runtime-env.js.map +1 -0
  58. package/dist/setup-fault.d.ts +13 -0
  59. package/dist/setup-fault.d.ts.map +1 -0
  60. package/dist/setup-fault.js +17 -0
  61. package/dist/setup-fault.js.map +1 -0
  62. package/dist/storage.d.ts +10 -5
  63. package/dist/storage.d.ts.map +1 -1
  64. package/dist/storage.js +22 -13
  65. package/dist/storage.js.map +1 -1
  66. package/dist/table-subscription.d.ts +1 -1
  67. package/dist/table-subscription.d.ts.map +1 -1
  68. package/dist/table-subscription.js +3 -2
  69. package/dist/table-subscription.js.map +1 -1
  70. package/dist/thrown-error.d.ts +16 -0
  71. package/dist/thrown-error.d.ts.map +1 -0
  72. package/dist/thrown-error.js +31 -0
  73. package/dist/thrown-error.js.map +1 -0
  74. package/dist/types.d.ts +59 -15
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js.map +1 -1
  77. package/package.json +6 -2
  78. package/src/auth.ts +135 -44
  79. package/src/bindings.ts +4 -1
  80. package/src/error-codes-doc.ts +9 -1
  81. package/src/errors.ts +155 -57
  82. package/src/graphql-transport.ts +7 -8
  83. package/src/index.ts +82 -60
  84. package/src/latest-rows.ts +78 -0
  85. package/src/mutation-request.ts +34 -19
  86. package/src/page-env-script.ts +27 -0
  87. package/src/preview.ts +8 -4
  88. package/src/query.ts +128 -52
  89. package/src/realtime.ts +15 -6
  90. package/src/runtime-env.ts +220 -0
  91. package/src/setup-fault.ts +18 -0
  92. package/src/storage.ts +26 -16
  93. package/src/table-subscription.ts +3 -3
  94. package/src/thrown-error.ts +31 -0
  95. package/src/types.ts +65 -14
  96. package/tests/auth-errors.test.ts +3 -3
  97. package/tests/auth-events.test.ts +3 -7
  98. package/tests/auth-sso.test.ts +260 -0
  99. package/tests/auth-url-session.test.ts +6 -25
  100. package/tests/data-plane-auth.test.ts +1 -6
  101. package/tests/draft-insert.test.ts +9 -9
  102. package/tests/draft-update.test.ts +5 -5
  103. package/tests/entry-points.test.ts +9 -0
  104. package/tests/error-family.test.ts +79 -0
  105. package/tests/helpers/auth-unmount-binding.ts +63 -0
  106. package/tests/helpers/oauth-binding.ts +4 -3
  107. package/tests/helpers/stale-read-binding.ts +113 -0
  108. package/tests/helpers/thrown-error-binding.ts +127 -0
  109. package/tests/minimal-writes.test.ts +118 -0
  110. package/tests/postgrest-error-codes.test.ts +5 -5
  111. package/tests/query.test.ts +3 -3
  112. package/tests/rate-limit-integration.test.ts +1 -1
  113. package/tests/realtime-session-auth.test.ts +1 -4
  114. package/tests/result-error-class.test.ts +107 -0
  115. package/tests/retry-policy.test.ts +1 -1
  116. package/tests/rpc-resend.test.ts +33 -8
  117. package/tests/runtime-env-bundle.test.ts +121 -0
  118. package/tests/runtime-env-page-script.test.ts +174 -0
  119. package/tests/runtime-env.test.ts +224 -0
  120. package/tests/server-bodies.test.ts +3 -3
  121. package/tests/supatype-prepare.test.ts +139 -0
  122. package/tests/support/browser.ts +28 -0
  123. package/tests/support/jwt.ts +9 -0
  124. package/tests/thrown-error.test.ts +59 -0
  125. package/tests/unauthorized-resend.test.ts +107 -0
  126. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,121 @@
1
+ /**
2
+ * A production bundle built with no address or anon key still says why it cannot start.
3
+ *
4
+ * The formflow report: `vite build` with neither value replaced both with `undefined`, folded the
5
+ * app's own `if (!key) throw` into an unconditional throw, and dropped everything after it, so the
6
+ * page was blank and the cause was gone from the bundle. The check that replaces it lives in the
7
+ * client and runs on the first request, reading the page at that moment, which no bundler can fold
8
+ * away. Built here with Vite, the bundler that report used, minified, and then run.
9
+ */
10
+
11
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"
12
+ import { tmpdir } from "node:os"
13
+ import { dirname, join, resolve } from "node:path"
14
+ import { fileURLToPath, pathToFileURL } from "node:url"
15
+ import { build, type Rollup } from "vite"
16
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"
17
+
18
+ const CLIENT_ENTRY = resolve(dirname(fileURLToPath(import.meta.url)), "../src/index.ts")
19
+
20
+ /** What an app's own setup file says, with nothing defined for either name. */
21
+ const APP_SOURCE = [
22
+ `import { createClient } from ${JSON.stringify(CLIENT_ENTRY.replace(/\\/g, "/"))}`,
23
+ "export const supatype = createClient({",
24
+ " url: import.meta.env.VITE_SUPATYPE_URL,",
25
+ " anonKey: import.meta.env.VITE_SUPATYPE_ANON_KEY,",
26
+ "})",
27
+ "globalThis.started = true",
28
+ "globalThis.firstRequest = () => supatype.from(\"posts\").select()",
29
+ ].join("\n")
30
+
31
+ let workDir = ""
32
+ let bundle = ""
33
+
34
+ /** The one chunk a single-entry build writes. */
35
+ function onlyChunk(output: Rollup.RollupOutput | Rollup.RollupOutput[] | Rollup.RollupWatcher): string {
36
+ const outputs = Array.isArray(output) ? output : [output]
37
+ const chunk = outputs.flatMap((o) => ("output" in o ? o.output : [])).find((item) => item.type === "chunk")
38
+ if (chunk === undefined) throw new Error("vite build wrote no chunk")
39
+ return chunk.code
40
+ }
41
+
42
+ beforeAll(async () => {
43
+ workDir = mkdtempSync(join(tmpdir(), "supatype-client-bundle-"))
44
+ const entry = join(workDir, "main.js")
45
+ writeFileSync(entry, APP_SOURCE, "utf8")
46
+ const output = await build({
47
+ root: workDir,
48
+ configFile: false,
49
+ logLevel: "silent",
50
+ mode: "production",
51
+ build: { write: false, minify: true, rollupOptions: { input: entry } },
52
+ })
53
+ bundle = onlyChunk(output)
54
+ }, 60_000)
55
+
56
+ let runs = 0
57
+
58
+ /**
59
+ * The bundle, imported as the page would load it. Each run is a file of its own, since a module
60
+ * is evaluated once per URL and each run needs its createClient call made again.
61
+ */
62
+ async function runBundle(): Promise<void> {
63
+ vi.stubGlobal("started", undefined)
64
+ vi.stubGlobal("firstRequest", undefined)
65
+ runs += 1
66
+ const file = join(workDir, `bundle-${runs}.mjs`)
67
+ writeFileSync(file, bundle, "utf8")
68
+ await import(pathToFileURL(file).href)
69
+ }
70
+
71
+ /** Every address the bundle sends to, answered with an empty list. */
72
+ function stubFetch(): string[] {
73
+ const sent: string[] = []
74
+ vi.stubGlobal("fetch", async (url: string) => {
75
+ sent.push(url)
76
+ return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
77
+ })
78
+ return sent
79
+ }
80
+
81
+ /** The request the bundle's app set up, made now. */
82
+ function firstRequest(): Promise<unknown> {
83
+ const run: unknown = Reflect.get(globalThis, "firstRequest")
84
+ if (typeof run !== "function") throw new Error("the bundle set up no request")
85
+ const request: unknown = Reflect.apply(run, undefined, [])
86
+ return Promise.resolve(request)
87
+ }
88
+
89
+ afterEach(() => {
90
+ vi.unstubAllGlobals()
91
+ })
92
+
93
+ afterAll(() => {
94
+ if (workDir !== "") rmSync(workDir, { recursive: true, force: true })
95
+ })
96
+
97
+ describe("a production bundle with no address or anon key", () => {
98
+ it("keeps the error that names the fix", () => {
99
+ // The frontend names are put together from prefix and name, so the bundle holds the parts.
100
+ expect(bundle).toContain("SUPATYPE_ANON_KEY")
101
+ expect(bundle).toContain("NEXT_PUBLIC_")
102
+ expect(bundle).toContain("supatype build")
103
+ expect(bundle).toContain("/supatype-env.js")
104
+ })
105
+
106
+ it("starts, and throws that error on its first request rather than sending one with no key", async () => {
107
+ const sent = stubFetch()
108
+ await runBundle()
109
+ expect(Reflect.get(globalThis, "started")).toBe(true)
110
+ await expect(firstRequest()).rejects.toThrow(/VITE_SUPATYPE_ANON_KEY/)
111
+ expect(sent).toEqual([])
112
+ })
113
+
114
+ it("sends with the values the page sets, the same build on any deployment", async () => {
115
+ const sent = stubFetch()
116
+ await runBundle()
117
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: "https://api.example.com", anonKey: "deployed-anon-key" })
118
+ await firstRequest()
119
+ expect(sent[0]?.startsWith("https://api.example.com/rest/v1/posts")).toBe(true)
120
+ })
121
+ })
@@ -0,0 +1,174 @@
1
+ /**
2
+ * A page whose `/supatype-env.js` gave it no values: the very first call says why, and sends nothing.
3
+ *
4
+ * A browser runs no script answered with an error status and shows the page nothing of why. So a
5
+ * misconfigured server answers the script 200, setting `window.__SUPATYPE_ENV__ = {"error": "..."}`
6
+ * to the reason its `.json` sibling gives as a 503, and the client quotes it. A page that has the
7
+ * script element but no global at all did not run the script, and is told to open it. A page with no
8
+ * element is told to add one.
9
+ */
10
+
11
+ import { afterEach, describe, expect, it, vi } from "vitest"
12
+ import { createClient, MissingClientValuesError, type SupatypeClient } from "../src/index.js"
13
+
14
+ const REASON =
15
+ "public env unavailable: SUPATYPE_ANON_KEY is not set on this server\n" +
16
+ "public env unavailable: set SUPATYPE_URL or SUPATYPE_API_EXTERNAL_URL to this deployment's public API address"
17
+ const SCRIPT = "http://localhost:3000/supatype-env.js"
18
+ const ADD_THE_TAG = 'add <script src="/supatype-env.js"'
19
+
20
+ afterEach(() => {
21
+ vi.unstubAllGlobals()
22
+ })
23
+
24
+ /** Run as a page whose scripts have `srcs`, with `env` as its `__SUPATYPE_ENV__` when given. */
25
+ function page(srcs: readonly string[], env?: unknown): void {
26
+ vi.stubGlobal("window", globalThis)
27
+ vi.stubGlobal("document", { scripts: srcs.map((src) => ({ src })) })
28
+ if (env !== undefined) vi.stubGlobal("__SUPATYPE_ENV__", env)
29
+ }
30
+
31
+ /** A fetch that records every call and answers none, so a test can show nothing was sent. */
32
+ function recordFetch(): ReturnType<typeof vi.fn> {
33
+ const fetch = vi.fn(() => Promise.reject(new Error("no request may be sent")))
34
+ vi.stubGlobal("fetch", fetch)
35
+ return fetch
36
+ }
37
+
38
+ /**
39
+ * The setup error `run` fails with, which must come before any timer runs: the reason is in the
40
+ * page already, so nothing is waited for, not a request and not a deadline.
41
+ */
42
+ async function firstCallError(run: () => unknown): Promise<MissingClientValuesError> {
43
+ const late = Symbol("late")
44
+ const timer = new Promise((resolve) => setTimeout(() => resolve(late), 0))
45
+ let outcome: unknown
46
+ try {
47
+ outcome = await Promise.race([Promise.resolve().then(run), timer])
48
+ } catch (err) {
49
+ if (err instanceof MissingClientValuesError) return err
50
+ throw err
51
+ }
52
+ throw new Error(outcome === late ? "the call had not failed before a timer ran" : "expected the call to fail")
53
+ }
54
+
55
+ /** The first call through each service, the ones that once gave the reason only on a second error. */
56
+ const FIRST_CALLS: ReadonlyArray<readonly [string, (client: SupatypeClient) => unknown]> = [
57
+ ["a sign-in", (c) => c.auth.signInWithPassword({ email: "a@example.com", password: "pw" })],
58
+ ["a realtime subscribe", (c) => c.realtime.channel("public:posts").subscribe()],
59
+ ["a table read", (c) => c.from("posts").select()],
60
+ ["a bucket file list", (c) => c.storage.from("avatars").list()],
61
+ ["a table write", (c) => c.from("posts").delete().eq("id", "1")],
62
+ ["a function call", (c) => c.functions.invoke("hello")],
63
+ ]
64
+
65
+ describe("a page whose script set the server's reason", () => {
66
+ it.each(FIRST_CALLS)("quotes it on %s, the first call, and sends nothing", async (_label, call) => {
67
+ page([SCRIPT], { error: REASON })
68
+ const fetch = recordFetch()
69
+
70
+ const err = await firstCallError(() => call(createClient({})))
71
+
72
+ expect(err.message).toContain(`${SCRIPT} set no API address and anon key, giving the server's reason instead:\n${REASON}\n`)
73
+ expect(err.message).not.toContain(ADD_THE_TAG)
74
+ expect(err.missing).toEqual(["url", "anonKey"])
75
+ expect(fetch).not.toHaveBeenCalled()
76
+ })
77
+
78
+ it("says to fix the server that answers the script, then reload, and keeps the build-time fix", async () => {
79
+ page([SCRIPT], { error: REASON })
80
+ recordFetch()
81
+
82
+ const { message } = await firstCallError(() => createClient({}).from("posts").select())
83
+
84
+ expect(message).toContain("Fix that in the environment of the server that answers it")
85
+ expect(message).toContain("app/supatype-env.js/route.ts")
86
+ expect(message).toContain("reload the page")
87
+ expect(message).toContain("VITE_SUPATYPE_ANON_KEY")
88
+ })
89
+
90
+ it("quotes it however the page loaded the script, by the global the script sets", async () => {
91
+ page([], { error: REASON })
92
+ recordFetch()
93
+
94
+ const { message } = await firstCallError(() => createClient({}).from("posts").select())
95
+
96
+ expect(message).toContain(`/supatype-env.js set no API address and anon key, giving the server's reason instead:\n${REASON}`)
97
+ })
98
+
99
+ it("names only the value the client was not given", async () => {
100
+ page([SCRIPT], { error: REASON })
101
+ recordFetch()
102
+
103
+ const err = await firstCallError(() => createClient({ url: "https://built.example.com" }).from("posts").select())
104
+
105
+ expect(err.missing).toEqual(["anonKey"])
106
+ expect(err.message).toContain(`${SCRIPT} set no anon key, giving the server's reason instead`)
107
+ })
108
+
109
+ it("is not what a client given both values sees", async () => {
110
+ page([SCRIPT], { error: REASON })
111
+ const fetch = vi.fn(async () => new Response("[]", { status: 200, headers: { "content-type": "application/json" } }))
112
+ vi.stubGlobal("fetch", fetch)
113
+
114
+ const result = await createClient({ url: "https://built.example.com", anonKey: "built-key" }).from("posts").select()
115
+
116
+ expect(result.error).toBeNull()
117
+ expect(fetch).toHaveBeenCalledOnce()
118
+ })
119
+
120
+ it.each([
121
+ ["a number", 42],
122
+ ["an empty string", " "],
123
+ ])("is not quoted when it is %s", async (_label, error) => {
124
+ page([SCRIPT], { error })
125
+ recordFetch()
126
+
127
+ const { message } = await firstCallError(() => createClient({}).from("posts").select())
128
+
129
+ expect(message).not.toContain("the server's reason")
130
+ expect(message).toContain(`the page loads ${SCRIPT}`)
131
+ })
132
+ })
133
+
134
+ describe("a page that has the script element but no __SUPATYPE_ENV__", () => {
135
+ it("says the script did not run, and to open it in the browser, not to add it", async () => {
136
+ page([SCRIPT])
137
+ const fetch = recordFetch()
138
+
139
+ const { message } = await firstCallError(() => createClient({}).from("posts").select())
140
+
141
+ expect(message).toContain(`the page loads ${SCRIPT}, but it had set no window.__SUPATYPE_ENV__`)
142
+ expect(message).toContain("blocked")
143
+ expect(message).toContain("failed to load")
144
+ expect(message).toContain("too old to serve it")
145
+ expect(message).toContain(`Open ${SCRIPT} in the browser`)
146
+ expect(message).not.toContain(ADD_THE_TAG)
147
+ expect(fetch).not.toHaveBeenCalled()
148
+ })
149
+
150
+ it("finds the element whatever the address before the path", async () => {
151
+ page(["https://cdn.example.com/app.js", "https://app.example.com/base/supatype-env.js?v=2"])
152
+ recordFetch()
153
+
154
+ const { message } = await firstCallError(() => createClient({}).from("posts").select())
155
+
156
+ expect(message).toContain("the page loads https://app.example.com/base/supatype-env.js?v=2")
157
+ })
158
+ })
159
+
160
+ describe("a page with no script element", () => {
161
+ it.each([
162
+ ["no scripts", []],
163
+ ["only other scripts", ["http://localhost:3000/app.js", "", "not a url"]],
164
+ ])("still says to add it, with %s", async (_label, srcs) => {
165
+ page(srcs)
166
+ const fetch = recordFetch()
167
+
168
+ const { message } = await firstCallError(() => createClient({}).from("posts").select())
169
+
170
+ expect(message).toContain(ADD_THE_TAG)
171
+ expect(message).not.toContain("did not run")
172
+ expect(fetch).not.toHaveBeenCalled()
173
+ })
174
+ })
@@ -0,0 +1,224 @@
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
+ })
@@ -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 () => {