@supatype/svelte 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 (37) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +19 -11
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +40 -1
  5. package/dist/createChannel.d.ts +27 -0
  6. package/dist/createChannel.d.ts.map +1 -0
  7. package/dist/createChannel.js +50 -0
  8. package/dist/createChannel.js.map +1 -0
  9. package/dist/createQuery.d.ts +1 -1
  10. package/dist/createQuery.d.ts.map +1 -1
  11. package/dist/createQuery.js +28 -7
  12. package/dist/createQuery.js.map +1 -1
  13. package/dist/createRealtimeConnection.d.ts +14 -0
  14. package/dist/createRealtimeConnection.d.ts.map +1 -0
  15. package/dist/createRealtimeConnection.js +18 -0
  16. package/dist/createRealtimeConnection.js.map +1 -0
  17. package/dist/createSubscription.d.ts.map +1 -1
  18. package/dist/createSubscription.js +1 -1
  19. package/dist/createSubscription.js.map +1 -1
  20. package/dist/index.d.ts +4 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2 -0
  23. package/dist/index.js.map +1 -1
  24. package/package.json +3 -3
  25. package/src/createChannel.ts +64 -0
  26. package/src/createQuery.ts +28 -7
  27. package/src/createRealtimeConnection.ts +28 -0
  28. package/src/createSubscription.ts +2 -2
  29. package/src/index.ts +6 -0
  30. package/tests/createChannel-private.test.ts +61 -0
  31. package/tests/createChannel-reactive-name.test.ts +63 -0
  32. package/tests/createChannel-typed-name.test.ts +15 -0
  33. package/tests/createChannel.test.ts +60 -0
  34. package/tests/createQuery-first-render.test.ts +90 -0
  35. package/tests/createQuery-reactive-options.test.ts +38 -0
  36. package/tests/createSubscription-status.test.ts +19 -4
  37. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,61 @@
