@supatype/vue 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.
@@ -0,0 +1,30 @@
1
+ import { computed, ref, onMounted, onUnmounted, type ComputedRef, type Ref } from "vue"
2
+ import type { AugmentedDatabase, AnyDatabase, RealtimeConnectionState } from "@supatype/client"
3
+ import { watchConnection } from "@supatype/client/bindings"
4
+ import { useSupatype } from "./context.js"
5
+
6
+ export interface UseRealtimeConnectionReturn {
7
+ /** "connecting" covers the first connect, a reconnect after a drop, and the sign-in swap. */
8
+ connectionState: Ref<RealtimeConnectionState>
9
+ /** True while the realtime socket is open. A channel may still be waiting on its join. */
10
+ isConnected: ComputedRef<boolean>
11
+ }
12
+
13
+ /**
14
+ * The realtime socket's own state, which no channel status reports: a drop and a first connect both
15
+ * read "connecting" on a channel. Reported by `watchConnection`, shared with Svelte and Solid.
16
+ */
17
+ export function useRealtimeConnection<TDatabase extends AnyDatabase = AugmentedDatabase>(): UseRealtimeConnectionReturn {
18
+ const client = useSupatype<TDatabase>()
19
+ const connectionState = ref<RealtimeConnectionState>(client.realtime.connectionState)
20
+ let stop: (() => void) | null = null
21
+
22
+ onMounted(() => {
23
+ stop = watchConnection(client.realtime, (state) => {
24
+ connectionState.value = state
25
+ })
26
+ })
27
+ onUnmounted(() => stop?.())
28
+
29
+ return { connectionState, isConnected: computed(() => connectionState.value === "connected") }
30
+ }
@@ -1,5 +1,5 @@
1
1
  import { ref, shallowRef, onMounted, onUnmounted, type Ref } from "vue"
2
- import type { AugmentedDatabase, AnyDatabase, SupatypeError, RealtimeEvent } from "@supatype/client"
2
+ import type { AugmentedDatabase, AnyClient, AnyDatabase, SupatypeError, RealtimeEvent } from "@supatype/client"
3
3
  import { watchTable, type SubscriptionState, type TableWatchOptions } from "@supatype/client/bindings"
4
4
  import { useSupatype } from "./context.js"
5
5
 
@@ -49,7 +49,7 @@ export function useSubscription<
49
49
  let unsubscribe: (() => void) | null = null
50
50
 
