@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.
Files changed (128) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +76 -68
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +82 -0
  5. package/dist/auth.d.ts +50 -6
  6. package/dist/auth.d.ts.map +1 -1
  7. package/dist/auth.js +117 -32
  8. package/dist/auth.js.map +1 -1
  9. package/dist/bindings.d.ts +3 -0
  10. package/dist/bindings.d.ts.map +1 -1
  11. package/dist/bindings.js +2 -0
  12. package/dist/bindings.js.map +1 -1
  13. package/dist/error-codes-doc.d.ts +1 -1
  14. package/dist/error-codes-doc.d.ts.map +1 -1
  15. package/dist/error-codes-doc.js +7 -0
  16. package/dist/error-codes-doc.js.map +1 -1
  17. package/dist/errors.d.ts +81 -21
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/errors.js +133 -46
  20. package/dist/errors.js.map +1 -1
  21. package/dist/graphql-transport.d.ts +8 -1
  22. package/dist/graphql-transport.d.ts.map +1 -1
  23. package/dist/graphql-transport.js +5 -5
  24. package/dist/graphql-transport.js.map +1 -1
  25. package/dist/index.d.ts +10 -6
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +52 -37
  28. package/dist/index.js.map +1 -1
  29. package/dist/latest-rows.d.ts +44 -0
  30. package/dist/latest-rows.d.ts.map +1 -0
  31. package/dist/latest-rows.js +58 -0
  32. package/dist/latest-rows.js.map +1 -0
  33. package/dist/mutation-request.d.ts +2 -1
  34. package/dist/mutation-request.d.ts.map +1 -1
  35. package/dist/mutation-request.js +2 -1
  36. package/dist/mutation-request.js.map +1 -1
  37. package/dist/page-env-script.d.ts +12 -0
  38. package/dist/page-env-script.d.ts.map +1 -0
  39. package/dist/page-env-script.js +30 -0
  40. package/dist/page-env-script.js.map +1 -0
  41. package/dist/preview.d.ts +2 -1
  42. package/dist/preview.d.ts.map +1 -1
  43. package/dist/preview.js +7 -3
  44. package/dist/preview.js.map +1 -1
  45. package/dist/query.d.ts +18 -5
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +33 -16
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime.d.ts +22 -8
  50. package/dist/realtime.d.ts.map +1 -1
  51. package/dist/realtime.js +121 -41
  52. package/dist/realtime.js.map +1 -1
  53. package/dist/runtime-env.d.ts +59 -0
  54. package/dist/runtime-env.d.ts.map +1 -0
  55. package/dist/runtime-env.js +202 -0
  56. package/dist/runtime-env.js.map +1 -0
  57. package/dist/setup-fault.d.ts +13 -0
  58. package/dist/setup-fault.d.ts.map +1 -0
  59. package/dist/setup-fault.js +17 -0
  60. package/dist/setup-fault.js.map +1 -0
  61. package/dist/storage.d.ts +10 -5
  62. package/dist/storage.d.ts.map +1 -1
  63. package/dist/storage.js +22 -13
  64. package/dist/storage.js.map +1 -1
  65. package/dist/table-subscription.d.ts +5 -3
  66. package/dist/table-subscription.d.ts.map +1 -1
  67. package/dist/table-subscription.js +8 -5
  68. package/dist/table-subscription.js.map +1 -1
  69. package/dist/thrown-error.d.ts +16 -0
  70. package/dist/thrown-error.d.ts.map +1 -0
  71. package/dist/thrown-error.js +31 -0
  72. package/dist/thrown-error.js.map +1 -0
  73. package/dist/types.d.ts +64 -15
  74. package/dist/types.d.ts.map +1 -1
  75. package/dist/types.js.map +1 -1
  76. package/package.json +2 -1
  77. package/src/auth.ts +121 -36
  78. package/src/bindings.ts +3 -0
  79. package/src/error-codes-doc.ts +9 -1
  80. package/src/errors.ts +155 -57
  81. package/src/graphql-transport.ts +5 -6
  82. package/src/index.ts +63 -45
  83. package/src/latest-rows.ts +95 -0
  84. package/src/mutation-request.ts +3 -2
  85. package/src/page-env-script.ts +27 -0
  86. package/src/preview.ts +8 -4
  87. package/src/query.ts +38 -19
  88. package/src/realtime.ts +146 -44
  89. package/src/runtime-env.ts +262 -0
  90. package/src/setup-fault.ts +18 -0
  91. package/src/storage.ts +26 -16
  92. package/src/table-subscription.ts +8 -6
  93. package/src/thrown-error.ts +31 -0
  94. package/src/types.ts +70 -14
  95. package/tests/auth-errors.test.ts +3 -3
  96. package/tests/auth-events.test.ts +3 -7
  97. package/tests/auth-sso.test.ts +291 -0
  98. package/tests/auth-url-session.test.ts +6 -25
  99. package/tests/entry-points.test.ts +9 -0
  100. package/tests/error-family.test.ts +79 -0
  101. package/tests/examples-runtime-env.test.ts +135 -0
  102. package/tests/helpers/auth-unmount-binding.ts +63 -0
  103. package/tests/helpers/mock-websocket.ts +22 -0
  104. package/tests/helpers/oauth-binding.ts +4 -3
  105. package/tests/helpers/reactive-options-binding.ts +99 -0
  106. package/tests/helpers/stale-read-binding.ts +113 -0
  107. package/tests/helpers/thrown-error-binding.ts +127 -0
  108. package/tests/postgrest-error-codes.test.ts +4 -4
  109. package/tests/query.test.ts +39 -2
  110. package/tests/rate-limit-integration.test.ts +1 -1
  111. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  112. package/tests/realtime-refusal-error.test.ts +79 -0
  113. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  114. package/tests/realtime-session-auth.test.ts +0 -1
  115. package/tests/realtime-shared-channel.test.ts +9 -27
  116. package/tests/result-error-class.test.ts +107 -0
  117. package/tests/retry-policy.test.ts +1 -1
  118. package/tests/runtime-env-bundle.test.ts +121 -0
  119. package/tests/runtime-env-expo.test.ts +58 -0
  120. package/tests/runtime-env-page-script.test.ts +174 -0
  121. package/tests/runtime-env.test.ts +259 -0
  122. package/tests/server-bodies.test.ts +3 -3
  123. package/tests/subscribe-frame.test.ts +48 -0
  124. package/tests/support/browser.ts +28 -0
  125. package/tests/support/jwt.ts +5 -0
  126. package/tests/thrown-error.test.ts +59 -0
  127. package/tsconfig.json +2 -1
  128. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The `error` of a `{ data, error }` result is an `Error`, whatever produced it.
