@supatype/react 0.9.1 → 0.10.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.
Files changed (43) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +26 -14
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +31 -1
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/useAuth.d.ts.map +1 -1
  10. package/dist/useAuth.js +18 -13
  11. package/dist/useAuth.js.map +1 -1
  12. package/dist/useChannel.d.ts +37 -0
  13. package/dist/useChannel.d.ts.map +1 -0
  14. package/dist/useChannel.js +48 -0
  15. package/dist/useChannel.js.map +1 -0
  16. package/dist/useQuery.d.ts +1 -1
  17. package/dist/useQuery.d.ts.map +1 -1
  18. package/dist/useQuery.js +24 -14
  19. package/dist/useQuery.js.map +1 -1
  20. package/dist/useRealtimeConnection.d.ts +13 -0
  21. package/dist/useRealtimeConnection.d.ts.map +1 -0
  22. package/dist/useRealtimeConnection.js +13 -0
  23. package/dist/useRealtimeConnection.js.map +1 -0
  24. package/dist/useSubscription.d.ts +5 -0
  25. package/dist/useSubscription.d.ts.map +1 -1
  26. package/dist/useSubscription.js +8 -3
  27. package/dist/useSubscription.js.map +1 -1
  28. package/package.json +3 -3
  29. package/src/index.ts +6 -0
  30. package/src/useAuth.ts +22 -13
  31. package/src/useChannel.ts +77 -0
  32. package/src/useQuery.ts +30 -16
  33. package/src/useRealtimeConnection.ts +26 -0
  34. package/src/useSubscription.ts +13 -3
  35. package/tests/stable-callbacks.test.tsx +123 -0
  36. package/tests/useChannel-private.test.tsx +77 -0
  37. package/tests/useChannel-typed-name.test.ts +14 -0
  38. package/tests/useChannel.test.tsx +121 -0
  39. package/tests/useMutation-requests.test.tsx +11 -2
  40. package/tests/useQuery-enabled.test.tsx +94 -0
  41. package/tests/useSubscription-error.test.tsx +56 -0
  42. package/tests/useSubscription-schema.test.tsx +56 -0
  43. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,77 @@
1
+ "use client"
2
+
3
+ import { useEffect, useState, type DependencyList } from "react"
4
+ import type { ChannelActionRefusal, ChannelName, ChannelOptions, ChannelStatus, ChannelSubscription } from "@supatype/client"
5
+ import { useSupatype } from "./context.js"
6
+ import { useRealtimeConnection, type UseRealtimeConnectionResult } from "./useRealtimeConnection.js"
7
+
8
+ export interface UseChannelResult extends UseRealtimeConnectionResult {
9
+ /** This channel's join status. */
10
+ status: ChannelStatus
11
+ /** Why the server refused the join, while the status is CHANNEL_ERROR; null otherwise. */
12
+ error: Error | null
13
+ /**
14
+ * The latest broadcast, presence track or payload the server refused on this channel, or null.
15
+ * The channel stays joined (`status` does not change); this is how the app learns a send went
16
+ * nowhere. Cleared when the channel changes.
17
+ */
18
+ refusal: ChannelActionRefusal | null
19
+ }
20
+
21
+ interface ChannelState {
22
+ status: ChannelStatus
23
+ error: Error | null
24
+ refusal: ChannelActionRefusal | null
25
+ }
26
+
27
+ const JOINING: ChannelState = { status: "SUBSCRIBING", error: null, refusal: null }
28
+
29
+ /**
30
+ * Join one channel and register whatever listeners `setup` adds to it: row changes, presence and
31
+ * broadcast together, which `useSubscription` (one row listener) cannot do.
32
+ *
33
+ * `setup` receives the channel before it is subscribed and must only add listeners; the hook
34
+ * subscribes, and unsubscribes when the component unmounts or `name` or `deps` change. Like
35
+ * `useEffect`, `setup` runs again only when `deps` change, so list whatever it reads.
36
+ *
37
+ * `options.private` asks for a private channel (a schema `Channel` declaration guards it): see
38
+ * `ChannelOptions`. A refused or withdrawn join shows as `error`, a `RealtimeChannelError` whose `reason`
39
+ * says why.
40
+ *
41
+ * @example
42
+ * ```tsx
43
+ * const { status, isConnected } = useChannel<Bid>("auction:42", (channel) => {
44
+ * channel.on("postgres_changes", { event: "INSERT", table: "bid" }, (p) => addBid(p.new))
45
+ * channel.onBroadcast("outbid", (p) => notify(p))
46
+ * }, [addBid, notify])
47
+ * ```
48
+ */
49
+ export function useChannel<TRow = Record<string, unknown>>(
50
+ name: ChannelName,
51
+ setup: (channel: ChannelSubscription<TRow>) => void,
52
+ deps: DependencyList = [],
53
+ options: ChannelOptions = {},
54
+ ): UseChannelResult {
55
+ const { realtime } = useSupatype()
56
+ const [state, setState] = useState<ChannelState>(JOINING)
57
+ const connection = useRealtimeConnection()
58
+ const isPrivate = options.private === true
59
+
60
+ useEffect(() => {
61
+ setState(JOINING)
62
+ const channel = realtime.channel<TRow>(name, { private: isPrivate })
63
+ setup(channel)
64
+ channel.onRefused((refusal) => setState((prev) => ({ ...prev, refusal })))
65
+ channel.subscribe((status, err) => {
66
+ const error = err ?? null
67
+ setState((prev) => (prev.status === status && prev.error === error ? prev : { ...prev, status, error }))
68
+ })
69
+ return () => {
70
+ channel.unsubscribe()
71
+ }
72
+ // `setup` is read through `deps`, as with useEffect.
73
+ // eslint-disable-next-line react-hooks/exhaustive-deps
74
+ }, [realtime, name, isPrivate, ...deps])
75
+
76
+ return { ...state, ...connection }
77
+ }
package/src/useQuery.ts CHANGED
@@ -4,7 +4,7 @@ import { useState, useEffect, useCallback, useRef } from "react"
4
4
  import type { AnyClient, AnyDatabase, AugmentedDatabase, SupatypeError, QueryCacheOptions } from "@supatype/client"
