@supatype/client 0.3.6 → 0.7.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 +58 -31
- package/.turbo/turbo-typecheck.log +2 -2
- package/LICENSE +1 -1
- package/dist/auth-redirect.d.ts +48 -0
- package/dist/auth-redirect.d.ts.map +1 -0
- package/dist/auth-redirect.js +70 -0
- package/dist/auth-redirect.js.map +1 -0
- package/dist/auth.d.ts +78 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +373 -274
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +16 -0
- package/dist/bindings.d.ts.map +1 -0
- package/dist/bindings.js +13 -0
- package/dist/bindings.js.map +1 -0
- package/dist/caller-types.d.ts +18 -0
- package/dist/caller-types.d.ts.map +1 -0
- package/dist/caller-types.js +22 -0
- package/dist/caller-types.js.map +1 -0
- package/dist/draft-create.d.ts +12 -0
- package/dist/draft-create.d.ts.map +1 -0
- package/dist/draft-create.js +47 -0
- package/dist/draft-create.js.map +1 -0
- package/dist/draft-models-registry.d.ts +27 -0
- package/dist/draft-models-registry.d.ts.map +1 -0
- package/dist/draft-models-registry.js +61 -0
- package/dist/draft-models-registry.js.map +1 -0
- 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 +42 -34
- package/dist/error-codes-doc.js.map +1 -1
- package/dist/errors.d.ts +102 -60
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +69 -28
- package/dist/errors.js.map +1 -1
- package/dist/exact-response.d.ts.map +1 -1
- package/dist/exact-response.js +2 -1
- package/dist/exact-response.js.map +1 -1
- package/dist/exact-values.d.ts +2 -0
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +12 -10
- package/dist/exact-values.js.map +1 -1
- package/dist/fetch-with-retry.d.ts +21 -6
- package/dist/fetch-with-retry.d.ts.map +1 -1
- package/dist/fetch-with-retry.js +67 -53
- package/dist/fetch-with-retry.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +11 -3
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +10 -6
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/filters.d.ts +51 -0
- package/dist/filters.d.ts.map +1 -0
- package/dist/filters.js +117 -0
- package/dist/filters.js.map +1 -0
- package/dist/generated-client.d.ts +7 -0
- package/dist/generated-client.d.ts.map +1 -0
- package/dist/generated-client.js +7 -0
- package/dist/generated-client.js.map +1 -0
- package/dist/graphql-document.d.ts +39 -0
- package/dist/graphql-document.d.ts.map +1 -0
- package/dist/graphql-document.js +228 -0
- package/dist/graphql-document.js.map +1 -0
- package/dist/graphql-json.d.ts +56 -0
- package/dist/graphql-json.d.ts.map +1 -0
- package/dist/graphql-json.js +220 -0
- package/dist/graphql-json.js.map +1 -0
- package/dist/graphql-transport.d.ts +28 -0
- package/dist/graphql-transport.d.ts.map +1 -0
- package/dist/graphql-transport.js +77 -0
- package/dist/graphql-transport.js.map +1 -0
- package/dist/index.d.ts +103 -40
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +153 -157
- package/dist/index.js.map +1 -1
- package/dist/json.d.ts +61 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +83 -0
- package/dist/json.js.map +1 -0
- package/dist/jwt.d.ts +16 -0
- package/dist/jwt.d.ts.map +1 -0
- package/dist/jwt.js +37 -0
- package/dist/jwt.js.map +1 -0
- package/dist/live-preview.d.ts +23 -0
- package/dist/live-preview.d.ts.map +1 -0
- package/dist/live-preview.js +28 -0
- package/dist/live-preview.js.map +1 -0
- package/dist/mutation-request.d.ts +17 -0
- package/dist/mutation-request.d.ts.map +1 -0
- package/dist/mutation-request.js +41 -0
- package/dist/mutation-request.js.map +1 -0
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +8 -6
- package/dist/preview.js.map +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +19 -13
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +108 -29
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +294 -224
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +20 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +105 -12
- package/dist/realtime.js.map +1 -1
- package/dist/select-types.d.ts +99 -0
- package/dist/select-types.d.ts.map +1 -0
- package/dist/select-types.js +2 -0
- package/dist/select-types.js.map +1 -0
- package/dist/storage.d.ts +81 -11
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +129 -37
- package/dist/storage.js.map +1 -1
- package/dist/table-subscription.d.ts +69 -0
- package/dist/table-subscription.d.ts.map +1 -0
- package/dist/table-subscription.js +93 -0
- package/dist/table-subscription.js.map +1 -0
- package/dist/types.d.ts +84 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -2
- package/src/auth-redirect.ts +90 -0
- package/src/auth.ts +421 -280
- package/src/bindings.ts +22 -0
- package/src/caller-types.ts +27 -0
- package/src/draft-create.ts +51 -0
- package/src/draft-models-registry.ts +81 -0
- package/src/error-codes-doc.ts +44 -35
- package/src/errors.ts +72 -28
- package/src/exact-response.ts +2 -1
- package/src/exact-values.ts +16 -9
- package/src/fetch-with-retry.ts +80 -70
- package/src/field-kinds-registry.ts +22 -9
- package/src/filters.ts +133 -0
- package/src/generated-client.ts +6 -0
- package/src/graphql-document.ts +234 -0
- package/src/graphql-json.ts +243 -0
- package/src/graphql-transport.ts +97 -0
- package/src/index.ts +272 -201
- package/src/json.ts +117 -0
- package/src/jwt.ts +37 -0
- package/src/live-preview.ts +37 -0
- package/src/mutation-request.ts +66 -0
- package/src/preview.ts +9 -11
- package/src/query-cache.ts +19 -16
- package/src/query.ts +389 -270
- package/src/realtime.ts +116 -13
- package/src/select-types.ts +184 -0
- package/src/storage.ts +214 -43
- package/src/table-subscription.ts +160 -0
- package/src/types.ts +90 -5
- package/tests/auth-error-codes.test.ts +53 -0
- package/tests/auth-errors.test.ts +84 -0
- package/tests/auth-events.test.ts +136 -0
- package/tests/auth-url-session.test.ts +204 -0
- package/tests/auth.test.ts +122 -26
- package/tests/count.test.ts +60 -0
- package/tests/data-plane-auth.test.ts +21 -46
- package/tests/draft-insert.integration.test.ts +118 -0
- package/tests/draft-insert.test.ts +225 -0
- package/tests/draft-profile.test.ts +55 -84
- package/tests/draft-update.integration.test.ts +122 -0
- package/tests/draft-update.test.ts +174 -0
- package/tests/dynamic-headers.test.ts +45 -0
- package/tests/entry-points.test.ts +42 -0
- package/tests/exact-response.test.ts +4 -4
- package/tests/exact-values.test.ts +14 -25
- package/tests/field-kinds-registry.test.ts +3 -3
- package/tests/filters.test.ts +146 -0
- package/tests/graphql-json.test.ts +199 -0
- package/tests/helpers/mock-websocket.ts +44 -11
- package/tests/helpers/oauth-binding.ts +92 -0
- package/tests/helpers/signup-binding.ts +73 -0
- package/tests/helpers/socket-swap.ts +139 -0
- package/tests/mfa-totp-integration.test.ts +13 -20
- package/tests/postgrest-error-codes.test.ts +85 -0
- package/tests/query-cache.test.ts +116 -117
- package/tests/query.test.ts +29 -31
- package/tests/rate-limit-integration.test.ts +4 -12
- package/tests/realtime-exact-values.test.ts +2 -4
- package/tests/realtime-presence.test.ts +75 -0
- package/tests/realtime-session-auth.test.ts +2 -4
- package/tests/realtime-swap-status.test.ts +62 -0
- package/tests/retry-integration.test.ts +3 -8
- package/tests/retry-policy.test.ts +166 -0
- package/tests/rpc-resend.test.ts +24 -0
- package/tests/server-bodies.test.ts +139 -0
- package/tests/serverless.test.ts +2 -2
- package/tests/signed-url-absolute.test.ts +2 -5
- package/tests/storage-object-shape.test.ts +101 -0
- package/tests/storage-quota-integration.test.ts +3 -2
- package/tests/storage-reference-url.test.ts +51 -0
- package/tests/storage-upload-browser.test.ts +71 -0
- package/tests/storage-upload-limit-integration.test.ts +12 -22
- package/tests/subscribe-frame.test.ts +5 -11
- package/tests/support/fetch-mock.ts +64 -0
- package/tests/support/storage-object.ts +37 -0
- package/tests/table-subscribe.test.ts +13 -13
- package/tests/table-subscription.test.ts +105 -0
- package/tests/table-transport.test.ts +94 -0
- package/tests/tsconfig.json +1 -1
- package/tests/types.test.ts +153 -1
- package/tsconfig.json +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"
|
|
2
|
+
import { createClient, forgetRegisteredDraftModels, registerDraftModels, type AnyDatabase, type DraftUpdateOptions, type UpdateOptions } from "../src/index.js"
|
|
3
|
+
import { runMutation } from "../src/bindings.js"
|
|
4
|
+
import { fetchCalls, header, jsonBody, jsonResponse, mockFetch, requestUrl, type FetchMock } from "./support/fetch-mock.js"
|
|
5
|
+
|
|
6
|
+
// An update on a model that keeps drafts saves a new draft of each record it matches, through
|
|
7
|
+
// `supatype.save_drafts`, and leaves the live rows as they are: they change only when a version is
|
|
8
|
+
// published. `{ publish: true }` saves and publishes in the same call. These pin which requests go
|
|
9
|
+
// out and what the caller gets back.
|
|
10
|
+
|
|
11
|
+
const BASE = "http://localhost:18473"
|
|
12
|
+
const ID = "7b1f115e-418d-4e92-91d0-f199ebd06e5e"
|
|
13
|
+
const ID_B = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
|
|
14
|
+
const DRAFT = { id: ID, title: "Edited", published_at: "2026-10-18T10:00:00Z" }
|
|
15
|
+
const SAVED = { record_id: ID, version: 2, status: "draft", created_at: "2026-10-22T08:00:00Z" }
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Answers as the database does for an editor: the table read names the matched records, `save_drafts`
|
|
19
|
+
* saves a version of each, and the draft view reads them back.
|
|
20
|
+
*/
|
|
21
|
+
function draftsServer(matched: readonly string[] = [ID]): FetchMock {
|
|
22
|
+
return mockFetch((input, init) => {
|
|
23
|
+
const url = new URL(requestUrl(input))
|
|
24
|
+
if (url.pathname.endsWith("/rpc/save_drafts")) {
|
|
25
|
+
return Promise.resolve(jsonResponse(matched.map((id) => ({ ...SAVED, record_id: id }))))
|
|
26
|
+
}
|
|
27
|
+
if (init?.method === "PATCH") return Promise.resolve(jsonResponse([{ ...DRAFT, title: "Live!" }]))
|
|
28
|
+
if (header(init ?? {}, "Accept-Profile") === "draft") return Promise.resolve(jsonResponse([DRAFT]))
|
|
29
|
+
return Promise.resolve(jsonResponse(matched.map((id) => ({ id }))))
|
|
30
|
+
})
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function serve(fetch: FetchMock): FetchMock {
|
|
34
|
+
vi.stubGlobal("fetch", fetch)
|
|
35
|
+
return fetch
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Untyped, as a project whose schema the test fixtures do not describe.
|
|
39
|
+
const client = () => createClient<AnyDatabase>({ url: BASE, anonKey: "anon-key" })
|
|
40
|
+
|
|
41
|
+
describe("update on a model that keeps drafts", () => {
|
|
42
|
+
beforeEach(() => registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } }))
|
|
43
|
+
afterEach(() => {
|
|
44
|
+
forgetRegisteredDraftModels()
|
|
45
|
+
vi.unstubAllGlobals()
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it("reads the keys of the records its filters match, as the caller reads the table", async () => {
|
|
49
|
+
const fetch = serve(draftsServer())
|
|
50
|
+
await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
51
|
+
const [match] = fetchCalls(fetch)
|
|
52
|
+
const url = new URL(match?.url ?? "")
|
|
53
|
+
expect(match?.init.method).toBe("GET")
|
|
54
|
+
expect(url.pathname).toBe("/rest/v1/posts")
|
|
55
|
+
expect(url.searchParams.get("id")).toBe(`eq.${ID}`)
|
|
56
|
+
expect(url.searchParams.get("select")).toBe("id")
|
|
57
|
+
expect(header(match?.init ?? {}, "Accept-Profile")).toBeNull()
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("saves a draft of each through supatype.save_drafts and never patches the live row", async () => {
|
|
61
|
+
const fetch = serve(draftsServer([ID, ID_B]))
|
|
62
|
+
await client().from("posts").update({ title: "Edited" }).in("id", [ID, ID_B])
|
|
63
|
+
const calls = fetchCalls(fetch)
|
|
64
|
+
const save = calls[1]
|
|
65
|
+
expect(save?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
|
|
66
|
+
expect(save?.init.method).toBe("POST")
|
|
67
|
+
expect(header(save?.init ?? {}, "Content-Profile")).toBe("supatype")
|
|
68
|
+
expect(jsonBody(save?.init ?? {})).toEqual({
|
|
69
|
+
model_table: "posts",
|
|
70
|
+
record_ids: [ID, ID_B],
|
|
71
|
+
data: { title: "Edited" },
|
|
72
|
+
publish: false,
|
|
73
|
+
})
|
|
74
|
+
expect(calls.map((call) => call.init.method)).not.toContain("PATCH")
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it("returns the draft rows, read back from the draft view with the update's select", async () => {
|
|
78
|
+
const fetch = serve(draftsServer())
|
|
79
|
+
const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID).select("id, title")
|
|
80
|
+
const readBack = fetchCalls(fetch)[2]
|
|
81
|
+
const url = new URL(readBack?.url ?? "")
|
|
82
|
+
expect(url.searchParams.get("id")).toBe(`in.(${ID})`)
|
|
83
|
+
expect(url.searchParams.get("select")).toBe("id, title")
|
|
84
|
+
expect(header(readBack?.init ?? {}, "Accept-Profile")).toBe("draft")
|
|
85
|
+
expect(error).toBeNull()
|
|
86
|
+
expect(data).toEqual([DRAFT])
|
|
87
|
+
expect(count).toBe(1)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it("publishes in the same call with { publish: true }", async () => {
|
|
91
|
+
const fetch = serve(draftsServer())
|
|
92
|
+
const { error } = await client().from("posts").update({ title: "Edited" }, { publish: true }).eq("id", ID)
|
|
93
|
+
expect(error).toBeNull()
|
|
94
|
+
expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it("saves nothing when the filters match no record, as a PATCH that matches nothing", async () => {
|
|
98
|
+
const fetch = serve(draftsServer([]))
|
|
99
|
+
const { data, error, count } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
100
|
+
expect(fetchCalls(fetch)).toHaveLength(1)
|
|
101
|
+
expect({ data, error, count }).toEqual({ data: [], error: null, count: 0 })
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it("passes save_drafts' refusal through and reads nothing back", async () => {
|
|
105
|
+
const refused = { code: "42501", details: null, hint: null, message: 'new row violates row-level security policy for table "posts_versions"' }
|
|
106
|
+
const fetch = serve(
|
|
107
|
+
mockFetch((input) =>
|
|
108
|
+
Promise.resolve(requestUrl(input).includes("/rpc/") ? jsonResponse(refused, 403) : jsonResponse([{ id: ID }])),
|
|
109
|
+
),
|
|
110
|
+
)
|
|
111
|
+
const { data, error } = await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
112
|
+
expect(data).toBeNull()
|
|
113
|
+
expect(error).toMatchObject({ code: "42501", status: 403 })
|
|
114
|
+
expect(fetchCalls(fetch)).toHaveLength(2)
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it("reaches the framework bindings, which update through runMutation", async () => {
|
|
118
|
+
const fetch = serve(draftsServer())
|
|
119
|
+
const outcome = await runMutation(client(), "posts", "update", { title: "Edited" }, { id: ID }, { publish: true })
|
|
120
|
+
expect(fetchCalls(fetch)[1]?.url).toBe(`${BASE}/rest/v1/rpc/save_drafts`)
|
|
121
|
+
expect(jsonBody(fetchCalls(fetch)[1]?.init ?? {})["publish"]).toBe(true)
|
|
122
|
+
expect(outcome.data).toEqual([DRAFT])
|
|
123
|
+
})
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
describe("update on a model that keeps no drafts", () => {
|
|
127
|
+
afterEach(() => {
|
|
128
|
+
forgetRegisteredDraftModels()
|
|
129
|
+
vi.unstubAllGlobals()
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
it("is a plain PATCH asking for the rows back", async () => {
|
|
133
|
+
registerDraftModels({ version: 1, tables: { posts: { primaryKey: "id" } } })
|
|
134
|
+
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([{ id: 1, label: "news" }]))))
|
|
135
|
+
const { data } = await client().from("tags").update({ label: "news" }).eq("id", 1)
|
|
136
|
+
const [only] = fetchCalls(fetch)
|
|
137
|
+
expect(fetchCalls(fetch)).toHaveLength(1)
|
|
138
|
+
expect(only?.init.method).toBe("PATCH")
|
|
139
|
+
expect(only?.url).toBe(`${BASE}/rest/v1/tags?id=eq.1`)
|
|
140
|
+
expect(header(only?.init ?? {}, "Prefer")).toContain("return=representation")
|
|
141
|
+
expect(data).toEqual([{ id: 1, label: "news" }])
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it("is a plain PATCH when nothing was registered, as for a client built without the generated file", async () => {
|
|
145
|
+
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([DRAFT]))))
|
|
146
|
+
await client().from("posts").update({ title: "Edited" }).eq("id", ID)
|
|
147
|
+
expect(fetchCalls(fetch).map((call) => call.init.method)).toEqual(["PATCH"])
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
it("refuses { publish: true } without sending anything, since there is nothing to publish", async () => {
|
|
151
|
+
const fetch = serve(mockFetch(() => Promise.resolve(jsonResponse([]))))
|
|
152
|
+
const { data, error } = await client().from("tags").update({ label: "news" }, { publish: true }).eq("id", 1)
|
|
153
|
+
expect(fetchCalls(fetch)).toHaveLength(0)
|
|
154
|
+
expect(data).toBeNull()
|
|
155
|
+
expect(error?.message).toContain("keeps drafts")
|
|
156
|
+
expect(error?.message).toContain("./supatype/generated/client")
|
|
157
|
+
})
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
// Checked by `tsc -p tests/tsconfig.json`, not by vitest.
|
|
161
|
+
type Post = { Row: { id: string; title: string }; Insert: { title: string }; Update: { title?: string }; Drafts: true }
|
|
162
|
+
type Tag = { Row: { id: number; label: string }; Insert: { label: string }; Update: { label?: string } }
|
|
163
|
+
type Blog = { public: { Tables: { posts: Post; tags: Tag } } }
|
|
164
|
+
|
|
165
|
+
describe("the publish option's types", () => {
|
|
166
|
+
it("exists on a drafts model and not on any other", () => {
|
|
167
|
+
expectTypeOf<UpdateOptions<Post>>().toEqualTypeOf<DraftUpdateOptions>()
|
|
168
|
+
expectTypeOf<UpdateOptions<Tag>>().toBeNever()
|
|
169
|
+
const typed = createClient<Blog>({ url: BASE, anonKey: "anon-key" })
|
|
170
|
+
void typed.from("posts").update({ title: "x" }, { publish: true })
|
|
171
|
+
// @ts-expect-error a model with no drafts has nothing to publish
|
|
172
|
+
void typed.from("tags").update({ label: "x" }, { publish: true })
|
|
173
|
+
})
|
|
174
|
+
})
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `headers` may be a function, read on every request, so a header can change for the life of one
|
|
3
|
+
* client. Studio's acting-mode switch needs this: the mode a request asks for is chosen after the
|
|
4
|
+
* client exists, and rebuilding the client would drop its session and its sockets.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from "vitest"
|
|
8
|
+
import { createClient } from "../src/index.js"
|
|
9
|
+
|
|
10
|
+
const BASE = "http://localhost:18474"
|
|
11
|
+
const ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiJ9.test"
|
|
12
|
+
|
|
13
|
+
afterEach(() => {
|
|
14
|
+
vi.unstubAllGlobals()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
function captureRequests(): Headers[] {
|
|
18
|
+
const seen: Headers[] = []
|
|
19
|
+
vi.stubGlobal("fetch", async (_url: string, init?: RequestInit) => {
|
|
20
|
+
seen.push(new Headers(init?.headers))
|
|
21
|
+
return new Response("[]", { status: 200, headers: { "content-type": "application/json" } })
|
|
22
|
+
})
|
|
23
|
+
return seen
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe("headers", () => {
|
|
27
|
+
it("are read on every request when given as a function", async () => {
|
|
28
|
+
const seen = captureRequests()
|
|
29
|
+
let mode = "elevated"
|
|
30
|
+
const client = createClient({ url: BASE, anonKey: ANON_KEY, headers: () => ({ "X-Supatype-Acting-Mode": mode }) })
|
|
31
|
+
|
|
32
|
+
await client.from("posts").select()
|
|
33
|
+
mode = "self"
|
|
34
|
+
await client.from("posts").select()
|
|
35
|
+
|
|
36
|
+
expect(seen.map((h) => h.get("X-Supatype-Acting-Mode"))).toEqual(["elevated", "self"])
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it("are still sent when given as a plain object", async () => {
|
|
40
|
+
const seen = captureRequests()
|
|
41
|
+
const client = createClient({ url: BASE, anonKey: ANON_KEY, headers: { "X-Supatype-Environment": "staging" } })
|
|
42
|
+
await client.from("posts").select()
|
|
43
|
+
expect(seen[0]?.get("X-Supatype-Environment")).toBe("staging")
|
|
44
|
+
})
|
|
45
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The framework bindings' building blocks live on `@supatype/client/bindings`, not the main entry.
|
|
3
|
+
*
|
|
4
|
+
* `watchTable`, `runMutation` and their helpers exist so the bindings share one copy of the
|
|
5
|
+
* channel wiring and the mutation requests. On the main entry they read as API an app should call,
|
|
6
|
+
* and anything exported there is a promise to every app. The subpath keeps them available to the
|
|
7
|
+
* bindings without that.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, it, expect } from "vitest"
|
|
11
|
+
import { readFileSync } from "node:fs"
|
|
12
|
+
import * as main from "../src/index.js"
|
|
13
|
+
import * as bindings from "../src/bindings.js"
|
|
14
|
+
|
|
15
|
+
const BINDING_EXPORTS = [
|
|
16
|
+
"watchTable",
|
|
17
|
+
"subscribeToTable",
|
|
18
|
+
"subscriptionViewOf",
|
|
19
|
+
"applyRowChange",
|
|
20
|
+
"isClientFor",
|
|
21
|
+
"isRowsOf",
|
|
22
|
+
"isCallerValue",
|
|
23
|
+
"runMutation",
|
|
24
|
+
"livePreviewMessage",
|
|
25
|
+
"previewMessageOf",
|
|
26
|
+
"originOf",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
describe("entry points", () => {
|
|
30
|
+
it("keeps the binding helpers off the main entry", () => {
|
|
31
|
+
for (const name of BINDING_EXPORTS) expect(main, name).not.toHaveProperty(name)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it("exports every binding helper from the bindings entry", () => {
|
|
35
|
+
for (const name of BINDING_EXPORTS) expect(bindings, name).toHaveProperty(name)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it("maps ./bindings in package.json to the built entry and its types", () => {
|
|
39
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"))
|
|
40
|
+
expect(pkg).toHaveProperty(["exports", "./bindings"], { types: "./dist/bindings.d.ts", import: "./dist/bindings.js" })
|
|
41
|
+
})
|
|
42
|
+
})
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* exactly two states worth distinguishing, and the design turns on telling them apart:
|
|
6
6
|
*
|
|
7
7
|
* nothing registered the project never generated, or the app imported `createClient` from the
|
|
8
|
-
* package instead of from `supatype/client`
|
|
8
|
+
* package instead of from `supatype/generated/client`
|
|
9
9
|
* registered, unknown the column is new since the last push, or reached through an embed
|
|
10
10
|
*
|
|
11
11
|
* Neither is papered over. The previous design fell back to fetching PostgREST's OpenAPI document,
|
|
@@ -36,7 +36,7 @@ describe("parseRowsExactly", () => {
|
|
|
36
36
|
const out = parseRowsExactly('[{"slug":"a","views":9007199254740993}]', "job_post")
|
|
37
37
|
|
|
38
38
|
expect(out.ok).toBe(true)
|
|
39
|
-
expect(out.ok &&
|
|
39
|
+
expect(out.ok && out.value).toEqual([{ slug: "a", views: 9007199254740993n }])
|
|
40
40
|
})
|
|
41
41
|
|
|
42
42
|
it("returns a numeric column as an exact string", () => {
|
|
@@ -44,7 +44,7 @@ describe("parseRowsExactly", () => {
|
|
|
44
44
|
const out = parseRowsExactly('[{"equityPct":0.20}]', "job_post")
|
|
45
45
|
|
|
46
46
|
expect(out.ok).toBe(true)
|
|
47
|
-
expect(out.ok &&
|
|
47
|
+
expect(out.ok && out.value).toEqual([{ equityPct: "0.20" }])
|
|
48
48
|
})
|
|
49
49
|
|
|
50
50
|
it("leaves ordinary columns alone", () => {
|
|
@@ -61,7 +61,7 @@ describe("parseRowsExactly", () => {
|
|
|
61
61
|
expect(out.ok).toBe(false)
|
|
62
62
|
expect(!out.ok && out.columns).toEqual(["views"])
|
|
63
63
|
expect(!out.ok && out.message).toContain("supatype push")
|
|
64
|
-
expect(!out.ok && out.message).toContain('import { createClient } from "./supatype/client"')
|
|
64
|
+
expect(!out.ok && out.message).toContain('import { createClient } from "./supatype/generated/client"')
|
|
65
65
|
})
|
|
66
66
|
|
|
67
67
|
it("says something different when the kinds are registered but the column is not", () => {
|
|
@@ -23,23 +23,21 @@ describe("quoteExactNumbers", () => {
|
|
|
23
23
|
it("keeps a bigint past 2^53 that JSON.parse would round", () => {
|
|
24
24
|
const body = '[{"views":9007199254740993}]'
|
|
25
25
|
// The failure this exists to prevent, stated as an assertion.
|
|
26
|
-
|
|
26
|
+
const lossy = JSON.parse(body)
|
|
27
|
+
expect(lossy).toEqual([{ views: 9007199254740992 }])
|
|
27
28
|
|
|
28
|
-
|
|
29
|
-
expect(parsed[0].views).toBe("9007199254740993")
|
|
29
|
+
expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ views: "9007199254740993" }])
|
|
30
30
|
})
|
|
31
31
|
|
|
32
32
|
it("keeps a high-precision decimal", () => {
|
|
33
33
|
const body = '[{"price":12345678901234567890.1234}]'
|
|
34
|
-
|
|
35
|
-
expect(parsed[0].price).toBe("12345678901234567890.1234")
|
|
34
|
+
expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ price: "12345678901234567890.1234" }])
|
|
36
35
|
})
|
|
37
36
|
|
|
38
37
|
it("keeps trailing zeros on a money amount", () => {
|
|
39
38
|
// Not a value loss, but `19.0000` becoming `19` contradicts the declared `string` type.
|
|
40
39
|
const body = '[{"balance":19.0000}]'
|
|
41
|
-
|
|
42
|
-
expect(parsed[0].balance).toBe("19.0000")
|
|
40
|
+
expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ balance: "19.0000" }])
|
|
43
41
|
})
|
|
44
42
|
|
|
45
43
|
it("leaves columns that are not exact-value kinds alone", () => {
|
|
@@ -49,8 +47,7 @@ describe("quoteExactNumbers", () => {
|
|
|
49
47
|
|
|
50
48
|
it("leaves null alone", () => {
|
|
51
49
|
const body = '[{"views":null}]'
|
|
52
|
-
|
|
53
|
-
expect(parsed[0].views).toBeNull()
|
|
50
|
+
expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ views: null }])
|
|
54
51
|
})
|
|
55
52
|
|
|
56
53
|
it("leaves a value that is already a string alone", () => {
|
|
@@ -66,15 +63,12 @@ describe("quoteExactNumbers", () => {
|
|
|
66
63
|
|
|
67
64
|
it("handles negative and exponent literals", () => {
|
|
68
65
|
const body = '[{"views":-9007199254740993,"price":1.5e10}]'
|
|
69
|
-
|
|
70
|
-
expect(parsed[0].views).toBe("-9007199254740993")
|
|
71
|
-
expect(parsed[0].price).toBe("1.5e10")
|
|
66
|
+
expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual([{ views: "-9007199254740993", price: "1.5e10" }])
|
|
72
67
|
})
|
|
73
68
|
|
|
74
69
|
it("handles a single-object response as well as an array", () => {
|
|
75
70
|
const body = '{"views":9007199254740993}'
|
|
76
|
-
|
|
77
|
-
expect(parsed.views).toBe("9007199254740993")
|
|
71
|
+
expect(JSON.parse(quoteExactNumbers(body, fields))).toEqual({ views: "9007199254740993" })
|
|
78
72
|
})
|
|
79
73
|
|
|
80
74
|
it("does not touch an embedded resource", () => {
|
|
@@ -95,29 +89,24 @@ describe("quoteExactNumbers", () => {
|
|
|
95
89
|
describe("coerceExactKinds", () => {
|
|
96
90
|
it("turns a bigint column into a native bigint", () => {
|
|
97
91
|
const rows = [{ views: "9007199254740993", price: "19.0000" }]
|
|
98
|
-
|
|
99
|
-
expect(
|
|
100
|
-
expect(typeof out[0].views).toBe("bigint")
|
|
92
|
+
// `toEqual` compares with Object.is, so the string "9007199254740993" would not pass.
|
|
93
|
+
expect(coerceExactKinds(rows, fields)).toEqual([{ views: 9007199254740993n, price: "19.0000" }])
|
|
101
94
|
})
|
|
102
95
|
|
|
103
96
|
it("leaves numeric columns as exact strings", () => {
|
|
104
97
|
// `@supatype/types` declares Decimal and Money as `string`. There is no native exact decimal.
|
|
105
98
|
const rows = [{ price: "12345678901234567890.1234" }]
|
|
106
|
-
|
|
107
|
-
expect(out[0].price).toBe("12345678901234567890.1234")
|
|
99
|
+
expect(coerceExactKinds(rows, fields)).toEqual([{ price: "12345678901234567890.1234" }])
|
|
108
100
|
})
|
|
109
101
|
|
|
110
102
|
it("leaves null alone", () => {
|
|
111
|
-
|
|
112
|
-
expect(out[0].views).toBeNull()
|
|
103
|
+
expect(coerceExactKinds([{ views: null }], fields)).toEqual([{ views: null }])
|
|
113
104
|
})
|
|
114
105
|
|
|
115
106
|
it("round-trips the full path, wire bytes to native bigint", () => {
|
|
116
107
|
const wire = '[{"views":9007199254740993,"balance":19.0000}]'
|
|
117
|
-
const rows = JSON.parse(quoteExactNumbers(wire, fields))
|
|
118
|
-
|
|
119
|
-
expect(out[0].views).toBe(9007199254740993n)
|
|
120
|
-
expect(out[0].balance).toBe("19.0000")
|
|
108
|
+
const rows = JSON.parse(quoteExactNumbers(wire, fields))
|
|
109
|
+
expect(coerceExactKinds(rows, fields)).toEqual([{ views: 9007199254740993n, balance: "19.0000" }])
|
|
121
110
|
})
|
|
122
111
|
})
|
|
123
112
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* How the client learns which columns a JSON parser would destroy.
|
|
3
3
|
*
|
|
4
|
-
* The generated `supatype/client.ts` calls `registerFieldKinds` when it is imported, and an app
|
|
4
|
+
* The generated `supatype/generated/client.ts` calls `registerFieldKinds` when it is imported, and an app
|
|
5
5
|
* imports `createClient` from there rather than from this package. So the kinds arrive by the same
|
|
6
6
|
* import that brings the client, compiled into the same bundle, with nothing fetched and nothing
|
|
7
7
|
* read from disk.
|
|
@@ -66,7 +66,7 @@ describe("registerFieldKinds", () => {
|
|
|
66
66
|
})
|
|
67
67
|
|
|
68
68
|
it("ignores a version it does not understand rather than guessing", () => {
|
|
69
|
-
registerFieldKinds({ version: 99, tables: { job_post: { views: "bigint" } } }
|
|
69
|
+
registerFieldKinds({ version: 99, tables: { job_post: { views: "bigint" } } })
|
|
70
70
|
expect(fieldKindsAreRegistered()).toBe(false)
|
|
71
71
|
})
|
|
72
72
|
|
|
@@ -74,7 +74,7 @@ describe("registerFieldKinds", () => {
|
|
|
74
74
|
registerFieldKinds({
|
|
75
75
|
version: 1,
|
|
76
76
|
tables: { job_post: { views: "bigint", weird: "quantum" } },
|
|
77
|
-
}
|
|
77
|
+
})
|
|
78
78
|
expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint" })
|
|
79
79
|
})
|
|
80
80
|
})
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest"
|
|
2
|
+
import { QueryBuilder, MutationBuilder } from "../src/query.js"
|
|
3
|
+
import { fetchCall, fetchReturning, header, type FetchMock } from "./support/fetch-mock.js"
|
|
4
|
+
|
|
5
|
+
const BASE = "http://localhost:18473"
|
|
6
|
+
const PATH = "/rest/v1/posts"
|
|
7
|
+
const HEADERS: Record<string, string> = { apikey: "anon-key", "Content-Type": "application/json" }
|
|
8
|
+
|
|
9
|
+
interface Post { id: string; title: string; tags: string[]; meta: Record<string, unknown> }
|
|
10
|
+
|
|
11
|
+
function stubFetch(): FetchMock {
|
|
12
|
+
const fetch = fetchReturning([])
|
|
13
|
+
vi.stubGlobal("fetch", fetch)
|
|
14
|
+
return fetch
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The filters exactly as PostgREST will read them, after URL decoding. */
|
|
18
|
+
function sentFilters(fetch: FetchMock): string[] {
|
|
19
|
+
return [...new URL(fetchCall(fetch).url).searchParams.entries()].map(([key, value]) => `${key}=${value}`)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe("contains / containedBy: PostgREST operand syntax", () => {
|
|
23
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
24
|
+
|
|
25
|
+
it("an array becomes a Postgres array literal, not JSON", async () => {
|
|
26
|
+
const fetch = stubFetch()
|
|
27
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).contains("tags", ["a", "b"])
|
|
28
|
+
expect(sentFilters(fetch)).toEqual(["tags=cs.{a,b}"])
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it("array elements PostgreSQL would split or misread are quoted and escaped", async () => {
|
|
32
|
+
const fetch = stubFetch()
|
|
33
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).containedBy("tags", [
|
|
34
|
+
"plain",
|
|
35
|
+
"a,b",
|
|
36
|
+
"with space",
|
|
37
|
+
'say "hi"',
|
|
38
|
+
"back\\slash",
|
|
39
|
+
"{brace}",
|
|
40
|
+
"",
|
|
41
|
+
"null",
|
|
42
|
+
7,
|
|
43
|
+
null,
|
|
44
|
+
])
|
|
45
|
+
expect(sentFilters(fetch)).toEqual([
|
|
46
|
+
'tags=cd.{plain,"a,b","with space","say \\"hi\\"","back\\\\slash","{brace}","","null",7,NULL}',
|
|
47
|
+
])
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it("an object becomes JSON, for jsonb columns", async () => {
|
|
51
|
+
const fetch = stubFetch()
|
|
52
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).contains("meta", { tier: "gold" })
|
|
53
|
+
expect(sentFilters(fetch)).toEqual(['meta=cs.{"tier":"gold"}'])
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it("a string is sent as written, for range types and hand-written literals", async () => {
|
|
57
|
+
const fetch = stubFetch()
|
|
58
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).containedBy("during", "[2026-01-01,2026-02-01)")
|
|
59
|
+
expect(sentFilters(fetch)).toEqual(["during=cd.[2026-01-01,2026-02-01)"])
|
|
60
|
+
})
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
describe("in(): values PostgREST would split are quoted", () => {
|
|
64
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
65
|
+
|
|
66
|
+
it("quotes a value holding a comma or parenthesis", async () => {
|
|
67
|
+
const fetch = stubFetch()
|
|
68
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).in("title", ["a,b", "c(d)", "plain", 3])
|
|
69
|
+
expect(sentFilters(fetch)).toEqual(['title=in.("a,b","c(d)",plain,3)'])
|
|
70
|
+
})
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
describe("MutationBuilder: the same filter set as QueryBuilder", () => {
|
|
74
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
75
|
+
|
|
76
|
+
it("update can filter with every query operator", async () => {
|
|
77
|
+
const fetch = stubFetch()
|
|
78
|
+
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "PATCH", { title: "x" })
|
|
79
|
+
.gt("views", 1)
|
|
80
|
+
.gte("likes", 2)
|
|
81
|
+
.lt("rank", 3)
|
|
82
|
+
.lte("score", 4)
|
|
83
|
+
.like("title", "%a%")
|
|
84
|
+
.ilike("body", "%B%")
|
|
85
|
+
.is("deleted_at", null)
|
|
86
|
+
.not("status", "eq", "draft")
|
|
87
|
+
.or("owner.eq.1,owner.eq.2")
|
|
88
|
+
.contains("tags", ["a"])
|
|
89
|
+
.containedBy("meta", { k: 1 })
|
|
90
|
+
.match({ author: "ann", lang: "en" })
|
|
91
|
+
expect(sentFilters(fetch)).toEqual([
|
|
92
|
+
"views=gt.1",
|
|
93
|
+
"likes=gte.2",
|
|
94
|
+
"rank=lt.3",
|
|
95
|
+
"score=lte.4",
|
|
96
|
+
"title=like.%a%",
|
|
97
|
+
"body=ilike.%B%",
|
|
98
|
+
"deleted_at=is.null",
|
|
99
|
+
"status=not.eq.draft",
|
|
100
|
+
"or=(owner.eq.1,owner.eq.2)",
|
|
101
|
+
"tags=cs.{a}",
|
|
102
|
+
'meta=cd.{"k":1}',
|
|
103
|
+
"author=eq.ann",
|
|
104
|
+
"lang=eq.en",
|
|
105
|
+
])
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
it("delete can filter with a range and a pattern", async () => {
|
|
109
|
+
const fetch = stubFetch()
|
|
110
|
+
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").lt("created_at", "2026-01-01").ilike("title", "tmp%")
|
|
111
|
+
expect(fetchCall(fetch).init.method).toBe("DELETE")
|
|
112
|
+
expect(sentFilters(fetch)).toEqual(["created_at=lt.2026-01-01", "title=ilike.tmp%"])
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it("query and mutation produce identical filters for the same chain", async () => {
|
|
116
|
+
const queryFetch = stubFetch()
|
|
117
|
+
await new QueryBuilder<Post>(BASE, PATH, HEADERS).eq("a", 1).neq("b", 2).in("c", [3, 4]).match({ d: 5 })
|
|
118
|
+
const query = sentFilters(queryFetch)
|
|
119
|
+
vi.restoreAllMocks()
|
|
120
|
+
const mutationFetch = stubFetch()
|
|
121
|
+
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("a", 1).neq("b", 2).in("c", [3, 4]).match({ d: 5 })
|
|
122
|
+
expect(sentFilters(mutationFetch)).toEqual(query)
|
|
123
|
+
})
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
describe("MutationBuilder: delete().select() returns the deleted rows", () => {
|
|
127
|
+
beforeEach(() => vi.restoreAllMocks())
|
|
128
|
+
|
|
129
|
+
it("asks PostgREST for the representation once select() is called", async () => {
|
|
130
|
+
const fetch = stubFetch()
|
|
131
|
+
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1").select("id")
|
|
132
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toBe("return=representation")
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it("a plain delete still asks for no body", async () => {
|
|
136
|
+
const fetch = stubFetch()
|
|
137
|
+
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "DELETE").eq("id", "1")
|
|
138
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toBeNull()
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
it("an upsert keeps both preferences, without a stray comma", async () => {
|
|
142
|
+
const fetch = stubFetch()
|
|
143
|
+
await new MutationBuilder<Post>(BASE, PATH, HEADERS, "POST", { id: "1" }, { upsert: true }).select("id")
|
|
144
|
+
expect(header(fetchCall(fetch).init, "Prefer")).toBe("resolution=merge-duplicates,return=representation")
|
|
145
|
+
})
|
|
146
|
+
})
|