@supatype/react 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * `useAuth().signInWithSSO`: SAML single sign-on from a component, beside `signInWithOAuth`. It is
3
+ * the client's own `signInWithSSO`, so what the auth server receives is asserted here.
4
+ */
5
+
6
+ import React from "react"
7
+ import { afterEach, describe, expect, it, vi } from "vitest"
8
+ import { act, create } from "react-test-renderer"
9
+ import { createClient, PKCE_METHOD_S256 } from "@supatype/client"
10
+ import { SupatypeProvider } from "../src/context.js"
11
+ import { useAuth, type UseAuthReturn } from "../src/useAuth.js"
12
+
13
+ const IDP_URL = "https://idp.example/sso?SAMLRequest=abc"
14
+ const PROVIDER_ID = "8a6f1f4e-2b1c-4f5e-9d3a-6b7c8d9e0f1a"
15
+
16
+ const probe: { auth: UseAuthReturn | null } = { auth: null }
17
+
18
+ function Probe(): React.ReactElement {
19
+ probe.auth = useAuth()
20
+ return <p />
21
+ }
22
+
23
+ /** Render a provider over a real client and record the requests it sends. */
24
+ async function renderApp(): Promise<Array<{ url: string; body: unknown }>> {
25
+ const sent: Array<{ url: string; body: unknown }> = []
26
+ vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {
27
+ sent.push({ url: input, body: typeof init?.body === "string" ? JSON.parse(init.body) as unknown : null })
28
+ return new Response(JSON.stringify({ url: IDP_URL }), { status: 200 })
29
+ }))
30
+ const client = createClient({ url: "http://localhost:9999", anonKey: "anon" })
31
+ await act(async () => {
32
+ create(<SupatypeProvider client={client}><Probe /></SupatypeProvider>)
33
+ await client.auth.getSession()
34
+ })
35
+ return sent
36
+ }
37
+
38
+ afterEach(() => {
39
+ vi.unstubAllGlobals()
40
+ probe.auth = null
41
+ })
42
+
43
+ describe("useAuth().signInWithSSO", () => {
44
+ it("starts SSO for an email domain and returns the identity provider's URL", async () => {
45
+ const sent = await renderApp()
46
+ const result = await probe.auth!.signInWithSSO({ domain: "acme.com", options: { skipBrowserRedirect: true } })
47
+
48
+ expect(result).toEqual({ data: { url: IDP_URL }, error: null })
49
+ const sso = sent.find((r) => r.url === "http://localhost:9999/auth/v1/sso")
50
+ expect(sso?.body).toMatchObject({ domain: "acme.com", skip_http_redirect: true, code_challenge_method: PKCE_METHOD_S256 })
51
+ })
52
+
53
+ it("starts SSO for a provider named by its ID", async () => {
54
+ const sent = await renderApp()
55
+ await probe.auth!.signInWithSSO({ providerId: PROVIDER_ID, options: { skipBrowserRedirect: true } })
56
+
57
+ expect(sent.find((r) => r.url.endsWith("/auth/v1/sso"))?.body).toMatchObject({ provider_id: PROVIDER_ID })
58
+ })
59
+
60
+ it("takes a domain or a provider ID, never both", async () => {
61
+ await renderApp()
62
+ const both = (): unknown =>
63
+ // @ts-expect-error: one of domain or providerId, never both
64
+ probe.auth!.signInWithSSO({ domain: "acme.com", providerId: PROVIDER_ID })
65
+ expect(typeof both).toBe("function")
66
+ })
67
+ })
@@ -128,7 +128,8 @@ describe("useMutation requests", () => {
128
128
  const sent = stubFetch()
129
129
  const result = await mutateOnce(operation, data)
130
130
  expect(sent).toEqual([])
131
- expect(result).toEqual({ data: null, error: { message }, count: null })
131
+ expect({ ...result, error: { ...result.error } }).toEqual({ data: null, error: { message }, count: null })
132
+ expect(result.error).toBeInstanceOf(Error)
132
133
  })
133
134
  })
134
135
 
@@ -155,11 +156,20 @@ describe("useQuery requests", () => {
155
156
  })
156
157
  expect(sent).toHaveLength(1)
157
158
  expect(sent[0]!.method).toBe("GET")
159
+ // 0.9.1 release test (FF15): the page went out as `?limit=10` plus a `Range: 20-29` header,
160
+ // which PostgREST refuses with 416. It is one pair of query parameters now.
158
161
  expect(sent[0]!.path).toBe(
159
- "/rest/v1/posts?select=id,title&status=eq.published&order=created_at.desc.nullslast&limit=10",
162
+ "/rest/v1/posts?select=id,title&status=eq.published&order=created_at.desc.nullslast&limit=10&offset=20",
160
163
  )