1
+ /** `createChannel(name, setup, { private: true })` joins as private and shows the typed refusal. */
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest"
4
+ import { get } from "svelte/store"
5
+ import { isRealtimeChannelError } from "@supatype/client"
6
+ import { ackNewestJoin, subscribeFrames, simulateServerMessage } from "../../client/tests/helpers/mock-websocket.js"
7
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
8
+
9
+ const lifecycle = vi.hoisted(() => ({ destroy: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
10
+
11
+ vi.mock("svelte", async (importOriginal) => ({
12
+ ...(await importOriginal<typeof import("svelte")>()),
13
+ onDestroy: (fn: () => void) => lifecycle.destroy.push(fn),
14
+ }))
15
+
16
+ vi.mock("../src/context.js", () => ({
17
+ getSupatypeClient: () => ({ realtime: lifecycle.harness?.realtime }),
18
+ }))
19
+
20
+ import { createChannel } from "../src/createChannel.js"
21
+
22
+ afterEach(() => {
23
+ for (const fn of lifecycle.destroy.splice(0)) fn()
24
+ lifecycle.harness?.restore()
25
+ })
26
+
27
+ describe("createChannel with private: true", () => {
28
+ it("joins as private once the server announces private_channels", async () => {
29
+ const harness = createSocketSwapHarness()
30
+ lifecycle.harness = harness
31
+ createChannel("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 } = createChannel("lot:42", () => undefined, { private: true })
41
+ await harness.settle()
42
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated" })
43
+ expect(get(status)).toBe("error")
44
+ expect(isRealtimeChannelError(get(error))).toBe(true)
45
+ })
46
+ })
47
+
48
+ describe("createChannel 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 } = createChannel("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(get(refusal)).toBeNull()
57
+ simulateServerMessage(harness.socket(), { type: "system", status: "error", code: "send_denied", message: "not allowed", channel: "lot:42" })
58
+ expect(get(refusal)).toEqual({ channel: "lot:42", code: "send_denied", message: "not allowed" })
59
+ expect(get(status)).toBe("connected")
60
+ })
61
+ })
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `createChannel` follows its name when it is a store: the old channel is left, its listeners go
3
+ * with it, and `setup` runs on the new one. `onDestroy` is collected rather than registered with a
4
+ * component.
5
+ */
6
+
7
+ import { afterEach, describe, expect, it, vi } from "vitest"
8
+ import { get, writable } from "svelte/store"
9
+ import { createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
10
+ import { sentFrames, simulateServerMessage, subscribedChannels } from "../../client/tests/helpers/mock-websocket.js"
11
+
12
+ const lifecycle = vi.hoisted(() => ({ destroy: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
13
+
14
+ vi.mock("svelte", async (importOriginal) => ({
15
+ ...(await importOriginal<typeof import("svelte")>()),
16
+ onDestroy: (fn: () => void) => lifecycle.destroy.push(fn),
17
+ }))
18
+
19
+ vi.mock("../src/context.js", () => ({
20
+ getSupatypeClient: () => ({ realtime: lifecycle.harness?.realtime }),
21
+ }))
22
+
23
+ import { createChannel } from "../src/createChannel.js"
24
+
25
+ afterEach(() => {
26
+ for (const fn of lifecycle.destroy.splice(0)) fn()
27
+ lifecycle.harness?.restore()
28
+ })
29
+
30
+ describe("createChannel with a store for its name", () => {
31
+ it("moves to the new channel when the store changes, leaving the old channel behind", async () => {
32
+ const harness = createSocketSwapHarness()
33
+ lifecycle.harness = harness
34
+ const heard: string[] = []
35
+ const name = writable("room:1")
36
+ const { status } = createChannel(name, (channel) => channel.onBroadcast("ping", () => heard.push("ping")))
37
+ await harness.settle()
38
+ harness.ackJoins()
39
+ expect(get(status)).toBe("connected")
40
+
41
+ name.set("room:2")
42
+ expect(get(status)).toBe("connecting")
43
+ await harness.settle()
44
+
45
+ const first = harness.sockets[0]
46
+ expect(first === undefined ? [] : sentFrames(first).some((f) => f["type"] === "unsubscribe" && f["channel"] === "room:1")).toBe(true)
47
+ expect(subscribedChannels(harness.socket())).toEqual(["room:2"])
48
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:1", event: "ping", payload: {} })
49
+ expect(heard).toEqual([])
50
+ harness.ackJoins()
51
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:2", event: "ping", payload: {} })
52
+ expect(heard).toEqual(["ping"])
53
+ })
54
+
55
+ it("keeps a plain string working", async () => {
56
+ const harness = createSocketSwapHarness()
57
+ lifecycle.harness = harness
58
+ const { status } = createChannel("room:1", () => undefined)
59
+ await harness.settle()
60
+ harness.ackJoins()
61
+ expect(get(status)).toBe("connected")
62
+ })
63
+ })
@@ -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 { Readable } from "svelte/store"
6
+ import type { createChannel } from "../src/createChannel.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("createChannel name type", () => {
11
+ it("is a ChannelName", () => {
12
+ const same: Same<Parameters<typeof createChannel>[0], ChannelName | Readable<ChannelName>> = true
13
+ expect(same).toBe(true)
14
+ })
15
+ })
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `createChannel` and `createRealtimeConnection`: the status across the sign-in swap, and the
3
+ * socket's own state through a drop. `onDestroy` is collected, as in the `createSubscription` suite.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it, vi } from "vitest"
7
+ import { get } from "svelte/store"
8
+ import { closeEvent } from "../../client/tests/helpers/close-event.js"
9
+ import { describeStatusAcrossSignIn, createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
10
+
11
+ const lifecycle = vi.hoisted(() => ({ destroy: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
12
+
13
+ vi.mock("svelte", async (importOriginal) => ({
14
+ ...(await importOriginal<typeof import("svelte")>()),
15
+ onDestroy: (fn: () => void) => lifecycle.destroy.push(fn),
16
+ }))
17
+
18
+ vi.mock("../src/context.js", () => ({
19
+ getSupatypeClient: () => ({ realtime: lifecycle.harness?.realtime }),
20
+ }))
21
+
22
+ import { createChannel } from "../src/createChannel.js"
23
+
24
+ const destroy = (): void => {
25
+ for (const fn of lifecycle.destroy.splice(0)) fn()
26
+ }
27
+
28
+ describeStatusAcrossSignIn(
29
+ "createChannel",
30
+ (harness) => {
31
+ lifecycle.harness = harness
32
+ const { status, error } = createChannel("public:task", () => undefined)
33
+ return { status: () => get(status), error: () => get(error) }
34
+ },
35
+ destroy,
36
+ )
37
+
38
+ describe("createChannel's connection", () => {
39
+ afterEach(() => {
40
+ destroy()
41
+ lifecycle.harness?.restore()
42
+ })
43
+
44
+ it("tells a drop from a first connect, and leaves the channel on destroy", async () => {
45
+ const harness = createSocketSwapHarness()
46
+ lifecycle.harness = harness
47
+ const { isConnected, connectionState } = createChannel("auction:1", () => undefined)
48
+ expect(get(connectionState)).toBe("connecting")
49
+ await harness.settle()
50
+ expect(get(connectionState)).toBe("connected")
51
+ expect(get(isConnected)).toBe(true)
52
+
53
+ harness.socket().onclose?.(closeEvent())
54
+ expect(get(connectionState)).toBe("connecting")
55
+ expect(get(isConnected)).toBe(false)
56
+
57
+ destroy()
58
+ expect(harness.realtime.connectionState).toBe("disconnected")
59
+ })
60
+ })
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 0.9.2 release test (N-FF9): React, Vue and Solid showed `loading: false, data: null` on the
3
+ * render where an enabled query started, which an app reads as "done, nothing found". Svelte's
4
+ * `loading` store starts at false too, but no subscriber ever sees it so for an enabled query: the
5
+ * read starts while `createQuery` runs, before anything can subscribe, and when the options store
6
+ * turns the query on, `loading` is set before a page subscribed to both stores hears of either.
7
+ * These hold that, so a read moved later (to a mount hook, say) cannot bring the bug here.
8
+ *
9
+ * Every read is held unanswered, so what is recorded is what a page shows while it waits.
10
+ */
11
+
12
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
13
+ import { derived, writable, type Readable } from "svelte/store"
14
+ import { createClient, type AnyDatabase, type SupatypeClient } from "@supatype/client"
15
+
16
+ const lifecycle = vi.hoisted(() => ({
17
+ destroy: [] as Array<() => void>,
18
+ client: null as SupatypeClient<AnyDatabase> | null,
19
+ }))
20
+
21
+ vi.mock("svelte", async (importOriginal) => ({
22
+ ...(await importOriginal<typeof import("svelte")>()),
23
+ onDestroy: (fn: () => void) => lifecycle.destroy.push(fn),
24
+ }))
25
+
26
+ vi.mock("../src/context.js", () => ({
27
+ getSupatypeClient: () => lifecycle.client,
28
+ }))
29
+
30
+ import { createQuery, type QueryOptions, type QueryStore } from "../src/createQuery.js"
31
+
32
+ /** What a page shows at one moment: the options it asked with, and the query's state. */
33
+ interface Shown {
34
+ enabled: boolean
35
+ loading: boolean
36
+ data: unknown[] | null
37
+ }
38
+
39
+ /** Every state a page subscribed to `query` (and to `options`, when a store) is shown, in order. */
40
+ function record(query: QueryStore<unknown>, options: Readable<QueryOptions>): Shown[] {
41
+ const seen: Shown[] = []
42
+ const shown = derived([options, query.loading, query.data], ([o, loading, data]) => ({
43
+ enabled: o.enabled !== false,
44
+ loading,
45
+ data,
46
+ }))
47
+ lifecycle.destroy.push(shown.subscribe((s) => seen.push(s)))
48
+ return seen
49
+ }
50
+
51
+ /** A state an app reads as "done, nothing found" while its read is still to come. */
52
+ const looksEmpty = (s: Shown): boolean => s.enabled && !s.loading && s.data === null
53
+
54
+ beforeEach(() => {
55
+ vi.stubGlobal("fetch", () => new Promise<Response>(() => {}))
56
+ lifecycle.client = createClient<AnyDatabase>({ url: "http://localhost:9999", anonKey: "anon" })
57
+ })
58
+
59
+ afterEach(() => {
60
+ for (const fn of lifecycle.destroy.splice(0)) fn()
61
+ vi.unstubAllGlobals()
62
+ })
63
+
64
+ describe("createQuery's first value", () => {
65
+ it("is loading when enabled with plain options", () => {
66
+ const q = createQuery<AnyDatabase>("profiles", {})
67
+ expect(record(q, writable({}))[0]).toEqual({ enabled: true, loading: true, data: null })
68
+ })
69
+
70
+ it("is loading when enabled with an options store", () => {
71
+ const options = writable<QueryOptions>({})
72
+ const q = createQuery<AnyDatabase>("profiles", options)
73
+ expect(record(q, options)[0]).toEqual({ enabled: true, loading: true, data: null })
74
+ })
75
+
76
+ it("is not loading when disabled", () => {
77
+ const options = writable<QueryOptions>({ enabled: false })
78
+ const q = createQuery<AnyDatabase>("profiles", options)
79
+ expect(record(q, options)).toEqual([{ enabled: false, loading: false, data: null }])
80
+ })
81
+
82
+ it("is loading from the moment the options store turns it on", () => {
83
+ const options = writable<QueryOptions>({ enabled: false })
84
+ const q = createQuery<AnyDatabase>("profiles", options)
85
+ const seen = record(q, options)
86
+ options.set({ enabled: true })
87
+ expect(seen.filter(looksEmpty)).toEqual([])
88
+ expect(seen.at(-1)).toEqual({ enabled: true, loading: true, data: null })
89
+ })
90
+ })
@@ -0,0 +1,38 @@
1
+ /**
2
+ * `createQuery` reads again when its options change, passed as a store. `onDestroy` is collected
3
+ * rather than registered with a component.
4
+ */
5
+
6
+ import { vi } from "vitest"
7
+ import { writable } from "svelte/store"
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
+ destroy: [] as Array<() => void>,
13
+ client: null as SupatypeClient<AnyDatabase> | null,
14
+ }))
15
+
16
+ vi.mock("svelte", async (importOriginal) => ({
17
+ ...(await importOriginal<typeof import("svelte")>()),
18
+ onDestroy: (fn: () => void) => lifecycle.destroy.push(fn),
19
+ }))
20
+
21
+ vi.mock("../src/context.js", () => ({
22
+ getSupatypeClient: () => lifecycle.client,
23
+ }))
24
+
25
+ import { createQuery } from "../src/createQuery.js"
26
+
27
+ describeReactiveOptionsBinding(
28
+ "createQuery with a store",
29
+ (client, initial) => {
30
+ lifecycle.client = client
31
+ const options = writable<ReadOptions>(initial)
32
+ createQuery<AnyDatabase>("posts", options)
33
+ return { change: (next) => options.set(next) }
34
+ },
35
+ () => {
36
+ for (const fn of lifecycle.destroy.splice(0)) fn()
37
+ },
38
+ )
@@ -9,11 +9,12 @@
9
9
  * store wires the channel, not Svelte's component lifecycle.
10
10
  */
11
11
 
12
- import { vi } from "vitest"
12
+ import { vi, it, expect } from "vitest"
13
13
  import { get } from "svelte/store"
14
- import { describeStatusAcrossSignIn, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
14
+ import { describeStatusAcrossSignIn, createSocketSwapHarness, type SocketSwapHarness } from "../../client/tests/helpers/socket-swap.js"
15
+ import { fakeClient } from "../../client/tests/helpers/fake-client.js"
15
16
 
16
- const lifecycle = vi.hoisted(() => ({ destroy: [] as Array<() => void>, harness: null as SocketSwapHarness | null }))
17
+ const lifecycle = vi.hoisted(() => ({ destroy: [] as Array<() => void>, harness: null as SocketSwapHarness | null, client: null as unknown }))
17
18
 
18
19
  vi.mock("svelte", async (importOriginal) => ({
19
20
  ...(await importOriginal<typeof import("svelte")>()),
@@ -21,7 +22,7 @@ vi.mock("svelte", async (importOriginal) => ({
21
22
  }))
22
23
 
23
24
  vi.mock("../src/context.js", () => ({
24
- getSupatypeClient: () => ({ realtime: lifecycle.harness?.realtime }),
25
+ getSupatypeClient: () => lifecycle.client,
25
26
  }))
26
27
 
27
28
  import { createSubscription } from "../src/createSubscription.js"
@@ -30,6 +31,7 @@ describeStatusAcrossSignIn(
30
31
  "createSubscription",
31
32
  (harness) => {
32
33
  lifecycle.harness = harness
34
+ lifecycle.client = fakeClient(harness).client
33
35
  const { status, error } = createSubscription("task")
34
36
  return { status: () => get(status), error: () => get(error) }
35
37
  },
@@ -37,3 +39,16 @@ describeStatusAcrossSignIn(
37
39
  for (const fn of lifecycle.destroy.splice(0)) fn()
38
40
  },
39
41
  )
42
+
43
+ it("createSubscription 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 } = createSubscription("task")
48
+ await harness.settle()
49
+ harness.ackJoins()
50
+ await harness.settle()
51
+ expect(get(data)).toEqual([{ id: 1 }])
52
+ for (const fn of lifecycle.destroy.splice(0)) fn()
53
+ harness.restore()
54
+ })