5
5
  import { onIdentityChange } from "@supatype/client"
6
6
  import { useSupatype } from "./context.js"
7
- import { isRowsOf, reportThrown } from "@supatype/client/bindings"
7
+ import { isRowsOf, reportThrown, withPage } from "@supatype/client/bindings"
8
8
 
9
9
  export interface UseQueryOptions {
10
10
  /** PostgREST select expression (default: '*') */
@@ -15,7 +15,7 @@ export interface UseQueryOptions {
15
15
  order?: { column: string; ascending?: boolean | undefined } | undefined
16
16
  /** Maximum number of rows to return */
17
17
  limit?: number | undefined
18
- /** Row offset (for pagination) */
18
+ /** Row offset (for pagination). With no `limit`, a page of 100 rows is read from it. */
19
19
  offset?: number | undefined
20
20
  /** Set to false to skip the query (useful for conditional fetching) */
21
21
  enabled?: boolean | undefined
@@ -69,11 +69,12 @@ export function useQuery<
69
69
  options?: UseQueryOptions | undefined,
70
70
  ): UseQueryResult<TRow> {
71
71
  const client = useSupatype<TDatabase>()
72
- const [state, setState] = useState<RowsState<TRow>>({ data: null, error: null, count: null, loading: true })
72
+ const [state, setState] = useState<RowsState<TRow>>({ data: null, error: null, count: null, loading: false, answered: null })
73
73
  const latest = useRef(0)
74
74
 
75
- // Stable reference to options for the effect dep
76
- const optionsJson = JSON.stringify(options)
75
+ // Which read this render asks for. A string, so a caller's inline options object, new on every
76
+ // render, does not count as a new read.
77
+ const key = JSON.stringify([table, options])
77
78
 
78
79
  const execute = useCallback(async () => {
79
80
  const request = ++latest.current
@@ -87,14 +88,20 @@ export function useQuery<
87
88
  return
88
89
  }
89
90
  show({ loading: true })
90
- show(await settledRows<TRow>(client as AnyClient, table, options))
91
- // eslint-disable-next-line react-hooks/exhaustive-deps
92
- }, [client, table, optionsJson])
91
+ show({ ...(await settledRows<TRow>(client as AnyClient, table, options)), answered: key })
92
+ // `key` stands in for `table` and `options`: a caller's inline object is new on every render,
93
+ // and depending on it would read again on every render.
94
+ }, [client, key])
93
95
 
