@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
@@ -3,6 +3,8 @@ import { AuthClient } from "../src/auth.js"
3
3
  import { createClient } from "../src/index.js"
4
4
  import type { AuthChangeEvent } from "../src/types.js"
5
5
  import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
6
+ import { stubBrowser } from "./support/browser.js"
7
+ import { liveAccessToken } from "./support/jwt.js"
6
8
 
7
9
  /**
8
10
  * The OAuth return: the auth server sends the browser back with the session in the URL, as tokens in
@@ -28,27 +30,6 @@ function jsonResponse(body: unknown, status = 200): Response {
28
30
  return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } })
29
31
  }
30
32
 
31
- function accessToken(): string {
32
- const payload = Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })).toString("base64url")
33
- return `eyJhbGciOiJub25lIn0.${payload}.sig`
34
- }
35
-
36
- /** A browser at `href`, with a localStorage holding `stored`. */
37
- function stubBrowser(href: string, stored: Record<string, string> = {}) {
38
- const store = new Map(Object.entries(stored))
39
- const replaceState = vi.fn<(state: unknown, unused: string, url: string) => void>()
40
- vi.stubGlobal("window", {
41
- location: { href, protocol: "https:" },
42
- history: { state: null, replaceState },
43
- localStorage: {
44
- getItem: (k: string) => store.get(k) ?? null,
45
- setItem: (k: string, v: string) => { store.set(k, v) },
46
- removeItem: (k: string) => { store.delete(k) },
47
- },
48
- })
49
- return { replaceState, store }
50
- }
51
-
52
33
  function recordEvents(client: AuthClient): AuthChangeEvent[] {
53
34
  const events: AuthChangeEvent[] = []
54
35
  client.onAuthStateChange((event) => { events.push(event) })
@@ -62,7 +43,7 @@ afterEach(() => {
62
43
 
63
44
  describe("detectSessionInUrl", () => {
64
45
  it("signs in from implicit-grant tokens in the fragment and cleans the URL", async () => {
65
- const token = accessToken()
46
+ const token = liveAccessToken()
66
47
  const { replaceState } = stubBrowser(
67
48
  `https://app.example/welcome?tab=1#access_token=${token}&refresh_token=rt-1&expires_in=3600&token_type=bearer&provider_token=gh&sb=`,
68
49
  )
@@ -86,7 +67,7 @@ describe("detectSessionInUrl", () => {
86
67
  const { replaceState, store } = stubBrowser("https://app.example/cb?next=%2Fhome&code=auth-code-1", {
87
68
  [VERIFIER_KEY]: "verifier-1",
88
69
  })
89
- const fetch = fetchReturning({ access_token: accessToken(), refresh_token: "rt-2", expires_in: 3600, token_type: "bearer", user: RAW_USER })
70
+ const fetch = fetchReturning({ access_token: liveAccessToken(), refresh_token: "rt-2", expires_in: 3600, token_type: "bearer", user: RAW_USER })
90
71
  vi.stubGlobal("fetch", fetch)
91
72
 
92
73
  const client = new AuthClient(AUTH_URL, HEADERS)
@@ -132,7 +113,7 @@ describe("detectSessionInUrl", () => {
132
113
  })
133
114
 
134
115
  it("does nothing when the app opts out", async () => {
135
- const { replaceState } = stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
116
+ const { replaceState } = stubBrowser(`https://app.example/#access_token=${liveAccessToken()}&refresh_token=rt-1`)
136
117
  const fetch = vi.fn()
137
118
  vi.stubGlobal("fetch", fetch)
138
119
 
@@ -146,7 +127,7 @@ describe("detectSessionInUrl", () => {
146
127
  })
147
128
 
148
129
  it("is on by default through createClient", async () => {
149
- stubBrowser(`https://app.example/#access_token=${accessToken()}&refresh_token=rt-1`)
130
+ stubBrowser(`https://app.example/#access_token=${liveAccessToken()}&refresh_token=rt-1`)
150
131
  vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(RAW_USER)))
151
132
 
152
133
  const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
@@ -21,6 +21,8 @@ const BINDING_EXPORTS = [
21
21
  "isRowsOf",
22
22
  "isCallerValue",
23
23
  "runMutation",
24
+ "reportThrown",
25
+ "latestRowsReader",
24
26
  "livePreviewMessage",
25
27
  "previewMessageOf",
26
28
  "originOf",
@@ -40,3 +42,10 @@ describe("entry points", () => {
40
42
  expect(pkg).toHaveProperty(["exports", "./bindings"], { types: "./dist/bindings.d.ts", import: "./dist/bindings.js" })
41
43
  })
42
44
  })
45
+
46
+ describe("the missing-values error on the main entry", () => {
47
+ it("exports MissingClientValuesError, which an app may catch, and not the internal rethrow helper", () => {
48
+ expect(main).toHaveProperty("MissingClientValuesError")
49
+ expect(main).not.toHaveProperty("rethrowSetupFault")
50
+ })
51
+ })
@@ -0,0 +1,79 @@
1
+ /**
2
+ * One error family. `SupatypeError` is the class of every error a result carries, imported as a
3
+ * value and a type from the main entry. The errors the SDK throws are `SupatypeCodedError`s: the
4
+ * same class with a required `code` and a `helpUrl`, so `instanceof SupatypeError` names them too.
5
+ * A status is `status` everywhere; there is no second name for it.
6
+ */
7
+
8
+ import { describe, expect, it, vi } from "vitest"
9
+ import {
10
+ AuthError,
11
+ createClient,
12
+ getErrorDocumentation,
13
+ MissingClientValuesError,
14
+ NetworkError,
15
+ PostgrestError,
16
+ RateLimitError,
17
+ StorageError,
18
+ SupatypeCodedError,
19
+ SupatypeError,
20
+ } from "../src/index.js"
21
+
22
+ describe("SupatypeError, the class every result error is", () => {
23
+ it("is what a request that failed in transit resolves with", async () => {
24
+ vi.stubGlobal("fetch", () => Promise.reject(new TypeError("fetch failed")))
25
+ const { error } = await createClient({ url: "http://127.0.0.1:9", anonKey: "x", retry: false }).from("posts").select("id")
26
+ vi.unstubAllGlobals()
27
+
28
+ expect(error).toBeInstanceOf(SupatypeError)
29
+ expect(error).toBeInstanceOf(NetworkError)
30
+ expect(String(error)).toBe("NetworkError: fetch failed")
31
+ })
32
+
33
+ it("is a value: built from a result's fields, its JSON and spread are exactly those fields", () => {
34
+ const error: SupatypeError = new SupatypeError({ message: "refused", status: 403, code: "42501", hint: "ask" })
35
+
36
+ expect(error.message).toBe("refused")
37
+ expect({ ...error }).toEqual({ message: "refused", status: 403, code: "42501", hint: "ask" })
38
+ expect(JSON.parse(JSON.stringify(error))).toEqual({ message: "refused", status: 403, code: "42501", hint: "ask" })
39
+ })
40
+ })
41
+
42
+ describe("SupatypeCodedError, the errors the SDK throws", () => {
43
+ it.each([
44
+ ["NetworkError", new NetworkError("offline")],
45
+ ["RateLimitError", new RateLimitError(3)],
46
+ ["AuthError", new AuthError("no")],
47
+ ["StorageError", new StorageError("no", "STORAGE_ERROR", 413)],
48
+ ["PostgrestError", new PostgrestError("no")],
49
+ ])("%s is a SupatypeCodedError and a SupatypeError", (_name, thrown) => {
50
+ expect(thrown).toBeInstanceOf(SupatypeCodedError)
51
+ expect(thrown).toBeInstanceOf(SupatypeError)
52
+ expect(thrown.helpUrl).toBe(`https://docs.supatype.com/errors#${thrown.code.toLowerCase()}`)
53
+ })
54
+
55
+ it("carries its HTTP status as status, the one name for it", () => {
56
+ expect(new RateLimitError(3).status).toBe(429)
57
+ expect(new StorageError("too big", "STORAGE_FILE_TOO_LARGE", 413).status).toBe(413)
58
+ expect(PostgrestError.fromResponse({ message: "denied", code: "42501" }, 403).status).toBe(403)
59
+ expect(JSON.parse(JSON.stringify(new RateLimitError(3)))).toEqual({
60
+ message: "Rate limited. Retry after 3 seconds.",
61
+ code: "RATE_LIMITED",
62
+ status: 429,
63
+ })
64
+ })
65
+
66
+ it("leaves a PostgREST hint and details absent, not null, when the server gave none", () => {
67
+ const error = new PostgrestError("no")
68
+ expect(error.hint).toBeUndefined()
69
+ expect(error.details).toBeUndefined()
70
+ })
71
+
72
+ it("counts a client with no address or anon key among them", () => {
73
+ const error = new MissingClientValuesError("no values", ["url"])
74
+ expect(error).toBeInstanceOf(SupatypeCodedError)
75
+ expect(error).toBeInstanceOf(SupatypeError)
76
+ expect(error.code).toBe("MISSING_CLIENT_VALUES")
77
+ expect(getErrorDocumentation(error.code)?.category).toBe("setup")
78
+ })
79
+ })
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The examples Supatype serves (`app.mode: "static"`) run from a plain production `vite build`.
3
+ *
4
+ * 0.9.1 release test (RB9): `supatype keys` and `dev` write a local stack's anon key to
5
+ * `.env.development.local`, which a production build never reads, so a build made by the README's
6
+ * own `vite build` had no key. Each example threw `VITE_SUPATYPE_ANON_KEY is not set` at load and
7
+ * the page was blank. The examples now carry no key in the build: the page loads `/supatype-env.js`
8
+ * from the server that serves it, and the client reads the key from there at its first request.
9
+ *
10
+ * Each example's client is built here with Vite in production mode, from a directory holding no
11
+ * `.env` at all, then run against a page whose script set the values.
12
+ */
13
+
14
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
15
+ import { tmpdir } from "node:os"
16
+ import { dirname, join, resolve } from "node:path"
17
+ import { fileURLToPath, pathToFileURL } from "node:url"
18
+ import { build, type Rollup } from "vite"
19
+ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"
20
+
21
+ const HERE = dirname(fileURLToPath(import.meta.url))
22
+ const CLIENT_ENTRY = resolve(HERE, "../src/index.ts")
23
+ const EXAMPLES = resolve(HERE, "../../../examples")
24
+
25
+ interface ServedExample {
26
+ name: string
27
+ /** The module that creates the example's client, exporting it as `supatype`. */
28
+ client: string
29
+ /** Every page Vite builds for it. */
30
+ pages: string[]
31
+ }
32
+
33
+ const SERVED: readonly ServedExample[] = [
34
+ { name: "kitchen-sink", client: "kitchen-sink/apps/app/src/client.ts", pages: ["kitchen-sink/apps/app/index.html"] },
35
+ { name: "supabucks", client: "supabucks/src/supatype.ts", pages: ["supabucks/index.html"] },
36
+ {
37
+ name: "framework-parity",
38
+ client: "framework-parity/src/client.ts",
39
+ pages: ["vue", "svelte", "solid"].map((app) => `framework-parity/src/${app}/index.html`),
40
+ },
41
+ ]
42
+
43
+ const PAGE_ORIGIN = "https://app.example.com"
44
+ const DEPLOYED_KEY = "deployed-anon-key"
45
+
46
+ let workDir = ""
47
+ let runs = 0
48
+
49
+ /** The one chunk a single-entry build writes. */
50
+ function onlyChunk(output: Rollup.RollupOutput | Rollup.RollupOutput[] | Rollup.RollupWatcher): string {
51
+ const outputs = Array.isArray(output) ? output : [output]
52
+ const chunk = outputs.flatMap((o) => ("output" in o ? o.output : [])).find((item) => item.type === "chunk")
53
+ if (chunk === undefined) throw new Error("vite build wrote no chunk")
54
+ return chunk.code
55
+ }
56
+
57
+ /** The example's client, built as `vite build` builds it, with no `.env` anywhere Vite looks. */
58
+ async function buildClient(example: ServedExample): Promise<string> {
59
+ const dir = join(workDir, example.name)
60
+ const entry = join(dir, "main.js")
61
+ const client = resolve(EXAMPLES, example.client).replace(/\\/g, "/")
62
+ writeFileSync(
63
+ entry,
64
+ [`import { supatype } from ${JSON.stringify(client)}`, `globalThis.firstRequest = () => supatype.from("posts").select()`].join("\n"),
65
+ "utf8",
66
+ )
67
+ const output = await build({
68
+ root: dir,
69
+ envDir: dir,
70
+ configFile: false,
71
+ logLevel: "silent",
72
+ mode: "production",
73
+ resolve: { alias: { "@supatype/client": CLIENT_ENTRY } },
74
+ build: { write: false, minify: true, rollupOptions: { input: entry } },
75
+ })
76
+ return onlyChunk(output)
77
+ }
78
+
79
+ /** Run a bundle as the page loads it: a file of its own each time, since a module runs once per URL. */
80
+ async function runBundle(bundle: string): Promise<void> {
81
+ runs += 1
82
+ const file = join(workDir, `bundle-${runs}.mjs`)
83
+ writeFileSync(file, bundle, "utf8")
84
+ await import(pathToFileURL(file).href)
85
+ }
86
+
87
+ /** The anon key each request is sent with, answered with an empty list. */
88
+ function stubFetch(): string[] {
89
+ const keys: string[] = []
90
+ vi.stubGlobal("fetch", async (_url: string, init?: RequestInit) => {
91
+ keys.push(new Headers(init?.headers).get("apikey") ?? "")
92
+ return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
93
+ })
94
+ return keys
95
+ }
96
+
97
+ function firstRequest(): Promise<unknown> {
98
+ const run: unknown = Reflect.get(globalThis, "firstRequest")
99
+ if (typeof run !== "function") throw new Error("the bundle set up no request")
100
+ return Promise.resolve(Reflect.apply(run, undefined, []))
101
+ }
102
+
103
+ beforeAll(() => {
104
+ workDir = mkdtempSync(join(tmpdir(), "supatype-example-bundle-"))
105
+ for (const example of SERVED) mkdirSync(join(workDir, example.name))
106
+ })
107
+
108
+ afterEach(() => {
109
+ vi.unstubAllGlobals()
110
+ })
111
+
112
+ afterAll(() => {
113
+ if (workDir !== "") rmSync(workDir, { recursive: true, force: true })
114
+ })
115
+
116
+ describe.each(SERVED)("the $name example, built with no anon key", (example) => {
117
+ it("loads, and sends the key the server's /supatype-env.js set", async () => {
118
+ const bundle = await buildClient(example)
119
+ const keys = stubFetch()
120
+ vi.stubGlobal("firstRequest", undefined)
121
+ vi.stubGlobal("window", { location: { origin: PAGE_ORIGIN } })
122
+ vi.stubGlobal("__SUPATYPE_ENV__", { url: PAGE_ORIGIN, anonKey: DEPLOYED_KEY })
123
+ await runBundle(bundle)
124
+ await firstRequest()
125
+ expect(keys).toEqual([DEPLOYED_KEY])
126
+ }, 60_000)
127
+
128
+ it.each(example.pages)("%s loads /supatype-env.js in the head, before the app's own script", (page) => {
129
+ const html = readFileSync(resolve(EXAMPLES, page), "utf8")
130
+ const head = html.slice(0, html.indexOf("</head>"))
131
+ // A plain script: async or defer could let it run after the app's module script.
132
+ expect(head).toMatch(/<script src="\/supatype-env\.js" vite-ignore><\/script>/)
133
+ expect(html.indexOf("/supatype-env.js")).toBeLessThan(html.indexOf('type="module"'))
134
+ })
135
+ })
@@ -0,0 +1,63 @@
1
+ import { vi, describe, it, expect, afterEach } from "vitest"
2
+ import { createClient, type AnyDatabase, type AuthRedirectError, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding's auth primitive owes a component unmounted while the client is
6
+ * still starting: no auth listener left behind.
7
+ *
8
+ * Vue's and Solid's subscribed only after awaiting start-up, so an unmount in that window ran its
9
+ * cleanup before there was anything to clean up, and the listener stayed for the life of the
10
+ * client. Shared by the Vue, Svelte and Solid suites over a real client, built from the package the
11
+ * bindings import. Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
12
+ */
13
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
14
+
15
+ interface ListenerCount {
16
+ subscribed: number
17
+ unsubscribed: number
18
+ }
19
+
20
+ /** Counts every auth listener the client hands out and every one given back. */
21
+ function countListeners(client: SupatypeClient<AnyDatabase>): ListenerCount {
22
+ const count: ListenerCount = { subscribed: 0, unsubscribed: 0 }
23
+ const subscribe = client.auth.onAuthStateChange.bind(client.auth)
24
+ vi.spyOn(client.auth, "onAuthStateChange").mockImplementation((listener) => {
25
+ const handed = subscribe(listener)
26
+ count.subscribed += 1
27
+ const unsubscribe = handed.data.subscription.unsubscribe.bind(handed.data.subscription)
28
+ vi.spyOn(handed.data.subscription, "unsubscribe").mockImplementation(() => {
29
+ count.unsubscribed += 1
30
+ unsubscribe()
31
+ })
32
+ return handed
33
+ })
34
+ return count
35
+ }
36
+
37
+ export function describeAuthUnmountBinding(
38
+ name: string,
39
+ mount: (client: SupatypeClient<AnyDatabase>) => void,
40
+ unmount: () => void,
41
+ ): void {
42
+ describe(`${name} unmounted while the client is starting`, () => {
43
+ afterEach(() => {
44
+ vi.restoreAllMocks()
45
+ })
46
+
47
+ it("leaves no auth listener behind", async () => {
48
+ const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
49
+ let started: (value: { error: AuthRedirectError | null }) => void = () => undefined
50
+ vi.spyOn(client.auth, "initialize").mockReturnValue(new Promise((resolve) => { started = resolve }))
51
+ const count = countListeners(client)
52
+
53
+ mount(client)
54
+ await settle()
55
+ unmount()
56
+ started({ error: null })
57
+ await settle()
58
+
59
+ expect(count.subscribed).toBeGreaterThan(0)
60
+ expect(count.unsubscribed).toBe(count.subscribed)
61
+ })
62
+ })
63
+ }
@@ -101,3 +101,25 @@ export function channelOf(frame: Record<string, unknown> | undefined): string {
101
101
  if (typeof channel !== "string") throw new Error(`the frame names no channel: ${JSON.stringify(frame)}`)
102
102
  return channel
103
103
  }
104
+ /** The subscribe frames the client sent on a socket for `channel`, in order. */
105
+ export function subscribeFrames(ws: MockWebSocketInstance, channel: string): Array<Record<string, unknown>> {
106
+ return sentFrames(ws).filter((frame) => frame["type"] === "subscribe" && frame["channel"] === channel)
107
+ }
108
+
109
+ /** The server takes the newest join on `channel`, echoing its ref as the real server does. */
110
+ export function ackNewestJoin(ws: MockWebSocketInstance, channel: string): void {
111
+ const newest = subscribeFrames(ws, channel).at(-1)
112
+ if (newest === undefined) throw new Error(`no join was sent on ${channel}`)
113
+ simulateServerMessage(ws, { type: "system", status: "ok", message: `subscribed to ${channel}`, ref: newest["ref"] })
114
+ }
115
+
116
+ /** The server delivers an INSERT of the row `{ id }` on `channel`. */
117
+ export function deliverInsert(ws: MockWebSocketInstance, channel: string, id: number): void {
118
+ simulateServerMessage(ws, {
119
+ type: "change",
120
+ channel,
121
+ event: "INSERT",
122
+ payload: { old: null, new: { id } },
123
+ timestamp: "2026-11-11T00:00:00Z",
124
+ })
125
+ }
@@ -1,5 +1,6 @@
1
1
  import { vi, describe, it, expect, beforeEach, afterEach } from "vitest"
2
- import type { AuthRedirectError, Session, SupatypeError } from "../../src/types.js"
2
+ import type { Session } from "../../src/types.js"
3
+ import { AuthRedirectError, SupatypeError } from "../../src/errors.js"
3
4
 
4
5
  /**
5
6
  * What every framework binding's auth primitive owes an OAuth sign-in.
@@ -71,7 +72,7 @@ export function describeOAuthBinding(
71
72
  })
72
73
 
73
74
  it("stays on the page and returns the error when the provider is not enabled", async () => {
74
- const refusal = { message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" }
75
+ const refusal = new SupatypeError({ message: "Sign-in with github is not enabled for this project.", code: "provider_disabled" })
75
76
  harness.auth.signInWithOAuth.mockResolvedValue({ data: { url: "", provider: "github" }, error: refusal })
76
77
 
77
78
  const { error } = await mount(harness).signInWithOAuth("github")
@@ -81,7 +82,7 @@ export function describeOAuthBinding(
81
82
  })
82
83
 
83
84
  it("exposes a refusal the server sent back in the URL", async () => {
84
- harness.redirectError = { message: "Signups not allowed", code: "signup_disabled", provider: "github" }
85
+ harness.redirectError = new AuthRedirectError({ message: "Signups not allowed", code: "signup_disabled", provider: "github" })
85
86
 
86
87
  const probe = mount(harness)
87
88
  await settle()
@@ -0,0 +1,99 @@
1
+ import { vi, describe, it, expect, afterEach } from "vitest"
2
+ import { createClient, type AnyDatabase, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding's query owes options that change after it mounted: a new read.
6
+ *
7
+ * 0.9.1 release test (FF25): the Vue, Svelte and Solid queries read their options once, so a
8
+ * table whose sort, page or filter came from component state kept showing the first read. Each
9
+ * suite mounts its binding with options held in its own reactive primitive (a ref or getter, a
10
+ * store, a signal) and changes them through `change`. Not named `*.test.ts`, so vitest's default
11
+ * include does not collect it as a suite.
12
+ */
13
+ export interface ReadOptions {
14
+ order: { column: string; ascending: boolean }
15
+ limit?: number
16
+ offset?: number
17
+ filter?: Record<string, unknown>
18
+ enabled?: boolean
19
+ }
20
+
21
+ export interface ReactiveOptionsProbe {
22
+ change(options: ReadOptions): void
23
+ }
24
+
25
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
26
+
27
+ /** The query string of every read sent, decoded, in order. */
28
+ function sentReads(): string[] {
29
+ const sent: string[] = []
30
+ vi.stubGlobal(
31
+ "fetch",
32
+ vi.fn(async (input: string | URL | Request) => {
33
+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url)
34
+ sent.push(decodeURIComponent(url.search))
35
+ return new Response("[]", { status: 200, headers: { "Content-Type": "application/json" } })
36
+ }),
37
+ )
38
+ return sent
39
+ }
40
+
41
+ const FIRST: ReadOptions = { order: { column: "title", ascending: true }, limit: 2 }
42
+
43
+ export function describeReactiveOptionsBinding(
44
+ name: string,
45
+ mount: (client: SupatypeClient<AnyDatabase>, initial: ReadOptions) => ReactiveOptionsProbe,
46
+ unmount: () => void,
47
+ ): void {
48
+ async function mounted(): Promise<{ probe: ReactiveOptionsProbe; sent: string[] }> {
49
+ const sent = sentReads()
50
+ const probe = mount(createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" }), FIRST)
51
+ await settle()
52
+ return { probe, sent }
53
+ }
54
+
55
+ describe(`${name} when its options change`, () => {
56
+ afterEach(() => {
57
+ unmount()
58
+ vi.unstubAllGlobals()
59
+ })
60
+
61
+ it("reads once on mount", async () => {
62
+ const { sent } = await mounted()
63
+ expect(sent).toEqual(["?order=title.asc.nullslast&limit=2"])
64
+ })
65
+
66
+ it("reads again with the new sort", async () => {
67
+ const { probe, sent } = await mounted()
68
+ probe.change({ ...FIRST, order: { column: "title", ascending: false } })
69
+ await settle()
70
+ expect(sent.at(-1)).toBe("?order=title.desc.nullslast&limit=2")
71
+ expect(sent).toHaveLength(2)
72
+ })
73
+
74
+ it("reads the next page as one limit and offset", async () => {
75
+ const { probe, sent } = await mounted()
76
+ probe.change({ ...FIRST, offset: 2 })
77
+ await settle()
78
+ expect(sent.at(-1)).toBe("?order=title.asc.nullslast&limit=2&offset=2")
79
+ })
80
+
81
+ it("reads again with the new filter", async () => {
82
+ const { probe, sent } = await mounted()
83
+ probe.change({ ...FIRST, filter: { status: "draft" } })
84
+ await settle()
85
+ expect(sent.at(-1)).toBe("?status=eq.draft&order=title.asc.nullslast&limit=2")
86
+ })
87
+
88
+ it("does not read while disabled, and reads when enabled again", async () => {
89
+ const { probe, sent } = await mounted()
90
+ probe.change({ ...FIRST, enabled: false })
91
+ await settle()
92
+ expect(sent).toHaveLength(1)
93
+ probe.change({ ...FIRST, offset: 2 })
94
+ await settle()
95
+ expect(sent).toHaveLength(2)
96
+ expect(sent.at(-1)).toBe("?order=title.asc.nullslast&limit=2&offset=2")
97
+ })
98
+ })
99
+ }
@@ -0,0 +1,113 @@
1
+ import { vi, describe, it, expect, afterEach } from "vitest"
2
+ import { createClient, QueryBuilder, SupatypeError, type AnyDatabase, type QueryResult, type SupatypeClient } from "@supatype/client"
3
+
4
+ /**
5
+ * What every framework binding's query owes a read that finishes after a newer one: nothing.
6
+ *
7
+ * A refetch while a read is in flight puts two reads on the wire, and the older can land last.
8
+ * Whatever it brings, rows, a returned error or a throw, must not replace what the newer read
9
+ * showed, nor end loading while the newer read is still out. Shared by the Vue, Svelte and Solid
10
+ * suites over a real client, built from the package the bindings import, so the prototype held
11
+ * is the one the bindings call. Not named `*.test.ts`, so vitest's default include does not
12
+ * collect it as a suite.
13
+ */
14
+ export interface StaleReadProbe {
15
+ data(): unknown
16
+ error(): unknown
17
+ loading(): boolean
18
+ refetch(): Promise<void>
19
+ }
20
+
21
+ interface PendingRead {
22
+ resolve(result: QueryResult<unknown[]>): void
23
+ reject(reason: unknown): void
24
+ }
25
+
26
+ const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
27
+
28
+ /** Every read waits until the test settles it, in the order the binding sent them. */
29
+ function heldReads(): PendingRead[] {
30
+ const reads: PendingRead[] = []
31
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) => {
32
+ const answer = new Promise<QueryResult<unknown[]>>((resolve, reject) => reads.push({ resolve, reject }))
33
+ return answer.then(onOk, onRejected)
34
+ })
35
+ return reads
36
+ }
37
+
38
+ function rows(id: number): QueryResult<unknown[]> {
39
+ return { data: [{ id }], error: null, count: null }
40
+ }
41
+
42
+ interface InFlight {
43
+ probe: StaleReadProbe
44
+ older: PendingRead
45
+ newer: PendingRead
46
+ newerDone: Promise<void>
47
+ }
48
+
49
+ export function describeStaleReadBinding(
50
+ name: string,
51
+ mount: (client: SupatypeClient<AnyDatabase>) => StaleReadProbe,
52
+ unmount: () => void,
53
+ ): void {
54
+ /** The binding's first read and a refetch, both still out. */
55
+ async function twoReadsInFlight(): Promise<InFlight> {
56
+ const reads = heldReads()
57
+ const probe = mount(createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" }))
58
+ await settle()
59
+ const older = reads.at(-1)
60
+ const newerDone = probe.refetch()
61
+ await settle()
62
+ const newer = reads.at(-1)
63
+ if (older === undefined || newer === undefined || older === newer) throw new Error("expected two reads")
64
+ return { probe, older, newer, newerDone }
65
+ }
66
+
67
+ describe(`${name} when an older read finishes last`, () => {
68
+ afterEach(() => {
69
+ unmount()
70
+ vi.restoreAllMocks()
71
+ })
72
+
73
+ it("keeps the newer rows over the older rows", async () => {
74
+ const { probe, older, newer, newerDone } = await twoReadsInFlight()
75
+ newer.resolve(rows(2))
76
+ await newerDone
77
+ older.resolve(rows(1))
78
+ await settle()
79
+ expect(probe.data()).toEqual([{ id: 2 }])
80
+ })
81
+
82
+ it("keeps the newer rows over the older read's returned error", async () => {
83
+ const { probe, older, newer, newerDone } = await twoReadsInFlight()
84
+ newer.resolve(rows(2))
85
+ await newerDone
86
+ older.resolve({ data: null, error: new SupatypeError({ message: "permission denied" }), count: null })
87
+ await settle()
88
+ expect(probe.data()).toEqual([{ id: 2 }])
89
+ expect(probe.error()).toBeNull()
90
+ })
91
+
92
+ it("keeps the newer rows over the older read's throw, still reporting it", async () => {
93
+ const logged = vi.spyOn(console, "error").mockImplementation(() => undefined)
94
+ const thrown = new Error("Supatype client has no API address")
95
+ const { probe, older, newer, newerDone } = await twoReadsInFlight()
96
+ newer.resolve(rows(2))
97
+ await newerDone
98
+ older.reject(thrown)
99
+ await settle()
100
+ expect(probe.data()).toEqual([{ id: 2 }])
101
+ expect(probe.error()).toBeNull()
102
+ expect(logged.mock.calls.filter((call) => call.includes(thrown))).toHaveLength(1)
103
+ })
104
+
105
+ it("stays loading while the newer read is out after the older one lands", async () => {
106
+ const { probe, older } = await twoReadsInFlight()
107
+ older.resolve(rows(1))
108
+ await settle()
109
+ expect(probe.loading()).toBe(true)
110
+ expect(probe.data()).toBeNull()
111
+ })
112
+ })
113
+ }