161
164
  expect(sent[0]!.profile).toBeNull()
162
- expect(sent[0]!.range).toBe("20-29")
165
+ expect(sent[0]!.range).toBeNull()
166
+ })
167
+
168
+ // An offset with no limit was dropped here, while the Vue, Svelte and Solid queries read a page
169
+ // of 100 from it. They share one default now.
170
+ it("reads a page of 100 from an offset with no limit", async () => {
171
+ const sent = await queryOnce({ offset: 20 })
172
+ expect(sent[0]!.path).toBe("/rest/v1/posts?select=*&offset=20&limit=100")
163
173
  })
164
174
 
165
175
  it("reads the draft schema when asked", async () => {
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 0.9.2 release test (N-FF9): `useQuery` reported `loading: false, data: null` on the render where
3
+ * `enabled` turned true, before its effect started the read. An app reads that pair as "done,
4
+ * nothing found": expo-auth wrote the email's local part as the display name and never looked
5
+ * again. No render may show that pair for a key whose answer has not arrived.
6
+ */
7
+
8
+ import React from "react"
9
+ import { afterEach, describe, expect, it, vi } from "vitest"
10
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
11
+ import { createClient, QueryBuilder, type AnyDatabase, type QueryResult } from "@supatype/client"
12
+ import { SupatypeProvider } from "../src/context.js"
13
+ import { useQuery } from "../src/useQuery.js"
14
+
15
+ interface Frame {
16
+ loading: boolean
17
+ data: unknown[] | null
18
+ }
19
+
20
+ const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
21
+
22
+ /** Every read waits until the test settles it. */
23
+ function heldReads(): Array<(result: QueryResult<unknown[]>) => void> {
24
+ const reads: Array<(result: QueryResult<unknown[]>) => void> = []
25
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) =>
26
+ new Promise<QueryResult<unknown[]>>((resolve) => reads.push(resolve)).then(onOk, onRejected),
27
+ )
28
+ return reads
29
+ }
30
+
31
+ function Profile({ userId, frames }: { userId: string | null; frames: Frame[] }): React.ReactElement {
32
+ const { loading, data } = useQuery<AnyDatabase>("profiles", {
33
+ filter: { id: userId },
34
+ enabled: userId !== null,
35
+ })
36
+ frames.push({ loading, data })
37
+ return <p>{loading ? "loading" : JSON.stringify(data)}</p>
38
+ }
39
+
40
+ async function render(frames: Frame[], userId: string | null): Promise<ReactTestRenderer> {
41
+ let tree: ReactTestRenderer | null = null
42
+ await act(async () => {
43
+ tree = create(<SupatypeProvider client={client}><Profile userId={userId} frames={frames} /></SupatypeProvider>)
44
+ })
45
+ if (tree === null) throw new Error("nothing rendered")
46
+ return tree
47
+ }
48
+
49
+ /** True for a frame an app would take as "the read finished and found nothing". */
50
+ const looksDoneAndEmpty = (frame: Frame): boolean => !frame.loading && frame.data === null
51
+
52
+ afterEach(() => {
53
+ vi.restoreAllMocks()
54
+ })
55
+
56
+ describe("useQuery when enabled turns true", () => {
57
+ it("is loading from the first render it is enabled until the rows arrive", async () => {
58
+ const reads = heldReads()
59
+ const frames: Frame[] = []
60
+ const tree = await render(frames, null)
61
+ expect(frames.at(-1)).toEqual({ loading: false, data: null })
62
+
63
+ const enabledFrom = frames.length
64
+ await act(async () => {
65
+ tree.update(<SupatypeProvider client={client}><Profile userId="u1" frames={frames} /></SupatypeProvider>)
66
+ })
67
+ expect(frames.slice(enabledFrom).filter(looksDoneAndEmpty)).toEqual([])
68
+
69
+ const settle = reads.at(-1)
70
+ if (settle === undefined) throw new Error("expected a read once enabled")
71
+ await act(async () => settle({ data: [{ id: "u1", display_name: "Nic" }], error: null, count: null }))
72
+ expect(frames.at(-1)).toEqual({ loading: false, data: [{ id: "u1", display_name: "Nic" }] })
73
+ })
74
+
75
+ it("is not loading while disabled, from the first render", async () => {
76
+ heldReads()
77
+ const frames: Frame[] = []
78
+ await render(frames, null)
79
+ expect(frames.filter((frame) => frame.loading)).toEqual([])
80
+ })
81
+
82
+ it("is loading from the first render when the options change to a key with no answer", async () => {
83
+ const reads = heldReads()
84
+ const frames: Frame[] = []
85
+ const tree = await render(frames, "u1")
86
+ await act(async () => reads.at(-1)?.({ data: [{ id: "u1" }], error: null, count: null }))
87
+
88
+ const changedFrom = frames.length
89
+ await act(async () => {
90
+ tree.update(<SupatypeProvider client={client}><Profile userId="u2" frames={frames} /></SupatypeProvider>)
91
+ })
92
+ expect(frames[changedFrom]?.loading).toBe(true)
93
+ })
94
+ })
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `useQuery` shows the answer to the latest request. When the options change while a read is in
3
+ * flight, the older read can finish last; whatever it brings, rows, a returned error or a throw,
4
+ * must not replace what the newer one showed.
5
+ */
6
+
7
+ import React from "react"
8
+ import { afterEach, describe, expect, it, vi } from "vitest"
9
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
10
+ import { createClient, QueryBuilder, SupatypeError, type AnyDatabase, type QueryResult } from "@supatype/client"
11
+ import { SupatypeProvider } from "../src/context.js"
12
+ import { useQuery } from "../src/useQuery.js"
13
+
14
+ interface PendingRead {
15
+ resolve(result: QueryResult<unknown[]>): void
16
+ reject(reason: unknown): void
17
+ }
18
+
19
+ /** Every read waits until the test settles it, in the order the hook sent them. */
20
+ function heldReads(): PendingRead[] {
21
+ const reads: PendingRead[] = []
22
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) => {
23
+ const answer = new Promise<QueryResult<unknown[]>>((resolve, reject) => reads.push({ resolve, reject }))
24
+ return answer.then(onOk, onRejected)
25
+ })
26
+ return reads
27
+ }
28
+
29
+ function rows(id: number): QueryResult<unknown[]> {
30
+ return { data: [{ id }], error: null, count: null }
31
+ }
32
+
33
+ function Posts({ id }: { id: number }): React.ReactElement {
34
+ const { data, error, loading } = useQuery<AnyDatabase>("posts", { filter: { id } })
35
+ if (loading) return <p>loading</p>
36
+ if (error !== null) return <p>error: {error.message}</p>
37
+ return <p>rows: {JSON.stringify(data)}</p>
38
+ }
39
+
40
+ const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
41
+
42
+ /** Renders for id 1, then id 2, leaving both reads held. */
43
+ async function twoReadsInFlight(): Promise<{ tree: ReactTestRenderer; older: PendingRead; newer: PendingRead }> {
44
+ const reads = heldReads()
45
+ let tree: ReactTestRenderer | null = null
46
+ await act(async () => {
47
+ tree = create(<SupatypeProvider client={client}><Posts id={1} /></SupatypeProvider>)
48
+ })
49
+ if (tree === null) throw new Error("nothing rendered")
50
+ const rendered: ReactTestRenderer = tree
51
+ const older = reads.at(-1)
52
+ await act(async () => {
53
+ rendered.update(<SupatypeProvider client={client}><Posts id={2} /></SupatypeProvider>)
54
+ })
55
+ const newer = reads.at(-1)
56
+ if (older === undefined || newer === undefined || older === newer) throw new Error("expected two reads")
57
+ return { tree: rendered, older, newer }
58
+ }
59
+
60
+ function textOf(tree: ReactTestRenderer): string {
61
+ return tree.root.findByType("p").children.join("")
62
+ }
63
+
64
+ afterEach(() => {
65
+ vi.restoreAllMocks()
66
+ })
67
+
68
+ describe("useQuery when an older read finishes last", () => {
69
+ it("keeps the newer rows over the older rows", async () => {
70
+ const { tree, older, newer } = await twoReadsInFlight()
71
+ await act(async () => newer.resolve(rows(2)))
72
+ await act(async () => older.resolve(rows(1)))
73
+ expect(textOf(tree)).toBe('rows: [{"id":2}]')
74
+ })
75
+
76
+ it("keeps the newer rows over the older read's returned error", async () => {
77
+ const { tree, older, newer } = await twoReadsInFlight()
78
+ await act(async () => newer.resolve(rows(2)))
79
+ await act(async () => older.resolve({ data: null, error: new SupatypeError({ message: "permission denied" }), count: null }))
80
+ expect(textOf(tree)).toBe('rows: [{"id":2}]')
81
+ })
82
+
83
+ it("keeps the newer rows over the older read's throw, still reporting it", async () => {
84
+ const logged = vi.spyOn(console, "error").mockImplementation(() => undefined)
85
+ const thrown = new Error("Supatype client has no API address")
86
+ const { tree, older, newer } = await twoReadsInFlight()
87
+ await act(async () => newer.resolve(rows(2)))
88
+ await act(async () => older.reject(thrown))
89
+ expect(textOf(tree)).toBe('rows: [{"id":2}]')
90
+ expect(logged.mock.calls.filter((call) => call.includes(thrown))).toHaveLength(1)
91
+ })
92
+
93
+ it("stays loading while the newer read is in flight after the older one lands", async () => {
94
+ const { tree, older } = await twoReadsInFlight()
95
+ await act(async () => older.resolve(rows(1)))
96
+ expect(textOf(tree)).toBe("loading")
97
+ })
98
+ })
@@ -0,0 +1,56 @@
1
+ /**
2
+ * `useSubscription` returns the server's reason when it refuses the join.
3
+ *
4
+ * 0.9.2 release test (N-FF5): a join for a table that does not exist is refused, naming the table.
5
+ * The hook only returned CHANNEL_ERROR, so a component could not say what was wrong.
6
+ */
7
+
8
+ import React from "react"
9
+ import { afterEach, describe, expect, it, vi } from "vitest"
10
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
11
+ import { simulateServerMessage, subscribedChannels } from "../../client/tests/helpers/mock-websocket.js"
12
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
13
+
14
+ const shared = vi.hoisted(() => ({ harness: null as SocketSwapHarness | null }))
15
+
16
+ vi.mock("../src/context.js", () => ({
17
+ useSupatype: () => ({ realtime: shared.harness?.realtime }),
18
+ }))
19
+
20
+ import { useSubscription, type UseSubscriptionResult } from "../src/useSubscription.js"
21
+
22
+ const REASON = "table public.notes does not exist: check the table name and schema"
23
+
24
+ let renderer: ReactTestRenderer | null = null
25
+ let latest: UseSubscriptionResult | null = null
26
+
27
+ function Probe(): null {
28
+ latest = useSubscription("notes:team", { table: "notes", callback: () => undefined })
29
+ return null
30
+ }
31
+
32
+ afterEach(() => {
33
+ act(() => renderer?.unmount())
34
+ renderer = null
35
+ latest = null
36
+ shared.harness?.restore()
37
+ })
38
+
39
+ describe("useSubscription's error", () => {
40
+ it("is null while joining and joined, and the server's reason once refused", async () => {
41
+ const harness = createSocketSwapHarness()
42
+ shared.harness = harness
43
+ act(() => {
44
+ renderer = create(<Probe />)
45
+ })
46
+ await act(() => harness.settle())
47
+ expect(latest?.error).toBeNull()
48
+
49
+ const channel = subscribedChannels(harness.socket())[0]
50
+ act(() => {
51
+ simulateServerMessage(harness.socket(), { type: "system", status: "error", message: REASON, channel })
52
+ })
53
+ expect(latest?.status).toBe("CHANNEL_ERROR")
54
+ expect(latest?.error?.message).toBe(REASON)
55
+ })
56
+ })
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The table `useSubscription` joins when the docs' example names a table and no schema.
3
+ *
4
+ * 0.9.1 release test (RB4): `useSubscription("comments:7", { table: "comment" })` joined
5
+ * `comments.comment`, because the client read the schema off the channel name even though the
6
+ * table was given. The hook reported SUBSCRIBED and delivered nothing. The docs say the schema
7
+ * defaults to `public`.
8
+ */
9
+
10
+ import React from "react"
11
+ import { afterEach, describe, expect, it, vi } from "vitest"
12
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
13
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
14
+ import { sentFrames } from "../../client/tests/helpers/mock-websocket.js"
15
+
16
+ const shared = vi.hoisted(() => ({ harness: null as SocketSwapHarness | null }))
17
+
18
+ vi.mock("../src/context.js", () => ({
19
+ useSupatype: () => ({ realtime: shared.harness?.realtime }),
20
+ }))
21
+
22
+ import { useSubscription } from "../src/useSubscription.js"
23
+
24
+ let renderer: ReactTestRenderer | null = null
25
+
26
+ function Comments({ postId }: { postId: string }): null {
27
+ useSubscription(`comments:${postId}`, {
28
+ table: "comment",
29
+ event: "INSERT",
30
+ filter: `post_id=eq.${postId}`,
31
+ callback: () => undefined,
32
+ })
33
+ return null
34
+ }
35
+
36
+ afterEach(() => {
37
+ act(() => renderer?.unmount())
38
+ renderer = null
39
+ shared.harness?.restore()
40
+ shared.harness = null
41
+ })
42
+
43
+ describe("useSubscription with a table and no schema", () => {
44
+ it("joins the table in public, as the docs' example is written", async () => {
45
+ const harness = createSocketSwapHarness()
46
+ shared.harness = harness
47
+ act(() => {
48
+ renderer = create(<Comments postId="7" />)
49
+ })
50
+ await harness.settle()
51
+
52
+ const joins = sentFrames(harness.socket()).filter((frame) => frame["type"] === "subscribe")
53
+ expect(joins).toHaveLength(1)
54
+ expect(joins[0]).toMatchObject({ channel: "comments:7", schema: "public", table: "comment" })
55
+ })
56
+ })