94
96
  useRunAndRefetch(execute, options?.refetchInterval)
95
97
  useRerunOnIdentityChange(client.auth, execute)
96
98
 
97
- return { ...state, refetch: () => void execute() }
99
+ // Changes only when the query does, so an app can list it as an effect dependency. 0.9.1 release
100
+ // test (RB10): a new function each render made `useEffect(() => refetch(), [refetch])` loop.
101
+ const refetch = useCallback(() => void execute(), [execute])
102
+
103
+ const { data, error, count } = state
104
+ return { data, error, count, loading: isLoading(state, key, options?.enabled), refetch }
98
105
  }
99
106
 
100
107
  /** What the hook shows: the latest request's answer, and whether one is in flight. */
@@ -103,6 +110,18 @@ interface RowsState<TRow> {
103
110
  error: SupatypeError | null
104
111
  count: number | null
105
112
  loading: boolean
113
+ /** The key of the read whose answer `data` holds, or null before any has arrived. */
114
+ answered: string | null
115
+ }
116
+
117
+ /**
118
+ * Loading, worked out while rendering rather than set by the effect that starts the read. 0.9.2
119
+ * release test (N-FF9): set by the effect, the render where `enabled` turned true, or the options
120
+ * changed, still said `loading: false` with no rows for the new key, which an app reads as "done,
121
+ * nothing found". Until the answer for this key arrives, an enabled query is loading.
122
+ */
123
+ function isLoading<TRow>(state: RowsState<TRow>, key: string, enabled: boolean | undefined): boolean {
124
+ return enabled !== false && (state.loading || state.answered !== key)
106
125
  }
107
126
 