51
51
  onMounted(() => {
52
- unsubscribe = watchTable<TRow>(client.realtime, table, options, {
52
+ unsubscribe = watchTable<TRow>(client as AnyClient, table, options, {
53
53
  rows: (rows) => {
54
54
  data.value = rows
55
55
  },
@@ -0,0 +1,61 @@
1
+ /** `useChannel(name, setup, { private: true })` joins as private and shows the typed refusal. */
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest"
4
+ import { isRealtimeChannelError } from "@supatype/client"
5
+ import { ackNewestJoin, subscribeFrames, simulateServerMessage } from "../../client/tests/helpers/mock-websocket.js"
6
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
7
+
8
+ const lifecycle = vi.hoisted(() => ({ unmount: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
9
+
10
+ vi.mock("vue", async (importOriginal) => ({
11
+ ...(await importOriginal<typeof import("vue")>()),
12
+ onMounted: (fn: () => void) => fn(),
13
+ onUnmounted: (fn: () => void) => lifecycle.unmount.push(fn),
14
+ }))
15
+
16
+ vi.mock("../src/context.js", () => ({
17
+ useSupatype: () => ({ realtime: lifecycle.harness?.realtime }),
18
+ }))
19
+
20
+ import { useChannel } from "../src/useChannel.js"
21
+
22
+ afterEach(() => {
23
+ for (const fn of lifecycle.unmount.splice(0)) fn()
24
+ lifecycle.harness?.restore()
25
+ })
26
+
27
+ describe("useChannel with private: true", () => {
28
+ it("joins as private once the server announces private_channels", async () => {
29
+ const harness = createSocketSwapHarness()
30
+ lifecycle.harness = harness
31
+ useChannel("lot:42", () => undefined, { private: true })
32
+ await harness.settle()
33
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated", features: ["private_channels"] })
34
+ expect(subscribeFrames(harness.socket(), "lot:42")[0]?.["private"]).toBe(true)
35
+ })
36
+
37
+ it("exposes the unsupported-server error as a RealtimeChannelError", async () => {
38
+ const harness = createSocketSwapHarness()
39
+ lifecycle.harness = harness
40
+ const { status, error } = useChannel("lot:42", () => undefined, { private: true })
41
+ await harness.settle()
42
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated" })
43
+ expect(status.value).toBe("error")
44
+ expect(isRealtimeChannelError(error.value)).toBe(true)
45
+ })
46
+ })
47
+
48
+ describe("useChannel with a refused send", () => {
49
+ it("exposes the refusal and keeps the status connected", async () => {
50
+ const harness = createSocketSwapHarness()
51
+ lifecycle.harness = harness
52
+ const { status, refusal } = useChannel("lot:42", () => undefined, { private: true })
53
+ await harness.settle()
54
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated", features: ["private_channels"] })
55
+ ackNewestJoin(harness.socket(), "lot:42")
56
+ expect(refusal.value).toBeNull()
57
+ simulateServerMessage(harness.socket(), { type: "system", status: "error", code: "send_denied", message: "not allowed", channel: "lot:42" })
58
+ expect(refusal.value).toEqual({ channel: "lot:42", code: "send_denied", message: "not allowed" })
59
+ expect(status.value).toBe("connected")
60
+ })
61
+ })
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `useChannel` follows its name when it is a ref or a getter: the old channel is left, its listeners
3
+ * go with it, and `setup` runs on the new one. The lifecycle hooks run directly, as elsewhere.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it, vi } from "vitest"
7
+ import { nextTick, ref, type MaybeRefOrGetter } from "vue"
8
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
9
+ import { sentFrames, simulateServerMessage, subscribedChannels } from "../../client/tests/helpers/mock-websocket.js"
10
+
11
+ const lifecycle = vi.hoisted(() => ({ unmount: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
12
+
13
+ vi.mock("vue", async (importOriginal) => ({
14
+ ...(await importOriginal<typeof import("vue")>()),
15
+ onMounted: (fn: () => void) => fn(),
16
+ onUnmounted: (fn: () => void) => lifecycle.unmount.push(fn),
17
+ }))
18
+
19
+ vi.mock("../src/context.js", () => ({
20
+ useSupatype: () => ({ realtime: lifecycle.harness?.realtime }),
21
+ }))
22
+
23
+ import { useChannel } from "../src/useChannel.js"
24
+
25
+ afterEach(() => {
26
+ for (const fn of lifecycle.unmount.splice(0)) fn()
27
+ lifecycle.harness?.restore()
28
+ })
29
+
30
+ describe("useChannel with a reactive name", () => {
31
+ it.each(["a ref", "a getter"])("moves to the new channel when %s changes", async (label) => {
32
+ const harness = createSocketSwapHarness()
33
+ lifecycle.harness = harness
34
+ const heard: string[] = []
35
+ const name = ref("room:1")
36
+ const given: MaybeRefOrGetter<string> = label === "a ref" ? name : () => name.value
37
+ const { status } = useChannel(given, (channel) => channel.onBroadcast("ping", () => heard.push("ping")))
38
+ await harness.settle()
39
+ harness.ackJoins()
40
+ expect(status.value).toBe("connected")
41
+
42
+ name.value = "room:2"
43
+ await nextTick()
44
+ expect(status.value).toBe("connecting")
45
+ await harness.settle()
46
+
47
+ const first = harness.sockets[0]
48
+ expect(first === undefined ? [] : sentFrames(first).some((f) => f["type"] === "unsubscribe" && f["channel"] === "room:1")).toBe(true)
49
+ expect(subscribedChannels(harness.socket())).toEqual(["room:2"])
50
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:1", event: "ping", payload: {} })
51
+ expect(heard).toEqual([])
52
+ harness.ackJoins()
53
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:2", event: "ping", payload: {} })
54
+ expect(heard).toEqual(["ping"])
55
+ })
56
+
57
+ it("keeps a plain string working", async () => {
58
+ const harness = createSocketSwapHarness()
59
+ lifecycle.harness = harness
60
+ const { status } = useChannel("room:1", () => undefined)
61
+ await harness.settle()
62
+ harness.ackJoins()
63
+ expect(status.value).toBe("connected")
64
+ })
65
+ })
@@ -0,0 +1,15 @@
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 { MaybeRefOrGetter } from "vue"
6
+ import type { useChannel } from "../src/useChannel.js"
7
+
8
+ type Same<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false
9
+
10
+ describe("useChannel name type", () => {
11
+ it("is a ChannelName", () => {
12
+ const same: Same<Parameters<typeof useChannel>[0], MaybeRefOrGetter<ChannelName>> = true
13
+ expect(same).toBe(true)
14
+ })
15
+ })
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `useChannel` and `useRealtimeConnection`: the status across the sign-in swap, and the socket's own
3
+ * state through a drop. The lifecycle hooks run directly, as in the `useSubscription` suite.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it, vi } from "vitest"
7
+ import { closeEvent } from "../../client/tests/helpers/close-event.js"
8
+ import { describeStatusAcrossSignIn, createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
9
+
10
+ const lifecycle = vi.hoisted(() => ({ unmount: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
11
+
12
+ vi.mock("vue", async (importOriginal) => ({
13
+ ...(await importOriginal<typeof import("vue")>()),
14
+ onMounted: (fn: () => void) => fn(),
15
+ onUnmounted: (fn: () => void) => lifecycle.unmount.push(fn),
16
+ }))
17
+
18
+ vi.mock("../src/context.js", () => ({
19
+ useSupatype: () => ({ realtime: lifecycle.harness?.realtime }),
20
+ }))
21
+
22
+ import { useChannel } from "../src/useChannel.js"
23
+
24
+ const unmount = (): void => {
25
+ for (const fn of lifecycle.unmount.splice(0)) fn()
26
+ }
27
+
28
+ describeStatusAcrossSignIn(
29
+ "useChannel",
30
+ (harness) => {
31
+ lifecycle.harness = harness
32
+ const { status, error } = useChannel("public:task", () => undefined)
33
+ return { status: () => status.value, error: () => error.value }
34
+ },
35
+ unmount,
36
+ )
37
+
38
+ describe("useChannel's connection", () => {
39
+ afterEach(() => {
40
+ unmount()
41
+ lifecycle.harness?.restore()
42
+ })
43
+
44
+ it("tells a drop from a first connect, and leaves the channel on unmount", async () => {
45
+ const harness = createSocketSwapHarness()
46
+ lifecycle.harness = harness
47
+ const { isConnected, connectionState } = useChannel("auction:1", () => undefined)
48
+ expect(connectionState.value).toBe("connecting")
49
+ await harness.settle()
50
+ expect(connectionState.value).toBe("connected")
51
+ expect(isConnected.value).toBe(true)
52
+
53
+ harness.socket().onclose?.(closeEvent())
54
+ expect(connectionState.value).toBe("connecting")
55
+ expect(isConnected.value).toBe(false)
56
+
57
+ unmount()
58
+ expect(harness.realtime.connectionState).toBe("disconnected")
59
+ })
60
+ })
@@ -0,0 +1,44 @@
1
+ /**
2
+ * 0.9.2 release test (N-FF9): the first render comes before `onMounted` starts the read, and
3
+ * `loading` started false, so an enabled query first showed `loading: false, data: null`. An app
4
+ * reads that pair as "done, nothing found". `onMounted` is held here so the state is read at
5
+ * that first render.
6
+ */
7
+
8
+ import { afterEach, describe, expect, it, vi } from "vitest"
9
+ import { createClient, type AnyDatabase, type SupatypeClient } from "@supatype/client"
10
+
11
+ const lifecycle = vi.hoisted(() => ({
12
+ mounted: [] as Array<() => void>,
13
+ client: null as SupatypeClient<AnyDatabase> | null,
14
+ }))
15
+
16
+ vi.mock("vue", async (importOriginal) => ({
17
+ ...(await importOriginal<typeof import("vue")>()),
18
+ onMounted: (fn: () => void) => lifecycle.mounted.push(fn),
19
+ onUnmounted: () => undefined,
20
+ }))
21
+
22
+ vi.mock("../src/context.js", () => ({
23
+ useSupatype: () => lifecycle.client,
24
+ }))
25
+
26
+ import { useQuery } from "../src/useQuery.js"
27
+
28
+ lifecycle.client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
29
+
30
+ afterEach(() => {
31
+ lifecycle.mounted.splice(0)
32
+ })
33
+
34
+ describe("useQuery before it is mounted", () => {
35
+ it("is loading when enabled", () => {
36
+ const q = useQuery<AnyDatabase>("profiles")
37
+ expect({ loading: q.loading.value, data: q.data.value }).toEqual({ loading: true, data: null })
38
+ })
39
+
40
+ it("is not loading when disabled", () => {
41
+ const q = useQuery<AnyDatabase>("profiles", { enabled: false })
42
+ expect(q.loading.value).toBe(false)
43
+ })
44
+ })
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `useQuery` reads again when its options change: options passed as a ref, and as a getter.
3
+ * Lifecycle hooks run directly: what is under test is the composable's wiring over a real client.
4
+ */
5
+
6
+ import { vi } from "vitest"
7
+ import { ref } from "vue"
8
+ import type { AnyDatabase, SupatypeClient } from "@supatype/client"
9
+ import { describeReactiveOptionsBinding, type ReadOptions } from "../../client/tests/helpers/reactive-options-binding.js"
10
+
11
+ const lifecycle = vi.hoisted(() => ({
12
+ unmount: [] as Array<() => void>,
13
+ client: null as SupatypeClient<AnyDatabase> | null,
14
+ }))
15
+
16
+ vi.mock("vue", async (importOriginal) => ({
17
+ ...(await importOriginal<typeof import("vue")>()),
18
+ onMounted: (fn: () => void) => fn(),
19
+ onUnmounted: (fn: () => void) => lifecycle.unmount.push(fn),
20
+ }))
21
+
22
+ vi.mock("../src/context.js", () => ({
23
+ useSupatype: () => lifecycle.client,
24
+ }))
25
+
26
+ import { useQuery } from "../src/useQuery.js"
27
+
28
+ const unmount = (): void => {
29
+ for (const fn of lifecycle.unmount.splice(0)) fn()
30
+ }
31
+
32
+ describeReactiveOptionsBinding(
33
+ "useQuery with a ref",
34
+ (client, initial) => {
35
+ lifecycle.client = client
36
+ const options = ref<ReadOptions>(initial)
37
+ useQuery<AnyDatabase>("posts", options)
38
+ return { change: (next) => { options.value = next } }
39
+ },
40
+ unmount,
41
+ )
42
+
43
+ describeReactiveOptionsBinding(
44
+ "useQuery with a getter",
45
+ (client, initial) => {
46
+ lifecycle.client = client
47
+ const order = ref(initial.order)
48
+ const offset = ref(initial.offset)
49
+ const filter = ref(initial.filter)
50
+ const enabled = ref(initial.enabled)
51
+ useQuery<AnyDatabase>("posts", () => ({
52
+ order: order.value,
53
+ limit: 2,
54
+ offset: offset.value,
55
+ filter: filter.value,
56
+ enabled: enabled.value,
57
+ }))
58
+ return {
59
+ change: (next) => {
60
+ order.value = next.order
61
+ offset.value = next.offset
62
+ filter.value = next.filter
63
+ enabled.value = next.enabled
64
+ },
65
+ }
66
+ },
67
+ unmount,
68
+ )
@@ -9,10 +9,11 @@
9
9
  * not Vue's mounting.
10
10
  */
11
11
 
12
- import { vi } from "vitest"
13
- import { describeStatusAcrossSignIn, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
12
+ import { vi, it, expect } from "vitest"
13
+ import { describeStatusAcrossSignIn, createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
14
+ import { fakeClient } from "../../client/tests/helpers/fake-client.js"
14
15
 
15
- const lifecycle = vi.hoisted(() => ({ unmount: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
16
+ const lifecycle = vi.hoisted(() => ({ unmount: [] as Array<() => void>, harness: null as SocketSwapHarness | null, client: null as unknown }))
16
17
 
17
18
  vi.mock("vue", async (importOriginal) => ({
18
19
  ...(await importOriginal<typeof import("vue")>()),
@@ -21,7 +22,7 @@ vi.mock("vue", async (importOriginal) => ({
21
22
  }))
22
23
 
23
24
  vi.mock("../src/context.js", () => ({
24
- useSupatype: () => ({ realtime: lifecycle.harness?.realtime }),
25
+ useSupatype: () => lifecycle.client,
25
26
  }))
26
27
 
27
28
  import { useSubscription } from "../src/useSubscription.js"
@@ -30,6 +31,7 @@ describeStatusAcrossSignIn(
30
31
  "useSubscription",
31
32
  (harness) => {
32
33
  lifecycle.harness = harness
34
+ lifecycle.client = fakeClient(harness).client
33
35
  const { status, error } = useSubscription("task")
34
36
  return { status: () => status.value, error: () => error.value }
35
37
  },
@@ -37,3 +39,16 @@ describeStatusAcrossSignIn(
37
39
  for (const fn of lifecycle.unmount.splice(0)) fn()
38
40
  },
39
41
  )
42
+
43
+ it("useSubscription shows the rows the table already holds once the join is acknowledged", async () => {
44
+ const harness = createSocketSwapHarness()
45
+ lifecycle.harness = harness
46
+ lifecycle.client = fakeClient(harness, [[{ id: 1 }]]).client
47
+ const { data } = useSubscription("task")
48
+ await harness.settle()
49
+ harness.ackJoins()
50
+ await harness.settle()
51
+ expect(data.value).toEqual([{ id: 1 }])
52
+ for (const fn of lifecycle.unmount.splice(0)) fn()
53
+ harness.restore()
54
+ })