@supatype/client 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +28 -21
- package/.turbo/turbo-typecheck.log +2 -2
- package/dist/auth.d.ts +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/exact-response.d.ts +26 -0
- package/dist/exact-response.d.ts.map +1 -0
- package/dist/exact-response.js +51 -0
- package/dist/exact-response.js.map +1 -0
- package/dist/exact-values.d.ts +50 -0
- package/dist/exact-values.d.ts.map +1 -0
- package/dist/exact-values.js +254 -0
- package/dist/exact-values.js.map +1 -0
- package/dist/field-kinds-registry.d.ts +46 -0
- package/dist/field-kinds-registry.d.ts.map +1 -0
- package/dist/field-kinds-registry.js +51 -0
- package/dist/field-kinds-registry.js.map +1 -0
- package/dist/identity.d.ts +29 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +30 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +17 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +29 -1
- package/dist/index.js.map +1 -1
- package/dist/query-cache.d.ts +1 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js +2 -8
- package/dist/query-cache.js.map +1 -1
- package/dist/query.d.ts +13 -1
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +36 -7
- package/dist/query.js.map +1 -1
- package/dist/realtime.d.ts +61 -3
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +181 -24
- package/dist/realtime.js.map +1 -1
- package/dist/storage.d.ts +12 -0
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +17 -1
- package/dist/storage.js.map +1 -1
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/src/auth.ts +1 -1
- package/src/exact-response.ts +76 -0
- package/src/exact-values.ts +281 -0
- package/src/field-kinds-registry.ts +80 -0
- package/src/identity.ts +43 -0
- package/src/index.ts +54 -1
- package/src/query-cache.ts +3 -10
- package/src/query.ts +41 -7
- package/src/realtime.ts +195 -27
- package/src/storage.ts +17 -1
- package/src/types.ts +28 -0
- package/tests/data-plane-auth.test.ts +6 -4
- package/tests/draft-profile.test.ts +3 -0
- package/tests/exact-response.test.ts +95 -0
- package/tests/exact-values.test.ts +171 -0
- package/tests/field-kinds-registry.test.ts +80 -0
- package/tests/fixtures/models.ts +55 -0
- package/tests/helpers/mock-websocket.ts +70 -0
- package/tests/identity-change.test.ts +120 -0
- package/tests/query-cache.test.ts +14 -8
- package/tests/query.test.ts +1 -0
- package/tests/realtime-exact-values.test.ts +161 -0
- package/tests/realtime-multi-tenant-integration.test.ts +5 -50
- package/tests/realtime-session-auth.test.ts +177 -0
- package/tests/signed-url-absolute.test.ts +84 -0
- package/tests/subscribe-frame.test.ts +102 -0
- package/tests/tsconfig.json +9 -0
- package/tests/types.test.ts +40 -32
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exact-value columns surviving the trip through `JSON.parse`.
|
|
3
|
+
*
|
|
4
|
+
* Postgres holds 9007199254740993 and PostgREST puts those digits on the wire as an unquoted JSON
|
|
5
|
+
* number. `JSON.parse` returns 9007199254740992. The digits are correct right up until the client
|
|
6
|
+
* reads them, so the fix has to happen on the response text, before any parse.
|
|
7
|
+
*
|
|
8
|
+
* Both `money` and `decimal` are NUMERIC and both are declared `string` by the generator, so they
|
|
9
|
+
* share the `numeric` kind here. `bigInt` is declared `bigint` and becomes a native one.
|
|
10
|
+
*/
|
|
11
|
+
import { describe, expect, it } from "vitest"
|
|
12
|
+
import {
|
|
13
|
+
quoteExactNumbers,
|
|
14
|
+
coerceExactKinds,
|
|
15
|
+
findLossyNumbers,
|
|
16
|
+
stringifyWithBigInts,
|
|
17
|
+
type ExactFields,
|
|
18
|
+
} from "../src/exact-values.js"
|
|
19
|
+
|
|
20
|
+
const fields: ExactFields = { views: "bigint", price: "numeric", balance: "numeric" }
|
|
21
|
+
|
|
22
|
+
describe("quoteExactNumbers", () => {
|
|
23
|
+
it("keeps a bigint past 2^53 that JSON.parse would round", () => {
|
|
24
|
+
const body = '[{"views":9007199254740993}]'
|
|
25
|
+
// The failure this exists to prevent, stated as an assertion.
|
|
26
|
+
expect(JSON.parse(body)[0].views).toBe(9007199254740992)
|
|
27
|
+
|
|
28
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: string }]
|
|
29
|
+
expect(parsed[0].views).toBe("9007199254740993")
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it("keeps a high-precision decimal", () => {
|
|
33
|
+
const body = '[{"price":12345678901234567890.1234}]'
|
|
34
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ price: string }]
|
|
35
|
+
expect(parsed[0].price).toBe("12345678901234567890.1234")
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it("keeps trailing zeros on a money amount", () => {
|
|
39
|
+
// Not a value loss, but `19.0000` becoming `19` contradicts the declared `string` type.
|
|
40
|
+
const body = '[{"balance":19.0000}]'
|
|
41
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ balance: string }]
|
|
42
|
+
expect(parsed[0].balance).toBe("19.0000")
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it("leaves columns that are not exact-value kinds alone", () => {
|
|
46
|
+
const body = '[{"hits":42,"rate":1.5}]'
|
|
47
|
+
expect(quoteExactNumbers(body, fields)).toBe(body)
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it("leaves null alone", () => {
|
|
51
|
+
const body = '[{"views":null}]'
|
|
52
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: null }]
|
|
53
|
+
expect(parsed[0].views).toBeNull()
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it("leaves a value that is already a string alone", () => {
|
|
57
|
+
const body = '[{"views":"9007199254740993"}]'
|
|
58
|
+
expect(quoteExactNumbers(body, fields)).toBe(body)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it("does not rewrite a field name that appears inside a string value", () => {
|
|
62
|
+
// The hazard that makes a regex wrong: this is prose, not a column.
|
|
63
|
+
const body = '[{"title":"the \\"views\\":123 column","hits":7}]'
|
|
64
|
+
expect(quoteExactNumbers(body, fields)).toBe(body)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it("handles negative and exponent literals", () => {
|
|
68
|
+
const body = '[{"views":-9007199254740993,"price":1.5e10}]'
|
|
69
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as [{ views: string; price: string }]
|
|
70
|
+
expect(parsed[0].views).toBe("-9007199254740993")
|
|
71
|
+
expect(parsed[0].price).toBe("1.5e10")
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it("handles a single-object response as well as an array", () => {
|
|
75
|
+
const body = '{"views":9007199254740993}'
|
|
76
|
+
const parsed = JSON.parse(quoteExactNumbers(body, fields)) as { views: string }
|
|
77
|
+
expect(parsed.views).toBe("9007199254740993")
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it("does not touch an embedded resource", () => {
|
|
81
|
+
// An embedded table can have a same-named column of a different kind, and the select that
|
|
82
|
+
// produced it is not parsed here. Rewriting it would be a guess, so row level only.
|
|
83
|
+
const body = '[{"views":9007199254740993,"author":{"views":42}}]'
|
|
84
|
+
const out = quoteExactNumbers(body, fields)
|
|
85
|
+
expect(out).toContain('"views":"9007199254740993"')
|
|
86
|
+
expect(out).toContain('"author":{"views":42}')
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it("is a no-op when no exact fields are known", () => {
|
|
90
|
+
const body = '[{"views":9007199254740993}]'
|
|
91
|
+
expect(quoteExactNumbers(body, {})).toBe(body)
|
|
92
|
+
})
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
describe("coerceExactKinds", () => {
|
|
96
|
+
it("turns a bigint column into a native bigint", () => {
|
|
97
|
+
const rows = [{ views: "9007199254740993", price: "19.0000" }]
|
|
98
|
+
const out = coerceExactKinds(rows, fields) as [{ views: bigint; price: string }]
|
|
99
|
+
expect(out[0].views).toBe(9007199254740993n)
|
|
100
|
+
expect(typeof out[0].views).toBe("bigint")
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it("leaves numeric columns as exact strings", () => {
|
|
104
|
+
// `@supatype/types` declares Decimal and Money as `string`. There is no native exact decimal.
|
|
105
|
+
const rows = [{ price: "12345678901234567890.1234" }]
|
|
106
|
+
const out = coerceExactKinds(rows, fields) as [{ price: string }]
|
|
107
|
+
expect(out[0].price).toBe("12345678901234567890.1234")
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it("leaves null alone", () => {
|
|
111
|
+
const out = coerceExactKinds([{ views: null }], fields) as [{ views: null }]
|
|
112
|
+
expect(out[0].views).toBeNull()
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it("round-trips the full path, wire bytes to native bigint", () => {
|
|
116
|
+
const wire = '[{"views":9007199254740993,"balance":19.0000}]'
|
|
117
|
+
const rows = JSON.parse(quoteExactNumbers(wire, fields)) as unknown
|
|
118
|
+
const out = coerceExactKinds(rows, fields) as [{ views: bigint; balance: string }]
|
|
119
|
+
expect(out[0].views).toBe(9007199254740993n)
|
|
120
|
+
expect(out[0].balance).toBe("19.0000")
|
|
121
|
+
})
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
describe("findLossyNumbers", () => {
|
|
125
|
+
it("names a column whose literal will not survive the parse", () => {
|
|
126
|
+
// The safety net for when column metadata could not be loaded. Without it, a failed metadata
|
|
127
|
+
// fetch would quietly restore the corruption this module exists to remove.
|
|
128
|
+
expect(findLossyNumbers('[{"views":9007199254740993}]')).toEqual(["views"])
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
it("says nothing about numbers that round-trip exactly", () => {
|
|
132
|
+
expect(findLossyNumbers('[{"hits":42,"rate":1.5,"edge":9007199254740992}]')).toEqual([])
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it("catches a decimal that loses digits", () => {
|
|
136
|
+
expect(findLossyNumbers('[{"price":12345678901234567890.1234}]')).toEqual(["price"])
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it("does not flag trailing zeros, which lose no value", () => {
|
|
140
|
+
// `19.0000` parsing to `19` is a type-fidelity problem, not a wrong number, and throwing on it
|
|
141
|
+
// would break every project with a money column and no metadata.
|
|
142
|
+
expect(findLossyNumbers('[{"balance":19.0000}]')).toEqual([])
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
it("reports each affected column once", () => {
|
|
146
|
+
const body = '[{"views":9007199254740993},{"views":9007199254740995}]'
|
|
147
|
+
expect(findLossyNumbers(body)).toEqual(["views"])
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
it("ignores digits inside string values", () => {
|
|
151
|
+
expect(findLossyNumbers('[{"title":"id 9007199254740993 here"}]')).toEqual([])
|
|
152
|
+
})
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
describe("stringifyWithBigInts", () => {
|
|
156
|
+
it("serialises a bigint rather than throwing", () => {
|
|
157
|
+
// `JSON.stringify` throws on a bigint, so writing back a row that was just read would fail
|
|
158
|
+
// the moment the generated types started declaring bigint.
|
|
159
|
+
expect(() => JSON.stringify({ views: 1n })).toThrow(TypeError)
|
|
160
|
+
expect(stringifyWithBigInts({ views: 9007199254740993n })).toBe('{"views":"9007199254740993"}')
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
it("leaves everything else as JSON.stringify would", () => {
|
|
164
|
+
const body = { a: 1, b: "x", c: null, d: [1, 2], e: { f: true } }
|
|
165
|
+
expect(stringifyWithBigInts(body)).toBe(JSON.stringify(body))
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
it("handles a bigint nested in an array", () => {
|
|
169
|
+
expect(stringifyWithBigInts({ rows: [{ views: 1n }] })).toBe('{"rows":[{"views":"1"}]}')
|
|
170
|
+
})
|
|
171
|
+
})
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the client learns which columns a JSON parser would destroy.
|
|
3
|
+
*
|
|
4
|
+
* The generated `supatype/client.ts` calls `registerFieldKinds` when it is imported, and an app
|
|
5
|
+
* imports `createClient` from there rather than from this package. So the kinds arrive by the same
|
|
6
|
+
* import that brings the client, compiled into the same bundle, with nothing fetched and nothing
|
|
7
|
+
* read from disk.
|
|
8
|
+
*
|
|
9
|
+
* This replaces reading `field-kinds.json` off the filesystem and falling back to PostgREST's
|
|
10
|
+
* OpenAPI document. The fallback always succeeded, which meant a project that had never generated
|
|
11
|
+
* looked identical to one that had, and the gap it papered over could never be reported.
|
|
12
|
+
*/
|
|
13
|
+
import { describe, expect, it, beforeEach } from "vitest"
|
|
14
|
+
import {
|
|
15
|
+
registerFieldKinds,
|
|
16
|
+
registeredFieldsFor,
|
|
17
|
+
fieldKindsAreRegistered,
|
|
18
|
+
forgetRegisteredFieldKinds,
|
|
19
|
+
} from "../src/field-kinds-registry.js"
|
|
20
|
+
|
|
21
|
+
const document = {
|
|
22
|
+
version: 1 as const,
|
|
23
|
+
tables: {
|
|
24
|
+
job_post: { views: "bigint" as const, equityPct: "numeric" as const },
|
|
25
|
+
landing_page: { price: "numeric" as const },
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
beforeEach(() => {
|
|
30
|
+
forgetRegisteredFieldKinds()
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
describe("registerFieldKinds", () => {
|
|
34
|
+
it("makes a table's exact columns available", () => {
|
|
35
|
+
registerFieldKinds(document)
|
|
36
|
+
expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint", equityPct: "numeric" })
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it("reports nothing for a table the schema does not describe", () => {
|
|
40
|
+
registerFieldKinds(document)
|
|
41
|
+
expect(registeredFieldsFor("unknown_table")).toEqual({})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it("knows whether anything registered at all", () => {
|
|
45
|
+
// The distinction the OpenAPI fallback could never draw: a project that never generated is
|
|
46
|
+
// not the same as a project whose tables happen to have no exact columns.
|
|
47
|
+
expect(fieldKindsAreRegistered()).toBe(false)
|
|
48
|
+
registerFieldKinds(document)
|
|
49
|
+
expect(fieldKindsAreRegistered()).toBe(true)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it("counts an empty schema as registered", () => {
|
|
53
|
+
// A project with no bigInt, decimal or money column still generated. Treating it as absent
|
|
54
|
+
// would make the safety net shout at a project that has nothing to protect.
|
|
55
|
+
registerFieldKinds({ version: 1, tables: {} })
|
|
56
|
+
expect(fieldKindsAreRegistered()).toBe(true)
|
|
57
|
+
expect(registeredFieldsFor("anything")).toEqual({})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it("lets a later registration replace an earlier one", () => {
|
|
61
|
+
// Two clients against two projects in one process, which is ordinary in a monorepo.
|
|
62
|
+
registerFieldKinds(document)
|
|
63
|
+
registerFieldKinds({ version: 1, tables: { other: { total: "numeric" } } })
|
|
64
|
+
expect(registeredFieldsFor("other")).toEqual({ total: "numeric" })
|
|
65
|
+
expect(registeredFieldsFor("job_post")).toEqual({})
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it("ignores a version it does not understand rather than guessing", () => {
|
|
69
|
+
registerFieldKinds({ version: 99, tables: { job_post: { views: "bigint" } } } as never)
|
|
70
|
+
expect(fieldKindsAreRegistered()).toBe(false)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it("drops kinds it does not recognise", () => {
|
|
74
|
+
registerFieldKinds({
|
|
75
|
+
version: 1,
|
|
76
|
+
tables: { job_post: { views: "bigint", weird: "quantum" } },
|
|
77
|
+
} as never)
|
|
78
|
+
expect(registeredFieldsFor("job_post")).toEqual({ views: "bigint" })
|
|
79
|
+
})
|
|
80
|
+
})
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema the test suite declares to `@supatype/client`.
|
|
3
|
+
*
|
|
4
|
+
* Module augmentation is global to a compilation. Once every test file shares one program, a
|
|
5
|
+
* `declare module` block written inside one of them applies to all of them, so a table declared in
|
|
6
|
+
* `types.test.ts` silently constrains `data-plane-auth.test.ts`. That is not a quirk to work
|
|
7
|
+
* around, it is what augmentation is: there is one `SupatypeModels`, and the suite has one schema.
|
|
8
|
+
*
|
|
9
|
+
* So it lives here, covering every table any test queries, rather than in whichever file happened
|
|
10
|
+
* to need it first.
|
|
11
|
+
*
|
|
12
|
+
* Declared with `type` rather than `interface` deliberately. An interface has no implicit index
|
|
13
|
+
* signature, so it does not satisfy `Record<string, unknown>` in `TableDef`, and a fixture written
|
|
14
|
+
* as an interface fails the `AnyDatabase` constraint. Generated output emits type aliases, so this
|
|
15
|
+
* matches what real projects have.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export type Post = {
|
|
19
|
+
id: string
|
|
20
|
+
title: string
|
|
21
|
+
status: "draft" | "published"
|
|
22
|
+
user_id: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type PostInsert = {
|
|
26
|
+
title: string
|
|
27
|
+
status?: "draft" | "published" | undefined
|
|
28
|
+
user_id: string
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type Comment = {
|
|
32
|
+
id: string
|
|
33
|
+
post_id: string
|
|
34
|
+
body: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Singular, and distinct from `posts`: several tests query it by that name. */
|
|
38
|
+
export type SinglePost = {
|
|
39
|
+
id: string
|
|
40
|
+
title: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type Author = {
|
|
44
|
+
id: string
|
|
45
|
+
name: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
declare module "../../src/types.js" {
|
|
49
|
+
interface SupatypeModels {
|
|
50
|
+
posts: { Row: Post; Insert: PostInsert; Update: Partial<PostInsert> }
|
|
51
|
+
comments: { Row: Comment; Insert: Omit<Comment, "id">; Update: Partial<Comment> }
|
|
52
|
+
post: { Row: SinglePost; Insert: Omit<SinglePost, "id">; Update: Partial<SinglePost> }
|
|
53
|
+
authors: { Row: Author; Insert: Omit<Author, "id">; Update: Partial<Author> }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { vi } from "vitest"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A stand-in WebSocket for the realtime suites.
|
|
5
|
+
*
|
|
6
|
+
* Shared because two suites drive the same socket lifecycle, and that lifecycle has just grown a
|
|
7
|
+
* one-at-a-time connect guard and a detach-before-close path. Two copies of the fake would have to
|
|
8
|
+
* learn each of those separately, and the first one to forget would pass while describing a client
|
|
9
|
+
* that no longer exists.
|
|
10
|
+
*
|
|
11
|
+
* Not named `*.test.ts`, so vitest's default include does not collect it as a suite.
|
|
12
|
+
*/
|
|
13
|
+
export interface MockWebSocketInstance {
|
|
14
|
+
url: string
|
|
15
|
+
readyState: number
|
|
16
|
+
onopen: ((event: Event) => void) | null
|
|
17
|
+
onclose: ((event: CloseEvent) => void) | null
|
|
18
|
+
onmessage: ((event: MessageEvent) => void) | null
|
|
19
|
+
onerror: ((event: Event) => void) | null
|
|
20
|
+
send: ReturnType<typeof vi.fn>
|
|
21
|
+
close: ReturnType<typeof vi.fn>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createMockWebSocketClass(): {
|
|
25
|
+
MockWebSocket: typeof WebSocket
|
|
26
|
+
instances: MockWebSocketInstance[]
|
|
27
|
+
} {
|
|
28
|
+
const instances: MockWebSocketInstance[] = []
|
|
29
|
+
|
|
30
|
+
class MockWebSocket {
|
|
31
|
+
static OPEN = 1
|
|
32
|
+
static CONNECTING = 0
|
|
33
|
+
static CLOSED = 3
|
|
34
|
+
|
|
35
|
+
url: string
|
|
36
|
+
readyState = 0
|
|
37
|
+
onopen: ((event: Event) => void) | null = null
|
|
38
|
+
onclose: ((event: CloseEvent) => void) | null = null
|
|
39
|
+
onmessage: ((event: MessageEvent) => void) | null = null
|
|
40
|
+
onerror: ((event: Event) => void) | null = null
|
|
41
|
+
send = vi.fn()
|
|
42
|
+
close = vi.fn()
|
|
43
|
+
|
|
44
|
+
constructor(url: string) {
|
|
45
|
+
this.url = url
|
|
46
|
+
instances.push(this as unknown as MockWebSocketInstance)
|
|
47
|
+
|
|
48
|
+
// Auto-open after a microtask
|
|
49
|
+
queueMicrotask(() => {
|
|
50
|
+
this.readyState = 1 // OPEN
|
|
51
|
+
this.onopen?.({} as Event)
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return { MockWebSocket: MockWebSocket as unknown as typeof WebSocket, instances }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Simulate a server message arriving on a WebSocket instance. */
|
|
60
|
+
export function simulateServerMessage(
|
|
61
|
+
ws: MockWebSocketInstance,
|
|
62
|
+
msg: Record<string, unknown>,
|
|
63
|
+
): void {
|
|
64
|
+
ws.onmessage?.({ data: JSON.stringify(msg) } as MessageEvent)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The token a socket was opened with, read back out of its URL. */
|
|
68
|
+
export function tokenOf(ws: MockWebSocketInstance): string | null {
|
|
69
|
+
return new URL(ws.url.replace(/^ws/, "http")).searchParams.get("token")
|
|
70
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which auth transitions a data hook should re-run on.
|
|
3
|
+
*
|
|
4
|
+
* The bindings' queries fetch once when their component mounts, which is before anybody has signed
|
|
5
|
+
* in, so on a table guarded by a logged-in policy that fetch reads nothing and the view stayed
|
|
6
|
+
* empty until something else called refetch. They now re-run on identity change, and this is the
|
|
7
|
+
* narrowing that makes that affordable: `onAuthStateChange` also fires at registration and on every
|
|
8
|
+
* token refresh, and re-running on those would double every mount's fetch and then refetch on a
|
|
9
|
+
* timer for as long as the page stayed open.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { describe, it, expect, vi } from "vitest"
|
|
13
|
+
import { onIdentityChange, type IdentitySource } from "../src/identity.js"
|
|
14
|
+
import type { AuthChangeEvent, Session } from "../src/types.js"
|
|
15
|
+
|
|
16
|
+
/** An auth client stand-in whose emissions the test drives by hand. */
|
|
17
|
+
function fakeAuth(): {
|
|
18
|
+
source: IdentitySource
|
|
19
|
+
emit: (event: AuthChangeEvent, session: Session | null) => void
|
|
20
|
+
unsubscribed: () => number
|
|
21
|
+
} {
|
|
22
|
+
let listener: ((event: AuthChangeEvent, session: Session | null) => void) | null = null
|
|
23
|
+
let unsubscribes = 0
|
|
24
|
+
return {
|
|
25
|
+
source: {
|
|
26
|
+
onAuthStateChange(callback) {
|
|
27
|
+
listener = callback
|
|
28
|
+
return { data: { subscription: { unsubscribe: () => { unsubscribes += 1 } } } }
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
emit: (event, session) => listener?.(event, session),
|
|
32
|
+
unsubscribed: () => unsubscribes,
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function sessionFor(userId: string, accessToken = "token"): Session {
|
|
37
|
+
return {
|
|
38
|
+
accessToken,
|
|
39
|
+
tokenType: "bearer",
|
|
40
|
+
expiresIn: 3600,
|
|
41
|
+
refreshToken: "refresh",
|
|
42
|
+
user: {
|
|
43
|
+
id: userId,
|
|
44
|
+
email: `${userId}@example.com`,
|
|
45
|
+
role: "authenticated",
|
|
46
|
+
appMetadata: {},
|
|
47
|
+
userMetadata: {},
|
|
48
|
+
createdAt: "2024-01-01T00:00:00Z",
|
|
49
|
+
updatedAt: "2024-01-01T00:00:00Z",
|
|
50
|
+
},
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
describe("onIdentityChange", () => {
|
|
55
|
+
it("does not fire on the emission onAuthStateChange makes at registration", () => {
|
|
56
|
+
const auth = fakeAuth()
|
|
57
|
+
const onChange = vi.fn()
|
|
58
|
+
onIdentityChange(auth.source, onChange)
|
|
59
|
+
|
|
60
|
+
// AuthClient calls back synchronously when a listener registers. Treating that as a change
|
|
61
|
+
// would refetch immediately after the fetch the caller has already made on mount.
|
|
62
|
+
auth.emit("SIGNED_OUT", null)
|
|
63
|
+
|
|
64
|
+
expect(onChange).not.toHaveBeenCalled()
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it("fires when a signed-out page signs in", () => {
|
|
68
|
+
const auth = fakeAuth()
|
|
69
|
+
const onChange = vi.fn()
|
|
70
|
+
onIdentityChange(auth.source, onChange)
|
|
71
|
+
auth.emit("SIGNED_OUT", null)
|
|
72
|
+
|
|
73
|
+
auth.emit("SIGNED_IN", sessionFor("user-1"))
|
|
74
|
+
|
|
75
|
+
expect(onChange).toHaveBeenCalledTimes(1)
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it("does not fire on a token refresh for the same user", () => {
|
|
79
|
+
const auth = fakeAuth()
|
|
80
|
+
const onChange = vi.fn()
|
|
81
|
+
onIdentityChange(auth.source, onChange)
|
|
82
|
+
auth.emit("SIGNED_IN", sessionFor("user-1", "first"))
|
|
83
|
+
|
|
84
|
+
auth.emit("TOKEN_REFRESHED", sessionFor("user-1", "second"))
|
|
85
|
+
auth.emit("TOKEN_REFRESHED", sessionFor("user-1", "third"))
|
|
86
|
+
|
|
87
|
+
expect(onChange).not.toHaveBeenCalled()
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it("fires on sign out", () => {
|
|
91
|
+
const auth = fakeAuth()
|
|
92
|
+
const onChange = vi.fn()
|
|
93
|
+
onIdentityChange(auth.source, onChange)
|
|
94
|
+
auth.emit("SIGNED_IN", sessionFor("user-1"))
|
|
95
|
+
|
|
96
|
+
auth.emit("SIGNED_OUT", null)
|
|
97
|
+
|
|
98
|
+
expect(onChange).toHaveBeenCalledTimes(1)
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
it("fires when one user replaces another", () => {
|
|
102
|
+
const auth = fakeAuth()
|
|
103
|
+
const onChange = vi.fn()
|
|
104
|
+
onIdentityChange(auth.source, onChange)
|
|
105
|
+
auth.emit("SIGNED_IN", sessionFor("user-1"))
|
|
106
|
+
|
|
107
|
+
auth.emit("SIGNED_IN", sessionFor("user-2"))
|
|
108
|
+
|
|
109
|
+
expect(onChange).toHaveBeenCalledTimes(1)
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
it("unsubscribes the underlying listener when torn down", () => {
|
|
113
|
+
const auth = fakeAuth()
|
|
114
|
+
const stop = onIdentityChange(auth.source, vi.fn())
|
|
115
|
+
|
|
116
|
+
stop()
|
|
117
|
+
|
|
118
|
+
expect(auth.unsubscribed()).toBe(1)
|
|
119
|
+
})
|
|
120
|
+
})
|
|
@@ -69,14 +69,20 @@ describe("QueryBuilder.cache", () => {
|
|
|
69
69
|
cache,
|
|
70
70
|
).cache({ ttl: 60_000 })
|
|
71
71
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
expect(
|
|
72
|
+
// Counted per table URL rather than across every request, because the client also fetches the
|
|
73
|
+
// project's column types once so it can keep bigInt, decimal and money columns exact. That
|
|
74
|
+
// request is cached per project and is not what this test is about.
|
|
75
|
+
const tableCalls = (): number =>
|
|
76
|
+
fetchMock.mock.calls.filter((call) => String(call[0]).includes("/rest/v1/posts")).length
|
|
77
|
+
|
|
78
|
+
const r1 = await qb
|
|
79
|
+
expect(r1.data).toEqual([{ id: 1 }])
|
|
80
|
+
expect(tableCalls()).toBe(1)
|
|
81
|
+
|
|
82
|
+
const r2 = await qb
|
|
83
|
+
expect(r2.data).toEqual([{ id: 1 }])
|
|
84
|
+
expect(r2.meta?.cacheStatus).toBe("HIT")
|
|
85
|
+
expect(tableCalls()).toBe(1)
|
|
80
86
|
})
|
|
81
87
|
|
|
82
88
|
it("sends X-Supatype-Cache when server: true", async () => {
|
package/tests/query.test.ts
CHANGED