@supatype/client 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +73 -69
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +110 -0
- package/bin/supatype-prepare.js +68 -0
- package/dist/auth.d.ts +50 -6
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +132 -40
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +4 -1
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +2 -0
- package/dist/bindings.js.map +1 -1
- package/dist/error-codes-doc.d.ts +1 -1
- package/dist/error-codes-doc.d.ts.map +1 -1
- package/dist/error-codes-doc.js +7 -0
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +81 -21
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +133 -46
- package/dist/errors.js.map +1 -1
- package/dist/graphql-transport.d.ts +10 -3
- package/dist/graphql-transport.d.ts.map +1 -1
- package/dist/graphql-transport.js +5 -5
- package/dist/graphql-transport.js.map +1 -1
- package/dist/index.d.ts +23 -16
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +66 -48
- package/dist/index.js.map +1 -1
- package/dist/latest-rows.d.ts +29 -0
- package/dist/latest-rows.d.ts.map +1 -0
- package/dist/latest-rows.js +51 -0
- package/dist/latest-rows.js.map +1 -0
- package/dist/mutation-request.d.ts +19 -5
- package/dist/mutation-request.d.ts.map +1 -1
- package/dist/mutation-request.js +18 -15
- package/dist/mutation-request.js.map +1 -1
- package/dist/page-env-script.d.ts +12 -0
- package/dist/page-env-script.d.ts.map +1 -0
- package/dist/page-env-script.js +30 -0
- package/dist/page-env-script.js.map +1 -0
- package/dist/preview.d.ts +2 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +7 -3
- package/dist/preview.js.map +1 -1
- package/dist/query.d.ts +49 -19
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +102 -33
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +5 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +13 -6
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +59 -0
- package/dist/runtime-env.d.ts.map +1 -0
- package/dist/runtime-env.js +167 -0
- package/dist/runtime-env.js.map +1 -0
- package/dist/setup-fault.d.ts +13 -0
- package/dist/setup-fault.d.ts.map +1 -0
- package/dist/setup-fault.js +17 -0
- package/dist/setup-fault.js.map +1 -0
- package/dist/storage.d.ts +10 -5
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +22 -13
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +1 -1
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +3 -2
- package/dist/table-subscription.js.map +1 -1
- package/dist/thrown-error.d.ts +16 -0
- package/dist/thrown-error.d.ts.map +1 -0
- package/dist/thrown-error.js +31 -0
- package/dist/thrown-error.js.map +1 -0
- package/dist/types.d.ts +59 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth.ts +135 -44
- package/src/bindings.ts +4 -1
- package/src/error-codes-doc.ts +9 -1
- package/src/errors.ts +155 -57
- package/src/graphql-transport.ts +7 -8
- package/src/index.ts +82 -60
- package/src/latest-rows.ts +78 -0
- package/src/mutation-request.ts +34 -19
- package/src/page-env-script.ts +27 -0
- package/src/preview.ts +8 -4
- package/src/query.ts +128 -52
- package/src/realtime.ts +15 -6
- package/src/runtime-env.ts +220 -0
- package/src/setup-fault.ts +18 -0
- package/src/storage.ts +26 -16
- package/src/table-subscription.ts +3 -3
- package/src/thrown-error.ts +31 -0
- package/src/types.ts +65 -14
- package/tests/auth-errors.test.ts +3 -3
- package/tests/auth-events.test.ts +3 -7
- package/tests/auth-sso.test.ts +260 -0
- package/tests/auth-url-session.test.ts +6 -25
- 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/entry-points.test.ts +9 -0
- package/tests/error-family.test.ts +79 -0
- package/tests/helpers/auth-unmount-binding.ts +63 -0
- package/tests/helpers/oauth-binding.ts +4 -3
- package/tests/helpers/stale-read-binding.ts +113 -0
- package/tests/helpers/thrown-error-binding.ts +127 -0
- package/tests/minimal-writes.test.ts +118 -0
- package/tests/postgrest-error-codes.test.ts +5 -5
- package/tests/query.test.ts +3 -3
- package/tests/rate-limit-integration.test.ts +1 -1
- package/tests/realtime-session-auth.test.ts +1 -4
- package/tests/result-error-class.test.ts +107 -0
- package/tests/retry-policy.test.ts +1 -1
- package/tests/rpc-resend.test.ts +33 -8
- package/tests/runtime-env-bundle.test.ts +121 -0
- package/tests/runtime-env-page-script.test.ts +174 -0
- package/tests/runtime-env.test.ts +224 -0
- package/tests/server-bodies.test.ts +3 -3
- package/tests/supatype-prepare.test.ts +139 -0
- package/tests/support/browser.ts +28 -0
- package/tests/support/jwt.ts +9 -0
- package/tests/thrown-error.test.ts +59 -0
- package/tests/unauthorized-resend.test.ts +107 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { vi, describe, it, expect, afterEach, type MockInstance } from "vitest"
|
|
2
|
+
import { MissingClientValuesError, createClient, MutationBuilder, QueryBuilder, type AnyDatabase, type SupatypeClient } from "@supatype/client"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What every framework binding owes a request that throws instead of answering `{ data, error }`.
|
|
6
|
+
*
|
|
7
|
+
* Some faults are thrown on purpose: a client with no API address or anon key throws from its first
|
|
8
|
+
* request. The binding must stop loading, hold the thrown error as its `error`, and say so once on
|
|
9
|
+
* the console. A returned `{ error }` must still arrive as before, unreported. Shared by the Vue,
|
|
10
|
+
* Svelte and Solid suites over a real client, built from the package the bindings import, so the
|
|
11
|
+
* prototypes spied on are the ones the bindings call. Not named `*.test.ts`, so vitest's default
|
|
12
|
+
* include does not collect it as a suite.
|
|
13
|
+
*/
|
|
14
|
+
export interface BindingState {
|
|
15
|
+
error(): unknown
|
|
16
|
+
loading(): boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface ThrownErrorBinding {
|
|
20
|
+
query(table: string): BindingState
|
|
21
|
+
mutation(table: string): BindingState & { mutate(row: Record<string, unknown>): Promise<{ data: unknown; error: unknown }> }
|
|
22
|
+
invoker(name: string): BindingState & { invoke(body: unknown): Promise<{ data: unknown; error: unknown }> }
|
|
23
|
+
auth(): BindingState
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The setup fault a client with no address throws: one of the SDK's errors, held as it is. */
|
|
27
|
+
class SetupFault extends MissingClientValuesError {
|
|
28
|
+
constructor() {
|
|
29
|
+
super("Supatype client has no API address", ["url"])
|
|
30
|
+
this.name = "SetupFault"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
|
|
35
|
+
|
|
36
|
+
/** Every read rejects with `thrown` when awaited, as a request that throws does. */
|
|
37
|
+
function readsReject(thrown: unknown): void {
|
|
38
|
+
vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
|
|
39
|
+
Promise.reject(thrown).then(undefined, onRejected),
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Every write rejects with `thrown` when awaited. */
|
|
44
|
+
function writesReject(thrown: unknown): void {
|
|
45
|
+
vi.spyOn(MutationBuilder.prototype, "then").mockImplementation((_onOk, onRejected) =>
|
|
46
|
+
Promise.reject(thrown).then(undefined, onRejected),
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The console.error calls that carry `thrown`. */
|
|
51
|
+
function reportsOf(logged: MockInstance<typeof console.error>, thrown: unknown): number {
|
|
52
|
+
return logged.mock.calls.filter((call) => call.includes(thrown)).length
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function refusingFetch(): void {
|
|
56
|
+
vi.stubGlobal("fetch", vi.fn(async () => new Response(
|
|
57
|
+
JSON.stringify({ message: "permission denied", code: "42501" }),
|
|
58
|
+
{ status: 403, headers: { "Content-Type": "application/json" } },
|
|
59
|
+
)))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function expectThrownHeld(state: BindingState, thrown: unknown, logged: MockInstance<typeof console.error>): void {
|
|
63
|
+
expect(state.loading()).toBe(false)
|
|
64
|
+
expect(state.error()).toBe(thrown)
|
|
65
|
+
expect(reportsOf(logged, thrown)).toBe(1)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function describeThrownErrorBinding(
|
|
69
|
+
name: string,
|
|
70
|
+
mount: (client: SupatypeClient<AnyDatabase>) => ThrownErrorBinding,
|
|
71
|
+
unmount: () => void,
|
|
72
|
+
): void {
|
|
73
|
+
describe(`${name} when a request throws`, () => {
|
|
74
|
+
const client = (): SupatypeClient<AnyDatabase> => createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
|
|
75
|
+
const thrown = new SetupFault()
|
|
76
|
+
const silence = (): MockInstance<typeof console.error> => vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
77
|
+
|
|
78
|
+
afterEach(() => {
|
|
79
|
+
unmount()
|
|
80
|
+
vi.restoreAllMocks()
|
|
81
|
+
vi.unstubAllGlobals()
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it("a query stops loading, holds the thrown error and reports it once", async () => {
|
|
85
|
+
readsReject(thrown)
|
|
86
|
+
const logged = silence()
|
|
87
|
+
const state = mount(client()).query("posts")
|
|
88
|
+
await settle()
|
|
89
|
+
expectThrownHeld(state, thrown, logged)
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it("a query still holds a returned error, unreported", async () => {
|
|
93
|
+
refusingFetch()
|
|
94
|
+
const logged = silence()
|
|
95
|
+
const state = mount(client()).query("posts")
|
|
96
|
+
await vi.waitFor(() => expect(state.loading()).toBe(false))
|
|
97
|
+
expect(state.error()).toMatchObject({ message: "permission denied" })
|
|
98
|
+
expect(logged).not.toHaveBeenCalled()
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it("a mutation answers and holds the thrown error and reports it once", async () => {
|
|
102
|
+
writesReject(thrown)
|
|
103
|
+
const logged = silence()
|
|
104
|
+
const state = mount(client()).mutation("posts")
|
|
105
|
+
await expect(state.mutate({ title: "a" })).resolves.toMatchObject({ data: null, error: thrown })
|
|
106
|
+
expectThrownHeld(state, thrown, logged)
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it("a function call answers and holds the thrown error and reports it once", async () => {
|
|
110
|
+
const using = client()
|
|
111
|
+
vi.spyOn(using.functions, "invoke").mockRejectedValue(thrown)
|
|
112
|
+
const logged = silence()
|
|
113
|
+
const state = mount(using).invoker("process-order")
|
|
114
|
+
await expect(state.invoke({ id: 1 })).resolves.toEqual({ data: null, error: thrown })
|
|
115
|
+
expectThrownHeld(state, thrown, logged)
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
it("auth stops loading, holds the thrown error and reports it once when starting throws", async () => {
|
|
119
|
+
const using = client()
|
|
120
|
+
vi.spyOn(using.auth, "initialize").mockRejectedValue(thrown)
|
|
121
|
+
const logged = silence()
|
|
122
|
+
const state = mount(using).auth()
|
|
123
|
+
await settle()
|
|
124
|
+
expectThrownHeld(state, thrown, logged)
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"
|
|
2
|
+
import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase, type QueryResult } from "../src/index.js"
|
|
3
|
+
import { fetchCalls, header, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
|
|
4
|
+
|
|
5
|
+
// A write asks for no rows back unless `.select()` says to, as postgrest-js does. Returning a row
|
|
6
|
+
// needs SELECT on it, so a table whose rules let a caller create but not read refused every insert
|
|
7
|
+
// that asked: an anon order form, say, answered 401 42501 for a row it was allowed to write.
|
|
8
|
+
|
|
9
|
+
const BASE = "http://localhost:18473"
|
|
10
|
+
const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
|
|
11
|
+
const ROW = { id: ID, title: "Mine" }
|
|
12
|
+
|
|
13
|
+
/** PostgREST answering a write that asked for nothing back: 201 or 204, and no body. */
|
|
14
|
+
function minimalServer(): FetchMock {
|
|
15
|
+
return mockFetch((_input, init) => {
|
|
16
|
+
const prefer = header(init ?? {}, "Prefer") ?? ""
|
|
17
|
+
if (prefer.includes("return=representation")) return Promise.resolve(jsonResponse([ROW], 201))
|
|
18
|
+
return Promise.resolve(new Response(null, { status: init?.method === "POST" ? 201 : 204 }))
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function serve(fetch: FetchMock): FetchMock {
|
|
23
|
+
vi.stubGlobal("fetch", fetch)
|
|
24
|
+
return fetch
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key", auth: { persistSession: false } })
|
|
28
|
+
|
|
29
|
+
describe("a write without select()", () => {
|
|
30
|
+
afterEach(() => vi.unstubAllGlobals())
|
|
31
|
+
|
|
32
|
+
it("insert asks for no representation and resolves to no rows", async () => {
|
|
33
|
+
const fetch = serve(minimalServer())
|
|
34
|
+
const result = await client().from("orders").insert({ title: "Mine" })
|
|
35
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBeNull()
|
|
36
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it("update asks for no representation and resolves to no rows", async () => {
|
|
40
|
+
const fetch = serve(minimalServer())
|
|
41
|
+
const result = await client().from("orders").update({ title: "Edited" }).eq("id", ID)
|
|
42
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBeNull()
|
|
43
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it("upsert keeps only its conflict resolution", async () => {
|
|
47
|
+
const fetch = serve(minimalServer())
|
|
48
|
+
const result = await client().from("orders").upsert({ id: ID, title: "Mine" })
|
|
49
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBe("resolution=merge-duplicates")
|
|
50
|
+
expect(result.data).toBeNull()
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it("delete resolves to no rows", async () => {
|
|
54
|
+
serve(minimalServer())
|
|
55
|
+
const result = await client().from("orders").delete().eq("id", ID)
|
|
56
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
describe("a write with select()", () => {
|
|
61
|
+
afterEach(() => vi.unstubAllGlobals())
|
|
62
|
+
|
|
63
|
+
it("asks for the representation and resolves to the rows", async () => {
|
|
64
|
+
const fetch = serve(minimalServer())
|
|
65
|
+
const { data, count } = await client().from("orders").insert({ title: "Mine" }).select()
|
|
66
|
+
expect(header(fetchCalls(fetch)[0]?.init ?? {}, "Prefer")).toBe("return=representation")
|
|
67
|
+
expect({ data, count }).toEqual({ data: [ROW], count: 1 })
|
|
68
|
+
})
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
describe("a drafts-model write without select()", () => {
|
|
72
|
+
beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
|
|
73
|
+
afterEach(() => {
|
|
74
|
+
forgetRegisteredDraftModels()
|
|
75
|
+
vi.unstubAllGlobals()
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
/** create_record and save_drafts answer with the record keys; a table read names the matches. */
|
|
79
|
+
function draftsServer(): FetchMock {
|
|
80
|
+
return mockFetch((input) => {
|
|
81
|
+
const url = requestUrl(input)
|
|
82
|
+
if (url.endsWith("/rpc/create_record")) return Promise.resolve(jsonResponse({ record_id: ID, version: 1 }))
|
|
83
|
+
if (url.endsWith("/rpc/save_drafts")) return Promise.resolve(jsonResponse([{ record_id: ID, version: 2 }]))
|
|
84
|
+
return Promise.resolve(jsonResponse([ROW]))
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
it("insert creates the record and reads nothing back", async () => {
|
|
89
|
+
const fetch = serve(draftsServer())
|
|
90
|
+
const result = await client().from("posts").insert({ title: "Mine" })
|
|
91
|
+
expect(fetchCalls(fetch).map(({ url }) => url)).toEqual([`${BASE}/rest/v1/rpc/create_record`])
|
|
92
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
it("update saves the drafts and reads none of them back", async () => {
|
|
96
|
+
const fetch = serve(draftsServer())
|
|
97
|
+
const result = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
98
|
+
expect(fetchCalls(fetch).map(({ url }) => new URL(url).pathname)).toEqual(["/rest/v1/posts", "/rest/v1/rpc/save_drafts"])
|
|
99
|
+
expect(result).toEqual({ data: null, error: null, count: null })
|
|
100
|
+
})
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
// Checked by `tsc -p tests/tsconfig.json`, not by vitest.
|
|
104
|
+
type Order = { Row: { id: string; title: string }; Insert: { title: string }; Update: { title?: string } }
|
|
105
|
+
type Shop = { public: { Tables: { orders: Order } } }
|
|
106
|
+
|
|
107
|
+
describe("the types of a write", () => {
|
|
108
|
+
it("resolve to null without select(), to rows with it, and allow single() only after it", () => {
|
|
109
|
+
const typed = createClient<Shop>({ url: BASE, anonKey: "anon-key" })
|
|
110
|
+
expectTypeOf(typed.from("orders").insert({ title: "x" })).resolves.toEqualTypeOf<QueryResult<null>>()
|
|
111
|
+
expectTypeOf(typed.from("orders").insert({ title: "x" }).select("id")).resolves.toEqualTypeOf<QueryResult<{ id: string }[]>>()
|
|
112
|
+
void typed.from("orders").insert({ title: "x" }).select().single()
|
|
113
|
+
// @ts-expect-error a write returns no row until select() asks for one
|
|
114
|
+
void typed.from("orders").insert({ title: "x" }).single()
|
|
115
|
+
// @ts-expect-error a write returns no row until select() asks for one
|
|
116
|
+
void typed.from("orders").update({ title: "x" }).eq("id", ID).maybeSingle()
|
|
117
|
+
})
|
|
118
|
+
})
|
|
@@ -50,14 +50,14 @@ describe("single() without exactly one row", () => {
|
|
|
50
50
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
|
|
51
51
|
const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {}).single()
|
|
52
52
|
vi.unstubAllGlobals()
|
|
53
|
-
expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
53
|
+
expect({ ...error }).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
54
54
|
})
|
|
55
55
|
|
|
56
56
|
it("a write words it as PostgREST does", async () => {
|
|
57
57
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(emptyArray()))
|
|
58
|
-
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).single()
|
|
58
|
+
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", {}, "PATCH", {}).select().single()
|
|
59
59
|
vi.unstubAllGlobals()
|
|
60
|
-
expect(error).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
60
|
+
expect({ ...error }).toEqual({ message: SINGLE_ROW_MESSAGE, code: "PGRST116" })
|
|
61
61
|
})
|
|
62
62
|
})
|
|
63
63
|
|
|
@@ -73,13 +73,13 @@ describe("a field validator's refusal", () => {
|
|
|
73
73
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
|
|
74
74
|
const { error } = await new QueryBuilder("http://x", "/rest/v1/t", {})
|
|
75
75
|
vi.unstubAllGlobals()
|
|
76
|
-
expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
|
|
76
|
+
expect({ ...error }).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
|
|
77
77
|
})
|
|
78
78
|
|
|
79
79
|
it("keeps the field on a write, which is where a validator runs", async () => {
|
|
80
80
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(refused()))
|
|
81
81
|
const { error } = await new MutationBuilder("http://x", "/rest/v1/t", { body: "HELLO" }, "POST", {})
|
|
82
82
|
vi.unstubAllGlobals()
|
|
83
|
-
expect(error).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
|
|
83
|
+
expect({ ...error }).toEqual({ message: "That reads as shouting.", status: 422, field: "body" })
|
|
84
84
|
})
|
|
85
85
|
})
|
package/tests/query.test.ts
CHANGED
|
@@ -268,7 +268,7 @@ describe("MutationBuilder: insert", () => {
|
|
|
268
268
|
it("sends POST with body", async () => {
|
|
269
269
|
const fetch = mockFetch([{ id: "1", title: "New", status: "draft" }])
|
|
270
270
|
vi.stubGlobal("fetch", fetch)
|
|
271
|
-
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" })
|
|
271
|
+
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { title: "New", status: "draft" }).select()
|
|
272
272
|
expect(error).toBeNull()
|
|
273
273
|
expect(data?.[0]?.id).toBe("1")
|
|
274
274
|
const { init } = fetchCall(fetch)
|
|
@@ -305,9 +305,9 @@ describe("MutationBuilder: update / delete", () => {
|
|
|
305
305
|
expect(url).toContain("id=eq.1")
|
|
306
306
|
})
|
|
307
307
|
|
|
308
|
-
it("204 No Content returns empty data array", async () => {
|
|
308
|
+
it("204 No Content to delete().select() returns an empty data array", async () => {
|
|
309
309
|
vi.stubGlobal("fetch", mockFetch(null, { status: 204 }))
|
|
310
|
-
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
|
|
310
|
+
const { data, error } = await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1").select()
|
|
311
311
|
expect(error).toBeNull()
|
|
312
312
|
expect(data).toEqual([])
|
|
313
313
|
})
|
|
@@ -120,7 +120,7 @@ describe("Task 91: SDK rate limit integration", () => {
|
|
|
120
120
|
expect.fail("Should have thrown RateLimitError")
|
|
121
121
|
} catch (err) {
|
|
122
122
|
expect(err).toBeInstanceOf(RateLimitError)
|
|
123
|
-
expect(err).toMatchObject({ retryAfterSeconds: 2,
|
|
123
|
+
expect(err).toMatchObject({ retryAfterSeconds: 2, status: 429, code: "RATE_LIMITED" })
|
|
124
124
|
}
|
|
125
125
|
vi.useFakeTimers()
|
|
126
126
|
})
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from "./helpers/mock-websocket.js"
|
|
23
23
|
import { createClient } from "../src/index.js"
|
|
24
24
|
import type { Session } from "../src/types.js"
|
|
25
|
+
import { fakeJwt } from "./support/jwt.js"
|
|
25
26
|
|
|
26
27
|
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 10))
|
|
27
28
|
|
|
@@ -30,10 +31,6 @@ function bearerHeaders(token: string): Record<string, string> {
|
|
|
30
31
|
return { apikey: "anon-key", Authorization: `Bearer ${token}` }
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
function fakeJwt(payload: Record<string, unknown>): string {
|
|
34
|
-
return `${btoa(JSON.stringify({ alg: "HS256", typ: "JWT" }))}.${btoa(JSON.stringify(payload))}.sig`
|
|
35
|
-
}
|
|
36
|
-
|
|
37
34
|
const ANON_KEY = fakeJwt({ role: "anon" })
|
|
38
35
|
const USER_TOKEN = fakeJwt({
|
|
39
36
|
role: "authenticated",
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `error` of a `{ data, error }` result is an `Error`, whatever produced it.
|
|
3
|
+
*
|
|
4
|
+
* It used to be a plain object typed `SupatypeError`, so `error instanceof Error` was false and
|
|
5
|
+
* `String(error)` printed "[object Object]": a page that rendered a failed request's error showed
|
|
6
|
+
* exactly that for a network failure or a CORS refusal. It is now a `SupatypeError`, with the
|
|
7
|
+
* same `message`, `code` and `status` as before, and the same keys when it is turned into JSON.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { afterEach, assert, describe, expect, it, vi } from "vitest"
|
|
11
|
+
import { createClient, SupatypeError, type SupatypeClient } from "../src/index.js"
|
|
12
|
+
import { NetworkError } from "../src/errors.js"
|
|
13
|
+
import { reportThrown } from "../src/thrown-error.js"
|
|
14
|
+
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
vi.unstubAllGlobals()
|
|
17
|
+
vi.restoreAllMocks()
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
type Request = (client: SupatypeClient) => PromiseLike<{ error: unknown }>
|
|
21
|
+
|
|
22
|
+
const client = (): SupatypeClient => createClient({ url: "http://127.0.0.1:9", anonKey: "x", retry: false })
|
|
23
|
+
|
|
24
|
+
/** Every request fails in transit, as fetch does when nothing listens on the port. */
|
|
25
|
+
function unreachable(): void {
|
|
26
|
+
vi.stubGlobal("fetch", () => Promise.reject(new TypeError("fetch failed")))
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Every request is answered with `status` and the JSON `body`. */
|
|
30
|
+
function answering(status: number, body: Record<string, unknown>): void {
|
|
31
|
+
vi.stubGlobal("fetch", () =>
|
|
32
|
+
Promise.resolve(new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })),
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The error a result carries is an Error that reads as its message and keeps the old JSON form. */
|
|
37
|
+
function expectResultError(error: unknown, shape: Record<string, unknown>): void {
|
|
38
|
+
assert(error instanceof Error)
|
|
39
|
+
expect(error).toBeInstanceOf(SupatypeError)
|
|
40
|
+
expect(String(error)).toBe(`${error.name}: ${String(shape["message"])}`)
|
|
41
|
+
expect(JSON.parse(JSON.stringify(error))).toEqual(shape)
|
|
42
|
+
expect({ ...error }).toEqual(shape)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const NETWORK_FAILURES: ReadonlyArray<readonly [string, Request]> = [
|
|
46
|
+
["a table read", (c) => c.from("posts").select("id")],
|
|
47
|
+
["an rpc call", (c) => c.rpc("hello")],
|
|
48
|
+
["a bucket list", (c) => c.storage.listBuckets()],
|
|
49
|
+
["a GraphQL query", (c) => c.graphql("{ __typename }")],
|
|
50
|
+
["a function call", (c) => c.functions.invoke("hello")],
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
describe("a request that never got an answer", () => {
|
|
54
|
+
it.each(NETWORK_FAILURES)("answers %s with an Error carrying the same fields", async (_label, request) => {
|
|
55
|
+
unreachable()
|
|
56
|
+
const { error } = await request(client())
|
|
57
|
+
expectResultError(error, { message: "fetch failed", code: "NETWORK_ERROR" })
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("is the NetworkError the transport threw, so its class names the failure", async () => {
|
|
61
|
+
unreachable()
|
|
62
|
+
const { error } = await client().from("posts").select("id")
|
|
63
|
+
expect(error).toBeInstanceOf(NetworkError)
|
|
64
|
+
expect(String(error)).toBe("NetworkError: fetch failed")
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
describe("a request the server refused", () => {
|
|
70
|
+
it("answers a refused table read with an Error carrying the code and status", async () => {
|
|
71
|
+
answering(403, { code: "42501", message: "permission denied for table posts" })
|
|
72
|
+
const { error } = await client().from("posts").select("id")
|
|
73
|
+
expectResultError(error, { message: "permission denied for table posts", code: "42501", status: 403 })
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it("answers a refused storage list with an Error carrying the status", async () => {
|
|
77
|
+
answering(403, { message: "not allowed" })
|
|
78
|
+
const { error } = await client().storage.from("avatars").list()
|
|
79
|
+
expectResultError(error, { message: "not allowed", status: 403 })
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it("answers a refused sign-in with an Error carrying the auth code", async () => {
|
|
83
|
+
answering(400, { error_code: "invalid_credentials", msg: "Invalid login credentials" })
|
|
84
|
+
const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
|
|
85
|
+
expectResultError(error, { message: "Invalid login credentials", code: "invalid_credentials", status: 400 })
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it("answers a call needing a session with an Error when there is none", async () => {
|
|
89
|
+
const { error } = await client().auth.updateUser({ data: {} })
|
|
90
|
+
expectResultError(error, { message: "Not authenticated" })
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
describe("a binding's thrown request", () => {
|
|
95
|
+
it("holds a thrown string as an Error", () => {
|
|
96
|
+
vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
97
|
+
expectResultError(reportThrown("useQuery(\"posts\")", "bad thing"), { message: "bad thing" })
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it("holds the SDK's own errors as an Error with the result's fields", () => {
|
|
101
|
+
vi.spyOn(console, "error").mockImplementation(() => undefined)
|
|
102
|
+
expectResultError(reportThrown("useQuery(\"posts\")", new NetworkError("offline")), {
|
|
103
|
+
message: "offline",
|
|
104
|
+
code: "NETWORK_ERROR",
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
})
|
|
@@ -133,7 +133,7 @@ describe("auth and storage use the client's transport", () => {
|
|
|
133
133
|
fetchReturning({ code: 429, error_code: "over_request_rate_limit", msg: "Request rate limit reached" }, 429),
|
|
134
134
|
)
|
|
135
135
|
const { error } = await client().auth.signInWithPassword({ email: "a@example.com", password: "pw" })
|
|
136
|
-
expect(error).toEqual({ message: "Request rate limit reached", status: 429, code: "over_request_rate_limit" })
|
|
136
|
+
expect({ ...error }).toEqual({ message: "Request rate limit reached", status: 429, code: "over_request_rate_limit" })
|
|
137
137
|
})
|
|
138
138
|
|
|
139
139
|
it("a storage upload that never answers ends at the timeout", { timeout: 2000 }, async () => {
|
package/tests/rpc-resend.test.ts
CHANGED
|
@@ -1,22 +1,47 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
-
import { createClient } from "../src/index.js"
|
|
3
|
-
import { fetchCalls, header, jsonResponse, mockFetch } from "./support/fetch-mock.js"
|
|
2
|
+
import { createClient, type Session } from "../src/index.js"
|
|
3
|
+
import { fetchCalls, header, jsonResponse, mockFetch, requestUrl } from "./support/fetch-mock.js"
|
|
4
|
+
import { fakeJwt } from "./support/jwt.js"
|
|
5
|
+
|
|
6
|
+
// A resend follows only a refresh that replaced a refused session token, so the caller is signed in.
|
|
7
|
+
const NOW = Math.floor(Date.now() / 1000)
|
|
8
|
+
const userJwt = (n: number): string => fakeJwt({ role: "authenticated", sub: "u1", exp: NOW + 3600, n })
|
|
9
|
+
|
|
10
|
+
const USER = { id: "u1", appMetadata: {}, userMetadata: {}, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z" }
|
|
11
|
+
const SESSION: Session = { accessToken: userJwt(1), tokenType: "bearer", expiresIn: 3600, refreshToken: "rt-1", user: USER }
|
|
12
|
+
const REFRESHED = {
|
|
13
|
+
access_token: userJwt(2),
|
|
14
|
+
refresh_token: "rt-2",
|
|
15
|
+
token_type: "bearer",
|
|
16
|
+
expires_in: 3600,
|
|
17
|
+
user: { id: "u1", app_metadata: {}, user_metadata: {}, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z" },
|
|
18
|
+
}
|
|
4
19
|
|
|
5
20
|
describe("rpc: the resend after a 401 is the same request", () => {
|
|
6
21
|
beforeEach(() => vi.restoreAllMocks())
|
|
7
22
|
|
|
8
23
|
it("keeps Content-Profile and Prefer on the second send", async () => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
.
|
|
24
|
+
let refused = false
|
|
25
|
+
const fetch = mockFetch((input) => {
|
|
26
|
+
if (requestUrl(input).includes("/auth/v1/token")) return Promise.resolve(jsonResponse(REFRESHED))
|
|
27
|
+
if (refused) return Promise.resolve(jsonResponse(1, 200))
|
|
28
|
+
refused = true
|
|
29
|
+
return Promise.resolve(jsonResponse({ code: "PGRST303", message: "JWT expired" }, 401))
|
|
30
|
+
})
|
|
12
31
|
vi.stubGlobal("fetch", fetch)
|
|
13
|
-
const client = createClient({
|
|
32
|
+
const client = createClient({
|
|
33
|
+
url: "http://localhost:18473",
|
|
34
|
+
anonKey: "anon",
|
|
35
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
36
|
+
initialSession: SESSION,
|
|
37
|
+
})
|
|
14
38
|
|
|
15
39
|
const { error } = await client.rpc("publish", undefined, { schema: "supatype", count: "exact" })
|
|
16
40
|
|
|
17
41
|
expect(error).toBeNull()
|
|
18
|
-
|
|
19
|
-
|
|
42
|
+
const sends = fetchCalls(fetch).filter(({ url }) => url.includes("/rpc/publish"))
|
|
43
|
+
expect(sends).toHaveLength(2)
|
|
44
|
+
for (const { init } of sends) {
|
|
20
45
|
expect(header(init, "Content-Profile")).toBe("supatype")
|
|
21
46
|
expect(header(init, "Prefer")).toBe("count=exact")
|
|
22
47
|
}
|