3
+ *
4
+ * It used to be a plain object typed `SupatypeError`, so `error instanceof Error` was false and
5
+ * `String(error)` printed "[object Object]": a page that rendered a failed request's error showed
6
+ * exactly that for a network failure or a CORS refusal. It is now a `SupatypeError`, with the
7
+ * same `message`, `code` and `status` as before, and the same keys when it is turned into JSON.
8
+ */
9
+
10
+ import { afterEach, assert, describe, expect, it, vi } from "vitest"
11
+ import { createClient, SupatypeError, type SupatypeClient } from "../src/index.js"
12
+ import { NetworkError } from "../src/errors.js"
13
+ import { reportThrown } from "../src/thrown-error.js"
14
+
15
+ afterEach(() => {
16
+ vi.unstubAllGlobals()
17
+ vi.restoreAllMocks()
18
+ })
19
+
20
+ type Request = (client: SupatypeClient) => PromiseLike<{ error: unknown }>
21
+
22
+ const client = (): SupatypeClient => createClient({ url: "http://127.0.0.1:9", anonKey: "x", retry: false })
23
+
24
+ /** Every request fails in transit, as fetch does when nothing listens on the port. */
25
+ function unreachable(): void {
26
+ vi.stubGlobal("fetch", () => Promise.reject(new TypeError("fetch failed")))
27
+ }
28
+
29
+ /** Every request is answered with `status` and the JSON `body`. */
30
+ function answering(status: number, body: Record<string, unknown>): void {
31
+ vi.stubGlobal("fetch", () =>
32
+ Promise.resolve(new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })),
33
+ )
34
+ }
35
+
36
+ /** The error a result carries is an Error that reads as its message and keeps the old JSON form. */
37
+ function expectResultError(error: unknown, shape: Record<string, unknown>): void {
38
+ assert(error instanceof Error)
39
+ expect(error).toBeInstanceOf(SupatypeError)
40
+ expect(String(error)).toBe(`${error.name}: ${String(shape["message"])}`)
41
+ expect(JSON.parse(JSON.stringify(error))).toEqual(shape)
42
+ expect({ ...error }).toEqual(shape)
43
+ }
44
+
45
+ const NETWORK_FAILURES: ReadonlyArray<readonly [string, Request]> = [
46
+ ["a table read", (c) => c.from("posts").select("id")],
47
+ ["an rpc call", (c) => c.rpc("hello")],
48
+ ["a bucket list", (c) => c.storage.listBuckets()],
49
+ ["a GraphQL query", (c) => c.graphql("{ __typename }")],
50
+ ["a function call", (c) => c.functions.invoke("hello")],
51
+ ]
52
+
53
+ describe("a request that never got an answer", () => {
54
+ it.each(NETWORK_FAILURES)("answers %s with an Error carrying the same fields", async (_label, request) => {
55
+ unreachable()
56
+ const { error } = await request(client())
57
+ expectResultError(error, { message: "fetch failed", code: "NETWORK_ERROR" })
58
+ })
59
+
60
+ it("is the NetworkError the transport threw, so its class names the failure", async () => {
61
+ unreachable()
62
+ const { error } = await client().from("posts").select("id")
63
+ expect(error).toBeInstanceOf(NetworkError)
64
+ expect(String(error)).toBe("NetworkError: fetch failed")
65
+ })
66
+
67
+ })
68
+
69
+ describe("a request the server refused", () => {
70
+ it("answers a refused table read with an Error carrying the code and status", async () => {
71
+ answering(403, { code: "42501", message: "permission denied for table posts" })
72
+ const { error } = await client().from("posts").select("id")
73
+ expectResultError(error, { message: "permission denied for table posts", code: "42501", status: 403 })
74
+ })
75
+
76
+ it("answers a refused storage list with an Error carrying the status", async () => {
77
+ answering(403, { message: "not allowed" })
78
+ const { error } = await client().storage.from("avatars").list()
79
+ expectResultError(error, { message: "not allowed", status: 403 })
80
+ })
81
+
82
+ it("answers a refused sign-in with an Error carrying the auth code", async () => {
83
+ answering(400, { error_code: "invalid_credentials", msg: "Invalid login credentials" })
84
+ const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
85
+ expectResultError(error, { message: "Invalid login credentials", code: "invalid_credentials", status: 400 })
86
+ })
87
+
88
+ it("answers a call needing a session with an Error when there is none", async () => {
89
+ const { error } = await client().auth.updateUser({ data: {} })
90
+ expectResultError(error, { message: "Not authenticated" })
91
+ })
92
+ })
93
+
94
+ describe("a binding's thrown request", () => {
95
+ it("holds a thrown string as an Error", () => {
96
+ vi.spyOn(console, "error").mockImplementation(() => undefined)
97
+ expectResultError(reportThrown("useQuery(\"posts\")", "bad thing"), { message: "bad thing" })
98
+ })
99
+
100
+ it("holds the SDK's own errors as an Error with the result's fields", () => {
101
+ vi.spyOn(console, "error").mockImplementation(() => undefined)
102
+ expectResultError(reportThrown("useQuery(\"posts\")", new NetworkError("offline")), {
103
+ message: "offline",
104
+ code: "NETWORK_ERROR",
105
+ })
106
+ })
107
+ })
@@ -133,7 +133,7 @@ describe("auth and storage use the client's transport", () => {
133
133
  fetchReturning({ code: 429, error_code: "over_request_rate_limit", msg: "Request rate limit reached" }, 429),
134
134
  )
135
135
  const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
136
- expect(error).toEqual({ message: "Request rate limit reached", status: 429, code: "over_request_rate_limit" })
136
+ expect({ ...error }).toEqual({ message: "Request rate limit reached", status: 429, code: "over_request_rate_limit" })
137
137
  })