108
127
  /**
@@ -113,7 +132,7 @@ async function settledRows<TRow>(
113
132
  client: AnyClient,
114
133
  table: string,
115
134
  options: UseQueryOptions | undefined,
116
- ): Promise<RowsState<TRow>> {
135
+ ): Promise<Omit<RowsState<TRow>, "answered">> {
117
136
  try {
118
137
  const result = await readRows(client, table, options)
119
138
  return { data: isRowsOf<TRow>(result.data) ? result.data : null, error: result.error, count: result.count, loading: false }
@@ -161,11 +180,6 @@ function readRows(client: AnyClient, table: string, options: UseQueryOptions | u
161
180
  if (options?.order !== undefined) {
162
181
  query = query.order(options.order.column, { ascending: options.order.ascending ?? true })
163
182
  }
164
- if (options?.limit !== undefined) {
165
- query = query.limit(options.limit)
166
- }
167
- if (options?.offset !== undefined && options.limit !== undefined) {
168
- query = query.range(options.offset, options.offset + options.limit - 1)
169
- }
183
+ query = withPage(query, options)
170
184
  return options?.cache !== undefined ? query.cache(options.cache) : query
171
185
  }
@@ -0,0 +1,26 @@
1
+ "use client"
2
+
3
+ import { useSyncExternalStore } from "react"
4
+ import type { RealtimeConnectionState } from "@supatype/client"
5
+ import { useSupatype } from "./context.js"
6
+
7
+ export interface UseRealtimeConnectionResult {
8
+ /** True while the realtime socket is open. A channel may still be waiting on its join. */
9
+ isConnected: boolean
10
+ /** "connecting" covers the first connect, a reconnect after a drop, and the sign-in swap. */
11
+ connectionState: RealtimeConnectionState
12
+ }
13
+
14
+ /**
15
+ * The realtime socket's own state, which no channel status reports: a drop and a first connect both
16
+ * read SUBSCRIBING on a channel.
17
+ */
18
+ export function useRealtimeConnection(): UseRealtimeConnectionResult {
19
+ const { realtime } = useSupatype()
20
+ const connectionState = useSyncExternalStore(
21
+ (notify) => realtime.onConnectionChange(notify),
22
+ () => realtime.connectionState,
23
+ (): RealtimeConnectionState => "disconnected",
24
+ )
25
+ return { isConnected: connectionState === "connected", connectionState }
26
+ }
@@ -22,6 +22,11 @@ export interface UseSubscriptionOptions<TRow> {
22
22
  export interface UseSubscriptionResult {
23
23
  /** Current subscription status. */
24
24
  status: SubscriptionStatus
25
+ /**
26
+ * Why the server refused the subscription, such as a table that does not exist, while the status
27
+ * is CHANNEL_ERROR; null otherwise.
28
+ */
29
+ error: Error | null
25
30
  }
26
31
 
27
32
  /**
@@ -41,7 +46,7 @@ export function useSubscription<TRow = Record<string, unknown>>(
41
46
  opts: UseSubscriptionOptions<TRow>,
42
47
  ): UseSubscriptionResult {
43
48
  const client = useSupatype()
44
- const [status, setStatus] = useState<SubscriptionStatus>("SUBSCRIBING")
49
+ const [result, setResult] = useState<UseSubscriptionResult>({ status: "SUBSCRIBING", error: null })
45
50
 
46
51
  // Stable ref so the effect doesn't re-run when the callback reference changes
47
52
  const callbackRef = useRef(opts.callback)
@@ -60,7 +65,12 @@ export function useSubscription<TRow = Record<string, unknown>>(
60
65
  },
61
66
  (payload) => callbackRef.current(payload),
62
67
  )
63
- .subscribe((s) => setStatus(s))
68
+ // The reason travels with the status it explains (N-FF5), so the two never disagree. The same
69
+ // answer keeps the same object, so React bails out of a render as it did for a bare status.
70
+ .subscribe((status, err) => {
71
+ const error = err ?? null
72
+ setResult((prev) => (prev.status === status && prev.error === error ? prev : { status, error }))
73
+ })
64
74
 
65
75
  return () => {
66
76
  channel.unsubscribe()
@@ -68,5 +78,5 @@ export function useSubscription<TRow = Record<string, unknown>>(
68
78
  // eslint-disable-next-line react-hooks/exhaustive-deps
69
79
  }, [client, channelName, opts.event, opts.schema, opts.table, opts.filter])
70
80
 
71
- return { status }
81
+ return result
72
82
  }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The functions a hook returns keep their identity across renders, as React's own hooks do, so an
3
+ * app can list them as effect dependencies.
4
+ *
5
+ * 0.9.1 release test (RB10): `useQuery` built a new `refetch` on every render, and the expo-auth
6
+ * example's `useEffect(() => { void refetch() }, [refetch])` looped, sending thousands of requests
7
+ * a second until React stopped it with "Maximum update depth exceeded".
8
+ */
9
+
10
+ import React, { useEffect } from "react"
11
+ import { afterEach, describe, expect, it, vi } from "vitest"
12
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
13
+ import { createClient, QueryBuilder, type AnyDatabase, type QueryResult } from "@supatype/client"
14
+ import { SupatypeProvider } from "../src/context.js"
15
+ import { useQuery, type UseQueryResult } from "../src/useQuery.js"
16
+ import { useAuth, type UseAuthReturn } from "../src/useAuth.js"
17
+
18
+ /** Every read answers at once with one row; returns how many were sent. */
19
+ function countedReads(): { count: () => number } {
20
+ let reads = 0
21
+ vi.spyOn(QueryBuilder.prototype, "then").mockImplementation((onOk, onRejected) => {
22
+ reads += 1
23
+ return Promise.resolve<QueryResult<unknown[]>>({ data: [{ id: reads }], error: null, count: null }).then(onOk, onRejected)
24
+ })
25
+ return { count: () => reads }
26
+ }
27
+
28
+ const client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
29
+
30
+ /** Every `refetch` the hook handed out, one per render. */
31
+ const refetches: Array<UseQueryResult<unknown>["refetch"]> = []
32
+
33
+ function Posts({ id, label }: { id: number; label: string }): React.ReactElement {
34
+ const { data, refetch } = useQuery<AnyDatabase>("posts", { filter: { id } })
35
+ refetches.push(refetch)
36
+ return <p>{label}: {JSON.stringify(data)}</p>
37
+ }
38
+
39
+ /** Effect runs past this many stop refetching, so a loop ends instead of exhausting the heap. */
40
+ const EFFECT_CAP = 20
41
+
42
+ /** How many times `RefetchOnChange`'s effect has run. */
43
+ const effectRuns = { count: 0 }
44
+
45
+ /** The expo-auth pattern: refetch whenever `refetch` (or anything else listed) changes. */
46
+ function RefetchOnChange({ author }: { author: string }): React.ReactElement {
47
+ const { data, refetch } = useQuery<AnyDatabase>("profiles", { filter: { author } })
48
+ useEffect(() => {
49
+ effectRuns.count += 1
50
+ if (effectRuns.count <= EFFECT_CAP) refetch()
51
+ }, [author, refetch])
52
+ return <p>{JSON.stringify(data)}</p>
53
+ }
54
+
55
+ async function mount(element: React.ReactElement): Promise<ReactTestRenderer> {
56
+ let tree: ReactTestRenderer | null = null
57
+ await act(async () => {
58
+ tree = create(<SupatypeProvider client={client}>{element}</SupatypeProvider>)
59
+ })
60
+ if (tree === null) throw new Error("nothing rendered")
61
+ return tree
62
+ }
63
+
64
+ afterEach(() => {
65
+ vi.restoreAllMocks()
66
+ refetches.length = 0
67
+ effectRuns.count = 0
68
+ })
69
+
70
+ describe("useQuery's refetch", () => {
71
+ it("is the same function on every render while the query is unchanged", async () => {
72
+ countedReads()
73
+ const tree = await mount(<Posts id={1} label="first" />)
74
+ await act(async () => {
75
+ tree.update(<SupatypeProvider client={client}><Posts id={1} label="second" /></SupatypeProvider>)
76
+ })
77
+ expect(refetches.length).toBeGreaterThan(1)
78
+ expect(new Set(refetches).size).toBe(1)
79
+ })
80
+
81
+ it("is a new function once the query it runs changes", async () => {
82
+ countedReads()
83
+ const tree = await mount(<Posts id={1} label="posts" />)
84
+ const before = refetches.at(-1)
85
+ await act(async () => {
86
+ tree.update(<SupatypeProvider client={client}><Posts id={2} label="posts" /></SupatypeProvider>)
87
+ })
88
+ expect(refetches.at(-1)).not.toBe(before)
89
+ })
90
+
91
+ it("can be an effect dependency without the effect looping", async () => {
92
+ const reads = countedReads()
93
+ const errors = vi.spyOn(console, "error").mockImplementation(() => undefined)
94
+ await mount(<RefetchOnChange author="ada" />)
95
+ expect(effectRuns.count).toBe(1)
96
+ // One read from the hook on mount and one from the app's effect.
97
+ expect(reads.count()).toBe(2)
98
+ expect(errors).not.toHaveBeenCalled()
99
+ })
100
+ })
101
+
102
+ describe("useAuth's methods", () => {
103
+ it("are the same functions on every render", async () => {
104
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 })))
105
+ const seen: UseAuthReturn[] = []
106
+ function Probe({ label }: { label: string }): React.ReactElement {
107
+ const auth = useAuth()
108
+ seen.push(auth)
109
+ return <p>{label}</p>
110
+ }
111
+ const tree = await mount(<Probe label="first" />)
112
+ await act(async () => {
113
+ tree.update(<SupatypeProvider client={client}><Probe label="second" /></SupatypeProvider>)
114
+ })
115
+ vi.unstubAllGlobals()
116
+ const first = seen[0]
117
+ const last = seen.at(-1)
118
+ if (first === undefined || last === undefined || first === last) throw new Error("expected two renders")
119
+ for (const name of ["signUp", "signIn", "signInWithOAuth", "signInWithSSO", "signInWithOtp", "signOut"] as const) {
120
+ expect(last[name], name).toBe(first[name])
121
+ }
122
+ })
123
+ })
@@ -0,0 +1,77 @@
1
+ /** `useChannel(name, setup, deps, { private: true })` joins as private and hands back the typed refusal. */
2
+
3
+ import React from "react"
4
+ import { afterEach, describe, expect, it, vi } from "vitest"
5
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
6
+ import { isRealtimeChannelError } from "@supatype/client"
7
+ import { ackNewestJoin, simulateServerMessage, subscribeFrames } from "../../client/tests/helpers/mock-websocket.js"
8
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
9
+
10
+ const shared = vi.hoisted(() => ({ harness: null as SocketSwapHarness | null }))
11
+
12
+ vi.mock("../src/context.js", () => ({
13
+ useSupatype: () => ({ realtime: shared.harness?.realtime }),
14
+ }))
15
+
16
+ import { useChannel, type UseChannelResult } from "../src/useChannel.js"
17
+
18
+ let renderer: ReactTestRenderer | null = null
19
+ let latest: UseChannelResult | null = null
20
+
21
+ function Probe(): null {
22
+ latest = useChannel("lot:42", () => undefined, [], { private: true })
23
+ return null
24
+ }
25
+
26
+ afterEach(() => {
27
+ act(() => renderer?.unmount())
28
+ renderer = null
29
+ latest = null
30
+ shared.harness?.restore()
31
+ })
32
+
33
+ async function mount(): Promise<SocketSwapHarness> {
34
+ const harness = createSocketSwapHarness()
35
+ shared.harness = harness
36
+ act(() => {
37
+ renderer = create(<Probe />)
38
+ })
39
+ await act(() => harness.settle())
40
+ return harness
41
+ }
42
+
43
+ describe("useChannel with private: true", () => {
44
+ it("joins as private once the server announces private_channels", async () => {
45
+ const harness = await mount()
46
+ act(() => {
47
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated", features: ["private_channels"] })
48
+ })
49
+ expect(subscribeFrames(harness.socket(), "lot:42")[0]?.["private"]).toBe(true)
50
+ })
51
+
52
+ it("hands back the unsupported-server error as a RealtimeChannelError", async () => {
53
+ const harness = await mount()
54
+ act(() => {
55
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated" })
56
+ })
57
+ expect(latest?.status).toBe("CHANNEL_ERROR")
58
+ expect(isRealtimeChannelError(latest?.error)).toBe(true)
59
+ })
60
+ })
61
+
62
+ describe("useChannel with a refused send", () => {
63
+ it("exposes the refusal and keeps the channel SUBSCRIBED", async () => {
64
+ const harness = await mount()
65
+ act(() => {
66
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated", features: ["private_channels"] })
67
+ ackNewestJoin(harness.socket(), "lot:42")
68
+ })
69
+ expect(latest?.refusal).toBeNull()
70
+ act(() => {
71
+ simulateServerMessage(harness.socket(), { type: "system", status: "error", code: "send_denied", message: "not allowed", channel: "lot:42" })
72
+ })
73
+ expect(latest?.refusal).toEqual({ channel: "lot:42", code: "send_denied", message: "not allowed" })
74
+ expect(latest?.status).toBe("SUBSCRIBED")
75
+ expect(latest?.error).toBeNull()
76
+ })
77
+ })
@@ -0,0 +1,14 @@
1
+ /** The channel binding's name takes a ChannelName, so a declared topic autocompletes and any other string still works. */
2
+
3
+ import { describe, expect, it } from "vitest"
4
+ import type { ChannelName } from "@supatype/client"
5
+ import type { useChannel } from "../src/useChannel.js"
6
+
7
+ type Same<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false
8
+
9
+ describe("useChannel name type", () => {
10
+ it("is a ChannelName", () => {
11
+ const same: Same<Parameters<typeof useChannel>[0], ChannelName> = true
12
+ expect(same).toBe(true)
13
+ })
14
+ })
@@ -0,0 +1,121 @@
1
+ /**
2
+ * `useChannel(name, setup)`: one channel with as many listeners as setup registers, its status, and
3
+ * the socket's own state.
4
+ *
5
+ * `useSubscription` takes one `postgres_changes` listener, so a component that wanted rows, presence
6
+ * and a broadcast on one channel had to leave the hook and manage the handle by hand.
7
+ */
8
+
9
+ import React from "react"
10
+ import { afterEach, describe, expect, it, vi } from "vitest"
11
+ import { act, create, type ReactTestRenderer } from "react-test-renderer"
12
+ import type { ChannelSubscription } from "@supatype/client"
13
+ import { sentFrames, simulateServerMessage, subscribedChannels } from "../../client/tests/helpers/mock-websocket.js"
14
+ import { closeEvent } from "../../client/tests/helpers/close-event.js"
15
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
16
+
17
+ const shared = vi.hoisted(() => ({ harness: null as SocketSwapHarness | null }))
18
+
19
+ vi.mock("../src/context.js", () => ({
20
+ useSupatype: () => ({ realtime: shared.harness?.realtime }),
21
+ }))
22
+
23
+ import { useChannel, type UseChannelResult } from "../src/useChannel.js"
24
+
25
+ let renderer: ReactTestRenderer | null = null
26
+ let latest: UseChannelResult | null = null
27
+ let setup: (channel: ChannelSubscription<Record<string, unknown>>) => void = () => undefined
28
+
29
+ function Probe({ name }: { name: string }): null {
30
+ latest = useChannel(name, (channel) => setup(channel), [name])
31
+ return null
32
+ }
33
+
34
+ function mount(name = "auction:1"): SocketSwapHarness {
35
+ const harness = createSocketSwapHarness()
36
+ shared.harness = harness
37
+ act(() => {
38
+ renderer = create(<Probe name={name} />)
39
+ })
40
+ return harness
41
+ }
42
+
43
+ function framesOn(harness: SocketSwapHarness): Array<Record<string, unknown>> {
44
+ const first = harness.sockets[0]
45
+ return first === undefined ? [] : sentFrames(first)
46
+ }
47
+
48
+ afterEach(() => {
49
+ act(() => renderer?.unmount())
50
+ renderer = null
51
+ latest = null
52
+ setup = () => undefined
53
+ shared.harness?.restore()
54
+ })
55
+
56
+ describe("useChannel", () => {
57
+ it("hands setup the channel and registers every listener it adds on one join", async () => {
58
+ const broadcasts = vi.fn()
59
+ setup = (channel) => {
60
+ channel.on("postgres_changes", { event: "*", table: "bid" }, () => undefined)
61
+ channel.onBroadcast("outbid", broadcasts)
62
+ }
63
+ const harness = mount()
64
+ await act(() => harness.settle())
65
+
66
+ expect(subscribedChannels(harness.socket())).toEqual(["auction:1"])
67
+ act(() => {
68
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "auction:1", event: "outbid", payload: { by: "x" } })
69
+ })
70
+ expect(broadcasts).toHaveBeenCalledWith({ by: "x" })
71
+ })
72
+
73
+ it("reports status, then the connection, through a drop", async () => {
74
+ const harness = mount()
75
+ expect(latest?.status).toBe("SUBSCRIBING")
76
+ await act(() => harness.settle())
77
+ expect(latest?.isConnected).toBe(true)
78
+ expect(latest?.connectionState).toBe("connected")
79
+
80
+ act(() => harness.ackJoins())
81
+ expect(latest?.status).toBe("SUBSCRIBED")
82
+
83
+ act(() => {
84
+ harness.socket().onclose?.(closeEvent())
85
+ })
86
+ expect(latest?.isConnected).toBe(false)
87
+ expect(latest?.connectionState).toBe("connecting")
88
+ })
89
+
90
+ it("leaves the channel when the component unmounts", async () => {
91
+ const harness = mount()
92
+ await act(() => harness.settle())
93
+
94
+ act(() => renderer?.unmount())
95
+ renderer = null
96
+
97
+ expect(framesOn(harness).some((f) => f["type"] === "unsubscribe" && f["channel"] === "auction:1")).toBe(true)
98
+ })
99
+
100
+ it("moves to the new channel when the name changes, leaving the old one", async () => {
101
+ const harness = mount("auction:1")
102
+ await act(() => harness.settle())
103
+
104
+ act(() => renderer?.update(<Probe name="auction:2" />))
105
+ await act(() => harness.settle())
106
+
107
+ // Leaving the only channel closes the socket, so the old channel's leave is on the first one
108
+ // and the new join is on whichever socket the name change opened.
109
+ expect(framesOn(harness).some((f) => f["type"] === "unsubscribe" && f["channel"] === "auction:1")).toBe(true)
110
+ expect(subscribedChannels(harness.socket())).toEqual(["auction:2"])
111
+ })
112
+
113
+ it("reads the refusal reason with a CHANNEL_ERROR", async () => {
114
+ const harness = mount()
115
+ await act(() => harness.settle())
116
+ act(() => harness.refuseJoin())
117
+
118
+ expect(latest?.status).toBe("CHANNEL_ERROR")
119
+ expect(latest?.error).not.toBeNull()
120
+ })
121
+ })
@@ -156,11 +156,20 @@ describe("useQuery requests", () => {
156
156
  })
157
157
  expect(sent).toHaveLength(1)
158
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.
159
161
  expect(sent[0]!.path).toBe(
160
- "/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",
161
163
  )
162
164
  expect(sent[0]!.profile).toBeNull()
163
- 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")
164
173
  })
165
174
 
166
175
  it("reads the draft schema when asked", async () => {