@supatype/client 0.7.0 → 0.9.0
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 +69 -56
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +28 -0
- package/bin/supatype-prepare.js +68 -0
- package/dist/auth.d.ts +17 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +41 -10
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +1 -1
- package/dist/bindings.d.ts.map +1 -1
- package/dist/graphql-transport.d.ts +2 -2
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +16 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +33 -21
- package/dist/index.js.map +1 -1
- package/dist/mutation-request.d.ts +17 -4
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +16 -14
- package/dist/mutation-request.js.map +1 -1
- package/dist/query.d.ts +40 -16
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +81 -21
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +38 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +201 -82
- package/dist/realtime.js.map +1 -1
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +10 -3
- package/dist/storage.js.map +1 -1
- package/dist/types.d.ts +14 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +5 -2
- package/src/auth.ts +43 -10
- package/src/bindings.ts +1 -1
- package/src/graphql-transport.ts +2 -2
- package/src/index.ts +40 -26
- package/src/mutation-request.ts +32 -18
- package/src/query.ts +102 -37
- package/src/realtime.ts +222 -82
- package/src/storage.ts +11 -3
- package/src/types.ts +14 -0
- package/tests/auth.test.ts +65 -0
- package/tests/data-plane-auth.test.ts +1 -6
- package/tests/draft-insert.test.ts +9 -9
- package/tests/draft-update.test.ts +5 -5
- package/tests/helpers/socket-swap.ts +3 -0
- package/tests/minimal-writes.test.ts +118 -0
- package/tests/postgrest-error-codes.test.ts +1 -1
- package/tests/query.test.ts +3 -3
- package/tests/realtime-ack-ref.test.ts +112 -0
- package/tests/realtime-session-auth.test.ts +1 -4
- package/tests/realtime-shared-channel.test.ts +209 -0
- package/tests/rpc-resend.test.ts +33 -8
- package/tests/server-bodies.test.ts +48 -0
- package/tests/storage-quota-integration.test.ts +4 -7
- package/tests/storage-upload-limit-integration.test.ts +5 -9
- package/tests/storage-url-encoding.test.ts +52 -0
- package/tests/supatype-prepare.test.ts +139 -0
- package/tests/support/blob.ts +10 -0
- package/tests/support/jwt.ts +4 -0
- package/tests/table-subscribe.test.ts +28 -1
- package/tests/unauthorized-resend.test.ts +107 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -137,3 +137,51 @@ describe("a refusal worded under `error`", () => {
|
|
|
137
137
|
expect(error?.message).toBe(REFUSED)
|
|
138
138
|
})
|
|
139
139
|
})
|
|
140
|
+
|
|
141
|
+
describe("a functions worker refusal", () => {
|
|
142
|
+
// The worker answers its own failures as `{ error: <code>, message }`; the code is under `error`.
|
|
143
|
+
const client = (): ReturnType<typeof createClient> =>
|
|
144
|
+
createClient({ url: "http://api.test", anonKey: "anon", auth: { persistSession: false } })
|
|
145
|
+
|
|
146
|
+
it("carries the worker's code for a function that does not exist", async () => {
|
|
147
|
+
vi.stubGlobal("fetch", fetchReturning({ error: "not_found", message: 'Function "nope" not found' }, 404))
|
|
148
|
+
const { error } = await client().functions.invoke("nope")
|
|
149
|
+
expect(error).toMatchObject({ code: "not_found", message: 'Function "nope" not found', status: 404 })
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
it("carries the worker's code for a handler that threw", async () => {
|
|
153
|
+
vi.stubGlobal("fetch", fetchReturning({ error: "function_error", message: "boom" }, 500))
|
|
154
|
+
const { error } = await client().functions.invoke("fn")
|
|
155
|
+
expect(error).toMatchObject({ code: "function_error", message: "boom", status: 500 })
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
it("keeps the worker's code when the thrown error had no message", async () => {
|
|
159
|
+
vi.stubGlobal("fetch", fetchReturning({ error: "function_error", message: "" }, 500))
|
|
160
|
+
const { error } = await client().functions.invoke("fn")
|
|
161
|
+
expect(error).toMatchObject({ code: "function_error", status: 500 })
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
it("prefers a handler's own `code` over `error`", async () => {
|
|
165
|
+
vi.stubGlobal("fetch", fetchReturning({ code: "out_of_stock", error: "conflict", message: "gone" }, 409))
|
|
166
|
+
const { error } = await client().functions.invoke("fn")
|
|
167
|
+
expect(error?.code).toBe("out_of_stock")
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
it("reads a handler's lone `error` string as the message, not the code", async () => {
|
|
171
|
+
vi.stubGlobal("fetch", fetchReturning({ error: "Email already taken" }, 400))
|
|
172
|
+
const { error } = await client().functions.invoke("fn")
|
|
173
|
+
expect(error).toEqual({ message: "Email already taken", status: 400 })
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
it("reads the message the way every other refusal is read, `msg` and an empty `message` included", async () => {
|
|
177
|
+
vi.stubGlobal("fetch", fetchReturning({ message: "", msg: "Rate limited" }, 429))
|
|
178
|
+
const { error } = await client().functions.invoke("fn")
|
|
179
|
+
expect(error).toEqual({ message: "Rate limited", status: 429 })
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
it("leaves the code unset when `error` is not a string", async () => {
|
|
183
|
+
vi.stubGlobal("fetch", fetchReturning({ error: { detail: "x" }, message: "bad" }, 400))
|
|
184
|
+
const { error } = await client().functions.invoke("fn")
|
|
185
|
+
expect(error).not.toHaveProperty("code")
|
|
186
|
+
})
|
|
187
|
+
})
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
8
8
|
import { StorageClient } from "../src/storage.js"
|
|
9
9
|
import { UNOWNED } from "./support/storage-object.js"
|
|
10
|
+
import { createMockBlob } from "./support/blob.js"
|
|
10
11
|
|
|
11
12
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
13
|
|
|
@@ -18,10 +19,6 @@ function freshClient(): StorageClient {
|
|
|
18
19
|
return new StorageClient(STORAGE_URL, () => Promise.resolve(HEADERS))
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
function createMockBlob(sizeBytes: number): Blob {
|
|
22
|
-
return new Blob([new Uint8Array(sizeBytes)])
|
|
23
|
-
}
|
|
24
|
-
|
|
25
22
|
function mockFetchResponse(
|
|
26
23
|
status: number,
|
|
27
24
|
body: unknown,
|
|
@@ -49,7 +46,7 @@ describe("Task 93: Storage quota integration", () => {
|
|
|
49
46
|
}, false))
|
|
50
47
|
|
|
51
48
|
const client = freshClient()
|
|
52
|
-
const blob = createMockBlob(
|
|
49
|
+
const blob = createMockBlob(1024)
|
|
53
50
|
const { data, error } = await client.from("uploads").upload("file.dat", blob)
|
|
54
51
|
|
|
55
52
|
expect(data).toBeNull()
|
|
@@ -115,10 +112,10 @@ describe("Task 93: Storage quota integration", () => {
|
|
|
115
112
|
|
|
116
113
|
const client = freshClient()
|
|
117
114
|
|
|
118
|
-
const first = await client.from("bucket").upload("first.txt", createMockBlob(
|
|
115
|
+
const first = await client.from("bucket").upload("first.txt", createMockBlob(1024))
|
|
119
116
|
expect(first.error).toBeNull()
|
|
120
117
|
|
|
121
|
-
const second = await client.from("bucket").upload("second.txt", createMockBlob(
|
|
118
|
+
const second = await client.from("bucket").upload("second.txt", createMockBlob(1024))
|
|
122
119
|
expect(second.data).toBeNull()
|
|
123
120
|
expect(second.error!.status).toBe(507)
|
|
124
121
|
})
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
8
8
|
import { StorageClient } from "../src/storage.js"
|
|
9
9
|
import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
|
|
10
|
+
import { createMockBlob } from "./support/blob.js"
|
|
10
11
|
|
|
11
12
|
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
|
12
13
|
|
|
@@ -18,11 +19,6 @@ function freshClient(): StorageClient {
|
|
|
18
19
|
return new StorageClient(STORAGE_URL, () => Promise.resolve(HEADERS))
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
function createMockBlob(sizeBytes: number): Blob {
|
|
22
|
-
const data = new Uint8Array(sizeBytes)
|
|
23
|
-
return new Blob([data])
|
|
24
|
-
}
|
|
25
|
-
|
|
26
22
|
function mockFetchResponse(status: number, body: unknown): FetchMock {
|
|
27
23
|
return fetchReturning(body, status)
|
|
28
24
|
}
|
|
@@ -49,7 +45,7 @@ describe("Task 92: File upload size limit integration", () => {
|
|
|
49
45
|
vi.stubGlobal("fetch", mockFetchResponse(200, { Key: "docs/file.pdf" }))
|
|
50
46
|
|
|
51
47
|
const client = freshClient()
|
|
52
|
-
const blob = createMockBlob(
|
|
48
|
+
const blob = createMockBlob(1024) // the mocked server's answer stands for a file at the limit
|
|
53
49
|
const { data, error } = await client.from("docs").upload("file.pdf", blob, {
|
|
54
50
|
contentType: "application/pdf",
|
|
55
51
|
})
|
|
@@ -68,7 +64,7 @@ describe("Task 92: File upload size limit integration", () => {
|
|
|
68
64
|
}))
|
|
69
65
|
|
|
70
66
|
const client = freshClient()
|
|
71
|
-
const blob = createMockBlob(
|
|
67
|
+
const blob = createMockBlob(1024) // the mocked 413 stands for a file over the limit
|
|
72
68
|
const { data, error } = await client.from("uploads").upload("large-video.mp4", blob)
|
|
73
69
|
|
|
74
70
|
expect(data).toBeNull()
|
|
@@ -83,7 +79,7 @@ describe("Task 92: File upload size limit integration", () => {
|
|
|
83
79
|
}))
|
|
84
80
|
|
|
85
81
|
const client = freshClient()
|
|
86
|
-
const { error } = await client.from("uploads").upload("huge.zip", createMockBlob(
|
|
82
|
+
const { error } = await client.from("uploads").upload("huge.zip", createMockBlob(1024))
|
|
87
83
|
|
|
88
84
|
expect(error!.message).toContain("50MB")
|
|
89
85
|
})
|
|
@@ -94,7 +90,7 @@ describe("Task 92: File upload size limit integration", () => {
|
|
|
94
90
|
}))
|
|
95
91
|
|
|
96
92
|
const client = freshClient()
|
|
97
|
-
const blob = createMockBlob(
|
|
93
|
+
const blob = createMockBlob(1024) // the mocked 413 stands for one byte over
|
|
98
94
|
const { data, error } = await client.from("uploads").upload("slightly-too-big.dat", blob)
|
|
99
95
|
|
|
100
96
|
expect(data).toBeNull()
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An object path goes into a URL one encoded segment at a time.
|
|
3
|
+
*
|
|
4
|
+
* The client interpolated the path as given, so a name holding `?` or `#` cut the URL short: the
|
|
5
|
+
* server saw `a b/c` and a query or fragment it never asked for, and answered for another object
|
|
6
|
+
* or none. The `/` between folders stays a `/`, since the server matches the path on it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { beforeEach, describe, expect, it, vi } from "vitest"
|
|
10
|
+
import { StorageClient } from "../src/storage.js"
|
|
11
|
+
import { fetchCall, fetchReturning } from "./support/fetch-mock.js"
|
|
12
|
+
|
|
13
|
+
const STORAGE_URL = "http://localhost:18473/storage/v1"
|
|
14
|
+
const NAME = "a b/c?d#e.png"
|
|
15
|
+
const ENCODED = "a%20b/c%3Fd%23e.png"
|
|
16
|
+
|
|
17
|
+
function bucket() {
|
|
18
|
+
return new StorageClient(STORAGE_URL, () => Promise.resolve({})).from("docs")
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
vi.restoreAllMocks()
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
describe("object paths in storage URLs", () => {
|
|
26
|
+
it("are encoded per segment in a public URL", () => {
|
|
27
|
+
expect(bucket().getPublicUrl(NAME).data.publicUrl).toBe(`${STORAGE_URL}/object/public/docs/${ENCODED}`)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it("are encoded per segment when asking for a signed URL", async () => {
|
|
31
|
+
const fetch = fetchReturning({ signedURL: `/object/sign/docs/${ENCODED}?token=t` })
|
|
32
|
+
vi.stubGlobal("fetch", fetch)
|
|
33
|
+
await bucket().createSignedUrl(NAME, 60)
|
|
34
|
+
expect(fetchCall(fetch).url).toBe(`${STORAGE_URL}/object/sign/docs/${ENCODED}`)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it("are encoded per segment on upload and download", async () => {
|
|
38
|
+
const fetch = fetchReturning({})
|
|
39
|
+
vi.stubGlobal("fetch", fetch)
|
|
40
|
+
await bucket().upload(NAME, new ArrayBuffer(1))
|
|
41
|
+
await bucket().download(NAME)
|
|
42
|
+
expect(fetchCall(fetch, 0).url).toBe(`${STORAGE_URL}/object/docs/${ENCODED}`)
|
|
43
|
+
expect(fetchCall(fetch, 1).url).toBe(`${STORAGE_URL}/object/authenticated/docs/${ENCODED}`)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it("read back as the name they were built from", () => {
|
|
47
|
+
const url = new URL(bucket().getPublicUrl(NAME).data.publicUrl)
|
|
48
|
+
expect(url.search).toBe("")
|
|
49
|
+
expect(url.hash).toBe("")
|
|
50
|
+
expect(decodeURIComponent(url.pathname)).toBe(`/storage/v1/object/public/docs/${NAME}`)
|
|
51
|
+
})
|
|
52
|
+
})
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from "vitest"
|
|
2
|
+
import { spawnSync } from "node:child_process"
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
|
4
|
+
import { tmpdir } from "node:os"
|
|
5
|
+
import { join } from "node:path"
|
|
6
|
+
|
|
7
|
+
const BIN = join(import.meta.dirname, "..", "bin", "supatype-prepare.js")
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `supatype-prepare`, a project's `prepare`, run in the project as npm runs it. A production
|
|
11
|
+
* install leaves out development dependencies, the CLI with them, and still runs `prepare`, where
|
|
12
|
+
* a bare `supatype generate` failed the install with `supatype: not found`.
|
|
13
|
+
*/
|
|
14
|
+
describe("supatype-prepare", () => {
|
|
15
|
+
const dirs: string[] = []
|
|
16
|
+
afterEach(() => {
|
|
17
|
+
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
function project(): string {
|
|
21
|
+
const dir = mkdtempSync(join(tmpdir(), "supatype-prepare-"))
|
|
22
|
+
dirs.push(dir)
|
|
23
|
+
writeFileSync(join(dir, "package.json"), '{ "type": "module" }\n')
|
|
24
|
+
return dir
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A workspace member under `root`, with no node_modules of its own. */
|
|
28
|
+
function member(root: string): string {
|
|
29
|
+
const pkg = join(root, "packages", "app")
|
|
30
|
+
mkdirSync(pkg, { recursive: true })
|
|
31
|
+
writeFileSync(join(pkg, "package.json"), '{ "type": "module" }\n')
|
|
32
|
+
return pkg
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A stand-in CLI whose `generate` records that it ran, and exits with `status`. Its `exports` do
|
|
37
|
+
* not name its package.json, as no release's do: it is found all the same.
|
|
38
|
+
*/
|
|
39
|
+
function installCli(dir: string, status: number, folder = "node_modules", bin: string | object = { supatype: "./bin/supatype.js" }): void {
|
|
40
|
+
const cli = join(dir, folder, "@supatype", "cli")
|
|
41
|
+
mkdirSync(join(cli, "bin"), { recursive: true })
|
|
42
|
+
const manifest = { name: "@supatype/cli", bin, exports: { ".": "./index.js" } }
|
|
43
|
+
writeFileSync(join(cli, "package.json"), JSON.stringify(manifest))
|
|
44
|
+
const script = `require("node:fs").writeFileSync("generated", process.argv[2]); process.exit(${status})`
|
|
45
|
+
writeFileSync(join(cli, "bin", "supatype.js"), `${script}\n`)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const prepare = (cwd: string, env: NodeJS.ProcessEnv = {}) =>
|
|
49
|
+
spawnSync(process.execPath, [BIN], { cwd, encoding: "utf8", env: { ...process.env, ...env } })
|
|
50
|
+
|
|
51
|
+
const generated = (dir: string): boolean => existsSync(join(dir, "generated"))
|
|
52
|
+
|
|
53
|
+
it("succeeds, and generates nothing, where the CLI is not installed", () => {
|
|
54
|
+
const dir = project()
|
|
55
|
+
const result = prepare(dir)
|
|
56
|
+
expect(result.status, result.stderr).toBe(0)
|
|
57
|
+
expect(generated(dir)).toBe(false)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
// pnpm's bin shims point NODE_PATH at pnpm's store, and Node's global folders include
|
|
61
|
+
// ~/.node_modules: neither is this project's, and a production install that left the CLI out
|
|
62
|
+
// must not run some other copy.
|
|
63
|
+
it.each([
|
|
64
|
+
["on NODE_PATH", "node_modules", (dir: string) => ({ NODE_PATH: join(dir, "node_modules") })],
|
|
65
|
+
["in the home folder's .node_modules", ".node_modules", (dir: string) => ({ HOME: dir, USERPROFILE: dir })],
|
|
66
|
+
] as const)("ignores a CLI %s", (_, folder, env) => {
|
|
67
|
+
const elsewhere = project()
|
|
68
|
+
installCli(elsewhere, 0, folder)
|
|
69
|
+
const dir = project()
|
|
70
|
+
const result = prepare(dir, env(elsewhere))
|
|
71
|
+
expect(result.status, result.stderr).toBe(0)
|
|
72
|
+
expect(generated(dir)).toBe(false)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
// npm reads `bin` given as a string as the package's one command.
|
|
76
|
+
it.each([
|
|
77
|
+
["named", { supatype: "./bin/supatype.js" }],
|
|
78
|
+
["given as a string", "./bin/supatype.js"],
|
|
79
|
+
] as const)("runs supatype generate where the CLI is installed, its bin %s", (_, bin) => {
|
|
80
|
+
const dir = project()
|
|
81
|
+
installCli(dir, 0, "node_modules", bin)
|
|
82
|
+
const result = prepare(dir)
|
|
83
|
+
expect(result.status, result.stderr).toBe(0)
|
|
84
|
+
expect(generated(dir)).toBe(true)
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
// A workspace hoists the CLI to the root's node_modules, above the package that runs prepare.
|
|
88
|
+
it("finds a CLI hoisted into a parent directory", () => {
|
|
89
|
+
const root = project()
|
|
90
|
+
installCli(root, 0)
|
|
91
|
+
const pkg = member(root)
|
|
92
|
+
const result = prepare(pkg)
|
|
93
|
+
expect(result.status, result.stderr).toBe(0)
|
|
94
|
+
expect(generated(pkg)).toBe(true)
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
// A workspace member can pin a CLI of its own beside the one the root hoists.
|
|
98
|
+
it("runs the nearest CLI", () => {
|
|
99
|
+
const root = project()
|
|
100
|
+
installCli(root, 4)
|
|
101
|
+
const pkg = member(root)
|
|
102
|
+
installCli(pkg, 0)
|
|
103
|
+
const result = prepare(pkg)
|
|
104
|
+
expect(result.status, result.stderr).toBe(0)
|
|
105
|
+
expect(generated(pkg)).toBe(true)
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
// A node_modules above the project that is a file, or one the user may not read, holds no CLI.
|
|
109
|
+
// Node's own lookup passes over it. Only Linux and macOS report a file there as ENOTDIR.
|
|
110
|
+
it("passes over a node_modules it cannot look inside", () => {
|
|
111
|
+
const root = project()
|
|
112
|
+
writeFileSync(join(root, "node_modules"), "")
|
|
113
|
+
const pkg = member(root)
|
|
114
|
+
const result = prepare(pkg)
|
|
115
|
+
expect(result.status, result.stderr).toBe(0)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
// A link into a pruned pnpm store, an empty folder, a package.json naming no command: skipping
|
|
119
|
+
// any of them would pass the install and fail the build later, on files never generated.
|
|
120
|
+
it.each([
|
|
121
|
+
["a link to nothing", (cli: string) => symlinkSync(join(cli, "..", "gone"), cli, "junction")],
|
|
122
|
+
["an empty folder", (cli: string) => mkdirSync(cli)],
|
|
123
|
+
["a CLI naming no supatype command", (cli: string) => installCli(join(cli, "..", "..", ".."), 0, "node_modules", { other: "./x.js" })],
|
|
124
|
+
] as const)("fails the install when the CLI folder is %s", (_, make) => {
|
|
125
|
+
const dir = project()
|
|
126
|
+
const cli = join(dir, "node_modules", "@supatype", "cli")
|
|
127
|
+
mkdirSync(join(cli, ".."), { recursive: true })
|
|
128
|
+
make(cli)
|
|
129
|
+
const result = prepare(dir)
|
|
130
|
+
expect(result.status).toBe(1)
|
|
131
|
+
expect(result.stderr).toContain("cannot read the Supatype CLI")
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it("fails the install when generate fails", () => {
|
|
135
|
+
const dir = project()
|
|
136
|
+
installCli(dir, 3)
|
|
137
|
+
expect(prepare(dir).status).toBe(3)
|
|
138
|
+
})
|
|
139
|
+
})
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A file body for upload tests. The client never checks a file's size: the storage server
|
|
3
|
+
* decides limits and quotas, and these suites mock its answer. So the tests upload small blobs,
|
|
4
|
+
* because a real 500 MB one costs real memory and timed out on CI runners.
|
|
5
|
+
*
|
|
6
|
+
* Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
|
|
7
|
+
*/
|
|
8
|
+
export function createMockBlob(sizeBytes: number): Blob {
|
|
9
|
+
return new Blob([new Uint8Array(sizeBytes)])
|
|
10
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** An unsigned JWT carrying `payload`: the client only ever decodes the payload, never checks the signature. */
|
|
2
|
+
export function fakeJwt(payload: Record<string, unknown>): string {
|
|
3
|
+
return `${btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${btoa(JSON.stringify(payload))}.sig`
|
|
4
|
+
}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
|
|
14
14
|
import { createClient } from "../src/index.js"
|
|
15
|
-
import type { RealtimePayload } from "../src/realtime.js"
|
|
15
|
+
import type { ChannelStatus, RealtimePayload } from "../src/realtime.js"
|
|
16
16
|
import {
|
|
17
17
|
channelOf,
|
|
18
18
|
createMockWebSocketClass,
|
|
@@ -288,3 +288,30 @@ describe("review fixes", () => {
|
|
|
288
288
|
expect(comments).toEqual([])
|
|
289
289
|
})
|
|
290
290
|
})
|
|
291
|
+
|
|
292
|
+
describe("a refusal that names its channel", () => {
|
|
293
|
+
it("fails only that channel, leaving the others on the socket subscribed", async () => {
|
|
294
|
+
// A refused join used to reach every channel on the socket: one bad filter put each healthy,
|
|
295
|
+
// subscribed channel beside it into CHANNEL_ERROR.
|
|
296
|
+
const client = newClient()
|
|
297
|
+
const healthy: ChannelStatus[] = []
|
|
298
|
+
const refused: ChannelStatus[] = []
|
|
299
|
+
client.realtime.channel("posts").on("postgres_changes", { event: "*", table: "posts" }, () => {}).subscribe((s) => healthy.push(s))
|
|
300
|
+
const bad = client.realtime
|
|
301
|
+
.channel("orders")
|
|
302
|
+
.on("postgres_changes", { event: "*", table: "orders", filter: "status=like.open" }, () => {})
|
|
303
|
+
bad.subscribe((s) => refused.push(s))
|
|
304
|
+
await settle()
|
|
305
|
+
const ws = onlySocket()
|
|
306
|
+
|
|
307
|
+
simulateServerMessage(ws, ack("posts"))
|
|
308
|
+
simulateServerMessage(ws, { type: "system", status: "error", message: "invalid filter status=like.open", channel: "orders" })
|
|
309
|
+
|
|
310
|
+
expect(healthy).toEqual(["SUBSCRIBED"])
|
|
311
|
+
expect(refused).toEqual(["CHANNEL_ERROR"])
|
|
312
|
+
// Refused, so it joined nothing and may join again on this socket.
|
|
313
|
+
bad.subscribe()
|
|
314
|
+
await settle()
|
|
315
|
+
expect(framesOfType("subscribe").filter((frame) => frame["channel"] === "orders")).toHaveLength(2)
|
|
316
|
+
})
|
|
317
|
+
})
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
2
|
+
import { createClient, type AnyDatabase, type Session } from "../src/index.js"
|
|
3
|
+
import { fetchCalls, header, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
|
|
4
|
+
import { fakeJwt } from "./support/jwt.js"
|
|
5
|
+
|
|
6
|
+
// A 401 is resent only when the server said the token was expired or invalid, a session was there to
|
|
7
|
+
// refresh, and the refresh produced a different token. Anything else (a row rule refusing an anon
|
|
8
|
+
// write, above all) goes out once: sending it again only repeats the refusal, and a write twice.
|
|
9
|
+
|
|
10
|
+
const BASE = "http://localhost:18473"
|
|
11
|
+
const ANON_KEY = "anon-key"
|
|
12
|
+
const NOW = Math.floor(Date.now() / 1000)
|
|
13
|
+
|
|
14
|
+
const STALE = fakeJwt({ role: "authenticated", sub: "user-1", exp: NOW + 3600, n: 1 })
|
|
15
|
+
const FRESH = fakeJwt({ role: "authenticated", sub: "user-1", exp: NOW + 7200, n: 2 })
|
|
16
|
+
|
|
17
|
+
/** A session the local clock still calls valid, which the server has nonetheless refused. */
|
|
18
|
+
const SESSION: Session = {
|
|
19
|
+
accessToken: STALE,
|
|
20
|
+
tokenType: "bearer",
|
|
21
|
+
expiresIn: 3600,
|
|
22
|
+
expiresAt: NOW + 3600,
|
|
23
|
+
refreshToken: "rt-1",
|
|
24
|
+
user: { id: "user-1", appMetadata: {}, userMetadata: {}, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" },
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const RAW_USER = { id: "user-1", app_metadata: {}, user_metadata: {}, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" }
|
|
28
|
+
|
|
29
|
+
/** PostgREST refusing an anon write a row rule does not allow. */
|
|
30
|
+
const RLS_REFUSAL = { code: "42501", details: null, hint: null, message: 'new row violates row-level security policy for table "orders"' }
|
|
31
|
+
/** PostgREST 14 refusing an expired token. */
|
|
32
|
+
const EXPIRED = { code: "PGRST303", details: null, hint: null, message: "JWT expired" }
|
|
33
|
+
|
|
34
|
+
/** Answers the table with `refusal` until a request carries FRESH, and the refresh with `refreshed`. */
|
|
35
|
+
function server(refusal: Record<string, unknown>, refreshed: string): FetchMock {
|
|
36
|
+
return mockFetch((input, init) => {
|
|
37
|
+
if (requestUrl(input).includes("/auth/v1/token")) {
|
|
38
|
+
return Promise.resolve(
|
|
39
|
+
jsonResponse({ access_token: refreshed, refresh_token: "rt-2", token_type: "bearer", expires_in: 3600, user: RAW_USER }),
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
const fresh = header(init ?? {}, "Authorization") === `Bearer ${FRESH}`
|
|
43
|
+
return Promise.resolve(fresh ? jsonResponse(null, 201) : jsonResponse(refusal, 401))
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function serve(fetch: FetchMock): FetchMock {
|
|
48
|
+
vi.stubGlobal("fetch", fetch)
|
|
49
|
+
return fetch
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const tableCalls = (fetch: FetchMock) => fetchCalls(fetch).filter(({ url }) => url.includes("/rest/v1/orders"))
|
|
53
|
+
const refreshCalls = (fetch: FetchMock) => fetchCalls(fetch).filter(({ url }) => url.includes("/auth/v1/token"))
|
|
54
|
+
|
|
55
|
+
function signedIn() {
|
|
56
|
+
return createClient<AnyDatabase>({
|
|
57
|
+
url: BASE,
|
|
58
|
+
anonKey: ANON_KEY,
|
|
59
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
60
|
+
initialSession: SESSION,
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
describe("the resend after a 401", () => {
|
|
65
|
+
afterEach(() => vi.unstubAllGlobals())
|
|
66
|
+
|
|
67
|
+
it("is not made for an anon write a row rule refused", async () => {
|
|
68
|
+
const fetch = serve(server(RLS_REFUSAL, FRESH))
|
|
69
|
+
const client = createClient<AnyDatabase>({ url: BASE, anonKey: ANON_KEY, auth: { persistSession: false } })
|
|
70
|
+
const { error } = await client.from("orders").insert({ item: "latte" })
|
|
71
|
+
expect(error).toMatchObject({ code: "42501", status: 401 })
|
|
72
|
+
expect(tableCalls(fetch)).toHaveLength(1)
|
|
73
|
+
expect(refreshCalls(fetch)).toHaveLength(0)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it("is not made for a signed-in write a row rule refused, and nothing is refreshed", async () => {
|
|
77
|
+
const fetch = serve(server(RLS_REFUSAL, FRESH))
|
|
78
|
+
const { error } = await signedIn().from("orders").insert({ item: "latte" })
|
|
79
|
+
expect(error).toMatchObject({ code: "42501" })
|
|
80
|
+
expect(tableCalls(fetch)).toHaveLength(1)
|
|
81
|
+
expect(refreshCalls(fetch)).toHaveLength(0)
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it("refreshes an expired token the local clock calls valid, and sends again with the new one", async () => {
|
|
85
|
+
const fetch = serve(server(EXPIRED, FRESH))
|
|
86
|
+
const { error } = await signedIn().from("orders").insert({ item: "latte" })
|
|
87
|
+
expect(error).toBeNull()
|
|
88
|
+
expect(refreshCalls(fetch)).toHaveLength(1)
|
|
89
|
+
expect(tableCalls(fetch).map(({ init }) => header(init, "Authorization"))).toEqual([`Bearer ${STALE}`, `Bearer ${FRESH}`])
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it("is not made when the refresh hands back the token the server refused", async () => {
|
|
93
|
+
const fetch = serve(server(EXPIRED, STALE))
|
|
94
|
+
const { error } = await signedIn().from("orders").insert({ item: "latte" })
|
|
95
|
+
expect(error).toMatchObject({ code: "PGRST303" })
|
|
96
|
+
expect(refreshCalls(fetch)).toHaveLength(1)
|
|
97
|
+
expect(tableCalls(fetch)).toHaveLength(1)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it("is not made for an anon caller whose token the server called expired, there being no session", async () => {
|
|
101
|
+
const fetch = serve(server(EXPIRED, FRESH))
|
|
102
|
+
const client = createClient<AnyDatabase>({ url: BASE, anonKey: ANON_KEY, auth: { persistSession: false } })
|
|
103
|
+
await client.from("orders").select("id")
|
|
104
|
+
expect(tableCalls(fetch)).toHaveLength(1)
|
|
105
|
+
expect(refreshCalls(fetch)).toHaveLength(0)
|
|
106
|
+
})
|
|
107
|
+
})
|