138
138
 
139
139
  it("a storage upload that never answers ends at the timeout", { timeout: 2000 }, async () => {
@@ -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,58 @@
1
+ /**
2
+ * 0.9.2 release test (N-S14): an Expo web export with no values threw `MissingClientValuesError`
3
+ * telling the developer to add the script tag to `index.html`, which an Expo Router app does not
4
+ * have. Its page comes from `app/+html.tsx`, so that is the file the error names. The client tells
5
+ * an Expo page by `globalThis.expo`, which Expo's runtime sets on the web as on a phone; the CLI's
6
+ * `EXPO_PUBLIC_` names are read by the app's own code, which the client never sees.
7
+ */
8
+
9
+ import { afterEach, describe, expect, it, vi } from "vitest"
10
+ import { createClient, MissingClientValuesError } from "../src/index.js"
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllGlobals()
14
+ })
15
+
16
+ /** A page with no `/supatype-env.js` script and no `__SUPATYPE_ENV__`, Expo's when `expo` is set. */
17
+ function page(expo: boolean): void {
18
+ vi.stubGlobal("window", globalThis)
19
+ vi.stubGlobal("document", { scripts: [] })
20
+ if (expo) vi.stubGlobal("expo", { modules: {} })
21
+ vi.stubGlobal("fetch", vi.fn(() => Promise.reject(new Error("no request may be sent"))))
22
+ }
23
+
24
+ async function firstCallMessage(): Promise<string> {
25
+ try {
26
+ await createClient({}).from("posts").select()
27
+ } catch (err) {
28
+ if (err instanceof MissingClientValuesError) return err.message
29
+ throw err
30
+ }
31
+ throw new Error("expected the first call to fail")
32
+ }
33
+
34
+ describe("the missing-values error in an Expo app", () => {
35
+ it("names app/+html.tsx, not index.html", async () => {
36
+ page(true)
37
+ const message = await firstCallMessage()
38
+ expect(message).toContain("app/+html.tsx")
39
+ expect(message).toContain('<script src="/supatype-env.js" />')
40
+ expect(message).not.toContain("index.html")
41
+ expect(message).not.toContain("vite-ignore")
42
+ })
43
+
44
+ it("says a native build takes the values at build time, under Expo's names", async () => {
45
+ page(true)
46
+ const message = await firstCallMessage()
47
+ expect(message).toContain("EXPO_PUBLIC_SUPATYPE_URL")
48
+ expect(message).toContain("A native build has no page")
49
+ expect(message).toContain("supatype build -- <your build command>")
50
+ })
51
+
52
+ it("still names index.html in a page that is not Expo's", async () => {
53
+ page(false)
54
+ const message = await firstCallMessage()
55
+ expect(message).toContain('add <script src="/supatype-env.js" vite-ignore></script> to index.html')
56
+ expect(message).not.toContain("+html.tsx")
57
+ })
58
+ })
@@ -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
+ })