@supatype/client 0.9.1 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +75 -70
- package/.turbo/turbo-typecheck.log +1 -1
- package/dist/auth.d.ts +9 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +15 -0
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +1 -1
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +1 -1
- package/dist/bindings.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +15 -0
- package/dist/latest-rows.d.ts.map +1 -1
- package/dist/latest-rows.js +14 -7
- package/dist/latest-rows.js.map +1 -1
- package/dist/query.d.ts +7 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +11 -3
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +17 -6
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +108 -35
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts.map +1 -1
- package/dist/runtime-env.js +40 -5
- package/dist/runtime-env.js.map +1 -1
- package/dist/table-subscription.d.ts +4 -2
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +6 -4
- package/dist/table-subscription.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/auth.ts +15 -0
- package/src/bindings.ts +1 -1
- package/src/index.ts +2 -2
- package/src/latest-rows.ts +24 -7
- package/src/query.ts +11 -3
- package/src/realtime.ts +131 -38
- package/src/runtime-env.ts +47 -5
- package/src/table-subscription.ts +6 -4
- package/src/types.ts +5 -0
- package/tests/auth-sso.test.ts +32 -1
- package/tests/examples-runtime-env.test.ts +135 -0
- package/tests/helpers/mock-websocket.ts +22 -0
- package/tests/helpers/reactive-options-binding.ts +99 -0
- package/tests/query.test.ts +39 -2
- package/tests/realtime-multi-tenant-integration.test.ts +0 -1
- package/tests/realtime-refusal-error.test.ts +79 -0
- package/tests/realtime-rows-after-broadcast.test.ts +205 -0
- package/tests/realtime-session-auth.test.ts +0 -1
- package/tests/realtime-shared-channel.test.ts +9 -27
- package/tests/runtime-env-expo.test.ts +58 -0
- package/tests/runtime-env.test.ts +35 -0
- package/tests/subscribe-frame.test.ts +48 -0
- package/tsconfig.json +2 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -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
|
+
})
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|
package/tests/query.test.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
2
|
import { QueryBuilder, MutationBuilder, defaultQueryCache } from "../src/query.js"
|
|
3
|
+
import { QueryCache } from "../src/query-cache.js"
|
|
3
4
|
import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
|
|
4
5
|
|
|
5
6
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
@@ -136,11 +137,47 @@ describe("QueryBuilder: URL construction", () => {
|
|
|
136
137
|
expect(url()).toContain("limit=20")
|
|
137
138
|
})
|
|
138
139
|
|
|
139
|
-
|
|
140
|
+
// 0.9.1 release test (FF15): `range` sent a `Range` header while `limit` sent `?limit=`, and
|
|
141
|
+
// PostgREST refuses the pair with 416 PGRST103. Both now live in the query string, as in
|
|
142
|
+
// supabase-js: `range` sets `offset` and `limit`, and whichever of the two is called last
|
|
143
|
+
// decides the page size.
|
|
144
|
+
it(".range() sets offset and limit params and no Range header", async () => {
|
|
140
145
|
const fetch = mockFetch([])
|
|
141
146
|
vi.stubGlobal("fetch", fetch)
|
|
142
147
|
await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(10, 19)
|
|
143
|
-
|
|
148
|
+
const params = new URL(fetchCall(fetch).url).searchParams
|
|
149
|
+
expect(params.get("offset")).toBe("10")
|
|
150
|
+
expect(params.get("limit")).toBe("10")
|
|
151
|
+
expect(header(fetchCall(fetch).init, "Range")).toBeNull()
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
it(".limit() then .range() sends one limit, the range's", async () => {
|
|
155
|
+
const { url } = captureUrl()
|
|
156
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).limit(2).range(2, 3)
|
|
157
|
+
const params = new URL(url()).searchParams
|
|
158
|
+
expect(params.getAll("limit")).toEqual(["2"])
|
|
159
|
+
expect(params.get("offset")).toBe("2")
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
it(".range() then .limit() keeps the offset and takes the later limit", async () => {
|
|
163
|
+
const { url } = captureUrl()
|
|
164
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).range(20, 29).limit(5)
|
|
165
|
+
const params = new URL(url()).searchParams
|
|
166
|
+
expect(params.getAll("limit")).toEqual(["5"])
|
|
167
|
+
expect(params.get("offset")).toBe("20")
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
// The cache key is the URL and the caller's identity. A page carried in a header was not part
|
|
171
|
+
// of it, so a cached second page answered with the first.
|
|
172
|
+
it("a cached read of one page is not served for another", async () => {
|
|
173
|
+
const fetch = mockFetch([])
|
|
174
|
+
vi.stubGlobal("fetch", fetch)
|
|
175
|
+
const cache = new QueryCache()
|
|
176
|
+
const page = (from: number) =>
|
|
177
|
+
new QueryBuilder<Post>(BASE, PATH, HEADERS, undefined, cache).cache({ ttl: 60_000 }).range(from, from + 9)
|
|
178
|
+
await page(0)
|
|
179
|
+
await page(10)
|
|
180
|
+
expect(fetch).toHaveBeenCalledTimes(2)
|
|
144
181
|
})
|
|
145
182
|
|
|
146
183
|
it("multiple chained filters all appear in URL", async () => {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A refused join hands the status callback the server's reason, as `(status, err)`.
|
|
3
|
+
*
|
|
4
|
+
* 0.9.2 release test (N-FF5): the server now refuses a join for a table that does not exist, and
|
|
5
|
+
* says which table. The client reported CHANNEL_ERROR and dropped the reason, so the bindings could
|
|
6
|
+
* only say "Subscription error" and the developer had to read the socket's frames to find the typo.
|
|
7
|
+
* The callback's second argument is how Supabase's client reports it too, so an existing
|
|
8
|
+
* `(status) => ...` callback is unaffected.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, afterEach } from "vitest"
|
|
12
|
+
import type { ChannelStatus } from "../src/realtime.js"
|
|
13
|
+
import { subscriptionViewOf, watchTable, type SubscriptionView } from "../src/table-subscription.js"
|
|
14
|
+
import { simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
|
|
15
|
+
import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
|
|
16
|
+
|
|
17
|
+
const REASON = "table public.notes does not exist: check the table name and schema"
|
|
18
|
+
|
|
19
|
+
let harness: SocketSwapHarness
|
|
20
|
+
|
|
21
|
+
afterEach(() => harness.restore())
|
|
22
|
+
|
|
23
|
+
/** The server refuses the newest socket's first join, naming its channel, with {@link REASON}. */
|
|
24
|
+
function refuseFirstJoin(): void {
|
|
25
|
+
const channel = subscribedChannels(harness.socket())[0]
|
|
26
|
+
simulateServerMessage(harness.socket(), { type: "system", status: "error", message: REASON, channel, ref: "1" })
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe("a refused join", () => {
|
|
30
|
+
it("passes the server's message to the status callback as an Error", async () => {
|
|
31
|
+
harness = createSocketSwapHarness()
|
|
32
|
+
const seen: Array<{ status: ChannelStatus; err: Error | undefined }> = []
|
|
33
|
+
harness.realtime
|
|
34
|
+
.channel("notes:team")
|
|
35
|
+
.on("postgres_changes", { event: "*", table: "notes" }, () => {})
|
|
36
|
+
.subscribe((status, err) => seen.push({ status, err }))
|
|
37
|
+
await harness.settle()
|
|
38
|
+
refuseFirstJoin()
|
|
39
|
+
|
|
40
|
+
expect(seen).toHaveLength(1)
|
|
41
|
+
expect(seen[0]?.status).toBe("CHANNEL_ERROR")
|
|
42
|
+
expect(seen[0]?.err).toBeInstanceOf(Error)
|
|
43
|
+
expect(seen[0]?.err?.message).toBe(REASON)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it("passes no error with any other status", async () => {
|
|
47
|
+
harness = createSocketSwapHarness()
|
|
48
|
+
const errs: Array<Error | undefined> = []
|
|
49
|
+
harness.realtime
|
|
50
|
+
.channel("notes:ok")
|
|
51
|
+
.on("postgres_changes", { event: "*", table: "note" }, () => {})
|
|
52
|
+
.subscribe((_status, err) => errs.push(err))
|
|
53
|
+
await harness.settle()
|
|
54
|
+
harness.ackJoins()
|
|
55
|
+
|
|
56
|
+
expect(errs).toEqual([undefined])
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it("reaches the bindings' view as the error message", async () => {
|
|
60
|
+
harness = createSocketSwapHarness()
|
|
61
|
+
const views: SubscriptionView[] = []
|
|
62
|
+
const stop = watchTable(harness.realtime, "notes", undefined, {
|
|
63
|
+
rows: () => undefined,
|
|
64
|
+
status: (view) => views.push(view),
|
|
65
|
+
})
|
|
66
|
+
await harness.settle()
|
|
67
|
+
refuseFirstJoin()
|
|
68
|
+
stop()
|
|
69
|
+
|
|
70
|
+
expect(views.map((view) => view.error?.message)).toEqual([REASON])
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
describe("subscriptionViewOf with an error", () => {
|
|
75
|
+
it("shows the error's message, and the old wording when there is none", () => {
|
|
76
|
+
expect(subscriptionViewOf("CHANNEL_ERROR", new Error(REASON)).error?.message).toBe(REASON)
|
|
77
|
+
expect(subscriptionViewOf("CHANNEL_ERROR").error?.message).toBe("Subscription error")
|
|
78
|
+
})
|
|
79
|
+
})
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A row listener added to a channel already joined without one gets a join that delivers its rows.
|
|
3
|
+
*
|
|
4
|
+
* A join made for broadcast or presence alone carries `changes: false`, and the server sends it no
|
|
5
|
+
* rows. A row listener added after that, on the same handle or a second handle with the same name,
|
|
6
|
+
* used to find the join already sent: `subscribe()` reported SUBSCRIBED at once, no second frame
|
|
7
|
+
* went out, and no row ever arrived (0.9.2 release test, FF-1).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, expect, beforeEach, afterEach } from "vitest"
|
|
11
|
+
import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
|
|
12
|
+
import { ackNewestJoin, deliverInsert, simulateServerMessage, subscribeFrames } from "./helpers/mock-websocket.js"
|
|
13
|
+
import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
|
|
14
|
+
|
|
15
|
+
let harness: SocketSwapHarness
|
|
16
|
+
|
|
17
|
+
/** A channel joined for broadcast alone, with that join sent and acknowledged. */
|
|
18
|
+
async function joinedForBroadcast(channel: string): Promise<{ statuses: ChannelStatus[] }> {
|
|
19
|
+
const statuses: ChannelStatus[] = []
|
|
20
|
+
harness.realtime.channel(channel).onBroadcast("ping", () => {}).subscribe((s) => statuses.push(s))
|
|
21
|
+
await harness.settle()
|
|
22
|
+
ackNewestJoin(harness.socket(), channel)
|
|
23
|
+
return { statuses }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
beforeEach(() => {
|
|
27
|
+
harness = createSocketSwapHarness()
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
afterEach(() => harness.restore())
|
|
31
|
+
|
|
32
|
+
describe("a row listener added to a channel joined for broadcast", () => {
|
|
33
|
+
it("on a second handle joins again for its rows and reports SUBSCRIBED only once that join is acknowledged", async () => {
|
|
34
|
+
const first = await joinedForBroadcast("room:x")
|
|
35
|
+
const statuses: ChannelStatus[] = []
|
|
36
|
+
const rows: Array<RealtimePayload<Record<string, unknown>>> = []
|
|
37
|
+
harness.realtime
|
|
38
|
+
.channel("room:x")
|
|
39
|
+
.on("postgres_changes", { event: "INSERT", table: "note" }, (p) => rows.push(p))
|
|
40
|
+
.subscribe((s) => statuses.push(s))
|
|
41
|
+
|
|
42
|
+
const joins = subscribeFrames(harness.socket(), "room:x")
|
|
43
|
+
expect(joins.map((frame) => frame["changes"])).toEqual([false, true])
|
|
44
|
+
expect(joins[1]).toMatchObject({ schema: "public", table: "note", event: "INSERT" })
|
|
45
|
+
expect(statuses).toEqual([])
|
|
46
|
+
|
|
47
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
48
|
+
deliverInsert(harness.socket(), "room:x", 1)
|
|
49
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
50
|
+
// The broadcast join kept serving it until the server took the rows join in its place.
|
|
51
|
+
expect(first.statuses).toEqual(["SUBSCRIBED"])
|
|
52
|
+
expect(rows.map((p) => [p.table, p.new])).toEqual([["note", { id: 1 }]])
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it("on the same handle joins again for its rows", async () => {
|
|
56
|
+
const statuses: ChannelStatus[] = []
|
|
57
|
+
const rows: Array<RealtimePayload<Record<string, unknown>>> = []
|
|
58
|
+
const handle = harness.realtime.channel("room:x").onBroadcast("ping", () => {}).subscribe()
|
|
59
|
+
await harness.settle()
|
|
60
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
61
|
+
|
|
62
|
+
handle.on("postgres_changes", { event: "INSERT", table: "note" }, (p) => rows.push(p)).subscribe((s) => statuses.push(s))
|
|
63
|
+
expect(subscribeFrames(harness.socket(), "room:x").map((frame) => frame["changes"])).toEqual([false, true])
|
|
64
|
+
expect(statuses).toEqual([])
|
|
65
|
+
|
|
66
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
67
|
+
deliverInsert(harness.socket(), "room:x", 1)
|
|
68
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
69
|
+
expect(rows.map((p) => p.new)).toEqual([{ id: 1 }])
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it("on a channel named after that table joins again for its rows", async () => {
|
|
73
|
+
await joinedForBroadcast("note")
|
|
74
|
+
const rows: Array<RealtimePayload<Record<string, unknown>>> = []
|
|
75
|
+
harness.realtime.channel("note").on("postgres_changes", { event: "INSERT", table: "note" }, (p) => rows.push(p)).subscribe()
|
|
76
|
+
|
|
77
|
+
const joins = subscribeFrames(harness.socket(), "note")
|
|
78
|
+
expect(joins.map((frame) => frame["changes"])).toEqual([false, true])
|
|
79
|
+
expect(joins[1]).toMatchObject({ schema: "public", table: "note", event: "INSERT" })
|
|
80
|
+
|
|
81
|
+
ackNewestJoin(harness.socket(), "note")
|
|
82
|
+
deliverInsert(harness.socket(), "note", 1)
|
|
83
|
+
expect(rows.map((p) => p.new)).toEqual([{ id: 1 }])
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
it("joins again when the broadcast join is still waiting for its reply, and ignores that stale reply", async () => {
|
|
87
|
+
const statuses: ChannelStatus[] = []
|
|
88
|
+
harness.realtime.channel("room:x").onBroadcast("ping", () => {}).subscribe()
|
|
89
|
+
await harness.settle()
|
|
90
|
+
const broadcastJoin = subscribeFrames(harness.socket(), "room:x")[0]
|
|
91
|
+
|
|
92
|
+
harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe((s) => statuses.push(s))
|
|
93
|
+
expect(subscribeFrames(harness.socket(), "room:x").map((frame) => frame["changes"])).toEqual([false, true])
|
|
94
|
+
|
|
95
|
+
simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "subscribed to room:x", ref: broadcastJoin?.["ref"] })
|
|
96
|
+
expect(statuses).toEqual([])
|
|
97
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
98
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
/** The server refuses the newest join on `channel`, as it refuses a table the caller cannot read. */
|
|
103
|
+
function refuseNewestJoin(channel: string): void {
|
|
104
|
+
const newest = subscribeFrames(harness.socket(), channel).at(-1)
|
|
105
|
+
simulateServerMessage(harness.socket(), {
|
|
106
|
+
type: "system",
|
|
107
|
+
status: "error",
|
|
108
|
+
message: "role anon cannot read public.note",
|
|
109
|
+
channel,
|
|
110
|
+
ref: newest?.["ref"],
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A refused rejoin registered nothing, so the join it was to replace still stands on the server and
|
|
116
|
+
* still serves broadcast and presence. Every handle on the name was told CHANNEL_ERROR and stayed
|
|
117
|
+
* there, and every member was said to have left (0.9.2 round 4, S-1).
|
|
118
|
+
*/
|
|
119
|
+
describe("a rows rejoin the server refuses", () => {
|
|
120
|
+
it("fails the handle whose rows it asked for, and leaves the broadcast handle SUBSCRIBED", async () => {
|
|
121
|
+
const first = await joinedForBroadcast("room:x")
|
|
122
|
+
const statuses: Array<[ChannelStatus, string | undefined]> = []
|
|
123
|
+
harness.realtime
|
|
124
|
+
.channel("room:x")
|
|
125
|
+
.on("postgres_changes", { event: "INSERT", table: "note" }, () => {})
|
|
126
|
+
.subscribe((s, err) => statuses.push([s, err?.message]))
|
|
127
|
+
|
|
128
|
+
refuseNewestJoin("room:x")
|
|
129
|
+
expect(statuses).toEqual([["CHANNEL_ERROR", "role anon cannot read public.note"]])
|
|
130
|
+
expect(first.statuses).toEqual(["SUBSCRIBED"])
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it("keeps who is present, as the standing join keeps reporting it", async () => {
|
|
134
|
+
const seen: Array<{ joins: string[]; leaves: string[] }> = []
|
|
135
|
+
harness.realtime
|
|
136
|
+
.channel("room:x")
|
|
137
|
+
.onPresence(({ joins, leaves }) => seen.push({ joins: joins.map((m) => m.user_id), leaves: leaves.map((m) => m.user_id) }))
|
|
138
|
+
.subscribe()
|
|
139
|
+
await harness.settle()
|
|
140
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
141
|
+
const presence = (joins: string[], leaves: string[]): void =>
|
|
142
|
+
simulateServerMessage(harness.socket(), {
|
|
143
|
+
type: "presence",
|
|
144
|
+
channel: "room:x",
|
|
145
|
+
joins: joins.map((user_id) => ({ user_id })),
|
|
146
|
+
leaves: leaves.map((user_id) => ({ user_id })),
|
|
147
|
+
})
|
|
148
|
+
presence(["u1", "u2"], [])
|
|
149
|
+
|
|
150
|
+
harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
|
|
151
|
+
// While the rejoin waits, the join still standing reports a leave.
|
|
152
|
+
presence([], ["u2"])
|
|
153
|
+
refuseNewestJoin("room:x")
|
|
154
|
+
expect(seen).toEqual([
|
|
155
|
+
{ joins: ["u1", "u2"], leaves: [] },
|
|
156
|
+
{ joins: [], leaves: ["u2"] },
|
|
157
|
+
])
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
it("is told who is present again once a rejoin is taken, after its old members leave", async () => {
|
|
161
|
+
const seen: Array<{ joins: string[]; leaves: string[] }> = []
|
|
162
|
+
harness.realtime
|
|
163
|
+
.channel("room:x")
|
|
164
|
+
.onPresence(({ joins, leaves }) => seen.push({ joins: joins.map((m) => m.user_id), leaves: leaves.map((m) => m.user_id) }))
|
|
165
|
+
.subscribe()
|
|
166
|
+
await harness.settle()
|
|
167
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
168
|
+
simulateServerMessage(harness.socket(), { type: "presence", channel: "room:x", joins: [{ user_id: "u1" }], leaves: [] })
|
|
169
|
+
|
|
170
|
+
harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
|
|
171
|
+
expect(seen).toHaveLength(1)
|
|
172
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
173
|
+
// The server follows the reply with who is present, so a page counting joins minus leaves
|
|
174
|
+
// counts u1 once.
|
|
175
|
+
simulateServerMessage(harness.socket(), { type: "presence", channel: "room:x", joins: [{ user_id: "u1" }], leaves: [] })
|
|
176
|
+
expect(seen).toEqual([
|
|
177
|
+
{ joins: ["u1"], leaves: [] },
|
|
178
|
+
{ joins: [], leaves: ["u1"] },
|
|
179
|
+
{ joins: ["u1"], leaves: [] },
|
|
180
|
+
])
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
it("sends no further join once the refused handle leaves", async () => {
|
|
184
|
+
const first = await joinedForBroadcast("room:x")
|
|
185
|
+
const rows = harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
|
|
186
|
+
refuseNewestJoin("room:x")
|
|
187
|
+
rows.unsubscribe()
|
|
188
|
+
expect(subscribeFrames(harness.socket(), "room:x")).toHaveLength(2)
|
|
189
|
+
expect(first.statuses.at(-1)).toBe("SUBSCRIBED")
|
|
190
|
+
})
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
describe("a row listener added to a channel whose join already delivers rows", () => {
|
|
194
|
+
it("sends no second join", async () => {
|
|
195
|
+
harness.realtime.channel("room:x").on("postgres_changes", { event: "INSERT", table: "note" }, () => {}).subscribe()
|
|
196
|
+
await harness.settle()
|
|
197
|
+
ackNewestJoin(harness.socket(), "room:x")
|
|
198
|
+
|
|
199
|
+
const statuses: ChannelStatus[] = []
|
|
200
|
+
harness.realtime.channel("room:x").onBroadcast("ping", () => {}).on("postgres_changes", { event: "*", table: "note" }, () => {}).subscribe((s) => statuses.push(s))
|
|
201
|
+
|
|
202
|
+
expect(subscribeFrames(harness.socket(), "room:x")).toHaveLength(1)
|
|
203
|
+
expect(statuses).toEqual(["SUBSCRIBED"])
|
|
204
|
+
})
|
|
205
|
+
})
|