@supatype/client 0.9.2 → 0.10.1

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 (99) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +98 -75
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/CHANGELOG.md +123 -20
  5. package/README.md +18 -0
  6. package/dist/auth.d.ts +4 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +38 -13
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +3 -0
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +1 -0
  13. package/dist/bindings.js.map +1 -1
  14. package/dist/channel-watch.d.ts +42 -0
  15. package/dist/channel-watch.d.ts.map +1 -0
  16. package/dist/channel-watch.js +59 -0
  17. package/dist/channel-watch.js.map +1 -0
  18. package/dist/errors.d.ts +40 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +31 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/exact-values.d.ts +18 -5
  23. package/dist/exact-values.d.ts.map +1 -1
  24. package/dist/exact-values.js +76 -12
  25. package/dist/exact-values.js.map +1 -1
  26. package/dist/field-kinds-registry.d.ts +1 -1
  27. package/dist/field-kinds-registry.d.ts.map +1 -1
  28. package/dist/field-kinds-registry.js +20 -2
  29. package/dist/field-kinds-registry.js.map +1 -1
  30. package/dist/index.d.ts +6 -2
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +5 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/public-env.d.ts +13 -0
  35. package/dist/public-env.d.ts.map +1 -0
  36. package/dist/public-env.js +23 -0
  37. package/dist/public-env.js.map +1 -0
  38. package/dist/query-cache.d.ts +2 -1
  39. package/dist/query-cache.d.ts.map +1 -1
  40. package/dist/query-cache.js.map +1 -1
  41. package/dist/query.js +1 -1
  42. package/dist/query.js.map +1 -1
  43. package/dist/realtime-refusals.d.ts +35 -0
  44. package/dist/realtime-refusals.d.ts.map +1 -0
  45. package/dist/realtime-refusals.js +73 -0
  46. package/dist/realtime-refusals.js.map +1 -0
  47. package/dist/realtime.d.ts +70 -2
  48. package/dist/realtime.d.ts.map +1 -1
  49. package/dist/realtime.js +198 -18
  50. package/dist/realtime.js.map +1 -1
  51. package/dist/runtime-env.d.ts +2 -0
  52. package/dist/runtime-env.d.ts.map +1 -1
  53. package/dist/runtime-env.js +5 -0
  54. package/dist/runtime-env.js.map +1 -1
  55. package/dist/table-subscription.d.ts +23 -9
  56. package/dist/table-subscription.d.ts.map +1 -1
  57. package/dist/table-subscription.js +155 -23
  58. package/dist/table-subscription.js.map +1 -1
  59. package/dist/types.d.ts +29 -1
  60. package/dist/types.d.ts.map +1 -1
  61. package/dist/types.js.map +1 -1
  62. package/package.json +2 -2
  63. package/src/auth.ts +40 -12
  64. package/src/bindings.ts +3 -0
  65. package/src/channel-watch.ts +86 -0
  66. package/src/errors.ts +54 -0
  67. package/src/exact-values.ts +101 -13
  68. package/src/field-kinds-registry.ts +2 -3
  69. package/src/index.ts +13 -1
  70. package/src/public-env.ts +22 -0
  71. package/src/query-cache.ts +2 -1
  72. package/src/query.ts +1 -1
  73. package/src/realtime-refusals.ts +100 -0
  74. package/src/realtime.ts +256 -20
  75. package/src/runtime-env.ts +6 -0
  76. package/src/table-subscription.ts +186 -30
  77. package/src/types.ts +35 -1
  78. package/tests/auth-restore-user.test.ts +84 -0
  79. package/tests/auth.test.ts +11 -0
  80. package/tests/channel-watch-private.test.ts +105 -0
  81. package/tests/channel-watch.test.ts +97 -0
  82. package/tests/exact-response.test.ts +101 -0
  83. package/tests/exact-values.test.ts +57 -0
  84. package/tests/field-kinds-registry.test.ts +12 -0
  85. package/tests/helpers/close-event.ts +12 -0
  86. package/tests/helpers/fake-client.ts +38 -0
  87. package/tests/public-env.test.ts +43 -0
  88. package/tests/query-cache.test.ts +1 -1
  89. package/tests/realtime-connection.test.ts +228 -0
  90. package/tests/realtime-exact-values.test.ts +42 -0
  91. package/tests/realtime-private-channels.test.ts +377 -0
  92. package/tests/realtime-refusal-error.test.ts +2 -1
  93. package/tests/realtime-typed-channels.test.ts +49 -0
  94. package/tests/runtime-env.test.ts +14 -0
  95. package/tests/table-subscription-rows.test.ts +136 -0
  96. package/tests/table-subscription.test.ts +4 -3
  97. package/tsconfig.tsbuildinfo +1 -1
  98. package/type-tests/declared-channels.ts +30 -0
  99. package/type-tests/tsconfig.json +4 -0
@@ -1,6 +1,9 @@
1
1
  import type { ChannelStatus, RealtimeClient, RealtimeEvent, RealtimePayload } from "./realtime.js"
2
- import { SupatypeError } from "./errors.js"
2
+ import { isRealtimeChannelError, SupatypeError } from "./errors.js"
3
3
  import { isJsonObject } from "./json.js"
4
+ import { isRowsOf } from "./caller-types.js"
5
+ import { reportThrown } from "./thrown-error.js"
6
+ import type { AnyClient } from "./index.js"
4
7
 
5
8
  /**
6
9
  * A table's live rows, for `from(table).subscribe()` and for the Vue, Svelte and Solid bindings.
@@ -22,12 +25,21 @@ export interface SubscriptionView {
22
25
  error: SupatypeError | null
23
26
  }
24
27
 
25
- export interface TableWatchOptions {
28
+ /** Which changes a table subscription hears. */
29
+ interface TableChangeOptions {
26
30
  event?: RealtimeEvent | undefined
27
31
  filter?: string | undefined
28
32
  }
29
33
 
30
- export interface TableSubscribeOptions extends TableWatchOptions {
34
+ export interface TableWatchOptions extends TableChangeOptions {
35
+ /**
36
+ * The column or columns that identify a row, which an upsert or a delete matches on. Default
37
+ * "id". Name the primary key when it is not `id`.
38
+ */
39
+ key?: string | readonly string[] | undefined
40
+ }
41
+
42
+ export interface TableSubscribeOptions extends TableChangeOptions {
31
43
  schema?: string | undefined
32
44
  }
33
45
 
@@ -103,60 +115,204 @@ export function subscriptionViewOf(status: ChannelStatus, err?: Error | undefine
103
115
  case "CLOSED":
104
116
  return { status: "disconnected", error: null }
105
117
  case "CHANNEL_ERROR":
106
- return { status: "error", error: new SupatypeError({ message: err?.message ?? "Subscription error" }) }
118
+ // A typed refusal is kept as it is, so the binding's error says which refusal it was.
119
+ return { status: "error", error: isRealtimeChannelError(err) ? err : new SupatypeError({ message: err?.message ?? "Subscription error" }) }
107
120
  case "TIMED_OUT":
108
121
  return { status: "error", error: new SupatypeError({ message: "Realtime connection timed out" }) }
109
122
  }
110
123
  }
111
124
 
112
- function rowId(row: unknown): unknown {
113
- return isJsonObject(row) ? row["id"] : undefined
125
+ const DEFAULT_KEY: readonly string[] = ["id"]
126
+
127
+ function keyColumnsOf(key: string | readonly string[] | undefined): readonly string[] {
128
+ if (key === undefined) return DEFAULT_KEY
129
+ return typeof key === "string" ? [key] : key
130
+ }
131
+
132
+ /** The row's key as one comparable string, or undefined when a key column is missing or null. */
133
+ function keyOf(row: unknown, key: readonly string[]): string | undefined {
134
+ if (!isJsonObject(row)) return undefined
135
+ const parts = key.map((column) => row[column])
136
+ return parts.some((part) => part === undefined || part === null) ? undefined : parts.map(String).join("\u0000")
137
+ }
138
+
139
+ /** `rows` with `next` in place of the row sharing its key, or added when none does. */
140
+ function upserted<TRow>(rows: TRow[], next: TRow, key: readonly string[]): TRow[] {
141
+ const wanted = keyOf(next, key)
142
+ const at = wanted === undefined ? -1 : rows.findIndex((row) => keyOf(row, key) === wanted)
143
+ if (at < 0) return [...rows, next]
144
+ return rows.map((row, i) => (i === at ? next : row))
114
145
  }
115
146
 
116
147
  /**
117
- * The rows after one change, matched on `id`.
148
+ * The rows after one change, matched on `key` (the `id` column unless the subscription names others).
118
149
  *
119
- * An insert or update always carries the new row; one without it (which the service does not send)
120
- * leaves the rows as they were rather than putting a null among them.
150
+ * An INSERT or UPDATE is an upsert: a row seen twice is listed once, and an update to a row not seen
151
+ * yet adds it. A DELETE removes by key, and one for a key not held leaves the rows as they were.
152
+ * An insert or update without its row (which the service does not send), or one whose row has no
153
+ * key to match, leaves the rows as they were rather than putting a null or a duplicate among them.
121
154
  */
122
- export function applyRowChange<TRow>(rows: TRow[] | null, payload: RealtimePayload<TRow>): TRow[] {
155
+ export function applyRowChange<TRow>(
156
+ rows: TRow[] | null,
157
+ payload: RealtimePayload<TRow>,
158
+ key: readonly string[] = DEFAULT_KEY,
159
+ ): TRow[] {
123
160
  const current = rows ?? []
124
- const next = payload.new
125
161
  switch (payload.eventType) {
126
162
  case "INSERT":
127
- return next === null ? current : [...current, next]
128
163
  case "UPDATE":
129
- return next === null ? current : current.map((row) => (rowId(row) === rowId(next) ? next : row))
130
- case "DELETE":
131
- return current.filter((row) => rowId(row) !== rowId(payload.old))
164
+ return payload.new === null || keyOf(payload.new, key) === undefined ? current : upserted(current, payload.new, key)
165
+ case "DELETE": {
166
+ const gone = keyOf(payload.old, key)
167
+ return gone === undefined ? current : current.filter((row) => keyOf(row, key) !== gone)
168
+ }
132
169
  default:
133
170
  return current
134
171
  }
135
172
  }
136
173
 
174
+ // ─── Reading the table ───────────────────────────────────────────────────────
175
+
176
+ /** A query the subscription's filter conditions can be applied to: the client's `QueryBuilder`. */
177
+ interface Narrowable<Q> {
178
+ eq(column: string, value: unknown): Q
179
+ neq(column: string, value: unknown): Q
180
+ gt(column: string, value: unknown): Q
181
+ gte(column: string, value: unknown): Q
182
+ lt(column: string, value: unknown): Q
183
+ lte(column: string, value: unknown): Q
184
+ }
185
+
186
+ const CONDITION = /^([^=]+)=([a-z]+)\.(.*)$/s
187
+ const OPERATORS = ["eq", "neq", "gt", "gte", "lt", "lte"] as const
188
+ type Operator = (typeof OPERATORS)[number]
189
+
190
+ function isOperator(text: string | undefined): text is Operator {
191
+ return OPERATORS.some((known) => known === text)
192
+ }
193
+
194
+ /**
195
+ * `query` narrowed by the conditions of a subscription's `filter`, so the rows read are the rows
196
+ * the subscription hears about. A condition the service ignores (an operator it does not know) is
197
+ * ignored here too.
198
+ */
199
+ function withConditions<Q extends Narrowable<Q>>(query: Q, filter: string | undefined): Q {
200
+ let narrowed = query
201
+ for (const text of (filter ?? "").split(",")) {
202
+ const match = CONDITION.exec(text.trim())
203
+ const op = match?.[2]
204
+ if (match === null || !isOperator(op)) continue
205
+ narrowed = narrowed[op](match[1] ?? "", match[3] ?? "")
206
+ }
207
+ return narrowed
208
+ }
209
+
210
+ type TableRead<TRow> = { rows: TRow[]; error: null } | { rows: null; error: SupatypeError }
211
+
212
+ async function readTable<TRow>(client: AnyClient, table: string, filter: string | undefined): Promise<TableRead<TRow>> {
213
+ try {
214
+ const result = await withConditions(client.from(table).select("*"), filter)
215
+ if (result.error !== null) return { rows: null, error: result.error }
216
+ return isRowsOf<TRow>(result.data) ? { rows: result.data, error: null } : { rows: [], error: null }
217
+ } catch (e) {
218
+ return { rows: null, error: reportThrown(`watchTable("${table}")`, e) }
219
+ }
220
+ }
221
+
222
+ // ─── A watched table ─────────────────────────────────────────────────────────
223
+
224
+ /**
225
+ * One subscription's rows.
226
+ *
227
+ * Seeded by a read of the table each time the channel's join is acknowledged: the first join, and
228
+ * every join after a drop or a sign-in swap. Reading after the join, not before it, leaves no gap:
229
+ * a change committed before the join is in the read, and one committed after it is delivered. The
230
+ * read is not the same as the changes a drop missed, so each re-join replaces the rows with a fresh
231
+ * read rather than trying to patch them.
232
+ *
233
+ * Changes that arrive while a read is in flight are replayed over it, in order, so the read
234
+ * cannot undo them. Only the newest read counts.
235
+ */
236
+ class WatchedRows<TRow> {
237
+ private rows: TRow[] | null = null
238
+ private replay: RealtimePayload<TRow>[] | null = null
239
+ private reads = 0
240
+ private joined = false
241
+ private view: SubscriptionView = { status: "connecting", error: null }
242
+ private readFailed = false
243
+ private stopped = false
244
+
245
+ constructor(
246
+ private readonly client: AnyClient,
247
+ private readonly table: string,
248
+ private readonly options: TableWatchOptions | undefined,
249
+ private readonly handlers: TableWatchHandlers<TRow>,
250
+ ) {}
251
+
252
+ change(payload: RealtimePayload<TRow>): void {
253
+ this.replay?.push(payload)
254
+ this.show(applyRowChange(this.rows, payload, keyColumnsOf(this.options?.key)))
255
+ }
256
+
257
+ status(view: SubscriptionView): void {
258
+ const rejoined = view.status === "connected" && !this.joined
259
+ this.joined = view.status === "connected"
260
+ this.view = view
261
+ this.handlers.status(view)
262
+ if (rejoined) void this.seed()
263
+ }
264
+
265
+ stop(): void {
266
+ this.stopped = true
267
+ }
268
+
269
+ private show(rows: TRow[]): void {
270
+ if (this.stopped) return
271
+ this.rows = rows
272
+ this.handlers.rows(rows)
273
+ }
274
+
275
+ private async seed(): Promise<void> {
276
+ const read = ++this.reads
277
+ this.replay ??= []
278
+ const answer = await readTable<TRow>(this.client, this.table, this.options?.filter)
279
+ if (read !== this.reads || this.stopped) return
280
+ const missed = this.replay
281
+ this.replay = null
282
+ this.reportRead(answer.error)
283
+ if (answer.rows === null) return
284
+ const key = keyColumnsOf(this.options?.key)
285
+ this.show(missed.reduce((rows, payload) => applyRowChange(rows, payload, key), answer.rows))
286
+ }
287
+
288
+ /** A failed read is the subscription's error until a read succeeds; the channel's status stands. */
289
+ private reportRead(error: SupatypeError | null): void {
290
+ if (error !== null) this.handlers.status({ ...this.view, error })
291
+ else if (this.readFailed) this.handlers.status(this.view)
292
+ this.readFailed = error !== null
293
+ }
294
+ }
295
+
137
296
  /**
138
297
  * Subscribe to changes on a `public` table, and return the unsubscribe.
139
298
  *
140
299
  * The handlers are told the rows and the connection status; the binding decides where they live.
141
- * The status is watched on the channel `subscribeToTable` already joined, which is what its
142
- * channel's `subscribe(cb)` is for.
300
+ * The rows are the table's own: read when the subscription joins and again after each re-join, and
301
+ * kept current by upserting each change by key. `options.filter` narrows both the read and the
302
+ * changes. The status is watched on the channel `subscribeToTable` already joined, which is what
303
+ * its channel's `subscribe(cb)` is for.
143
304
  */
144
305
  export function watchTable<TRow>(
145
- realtime: RealtimeClient,
306
+ client: AnyClient,
146
307
  table: string,
147
308
  options: TableWatchOptions | undefined,
148
309
  handlers: TableWatchHandlers<TRow>,
149
310
  ): () => void {
150
- let rows: TRow[] | null = null
151
- const subscription = subscribeToTable<TRow>(
152
- realtime,
153
- table,
154
- (payload) => {
155
- rows = applyRowChange(rows, payload)
156
- handlers.rows(rows)
157
- },
158
- options,
159
- )
160
- subscription.channel.subscribe((status, err) => handlers.status(subscriptionViewOf(status, err)))
161
- return subscription.unsubscribe
311
+ const watched = new WatchedRows<TRow>(client, table, options, handlers)
312
+ const subscription = subscribeToTable<TRow>(client.realtime, table, (payload) => watched.change(payload), options)
313
+ subscription.channel.subscribe((status, err) => watched.status(subscriptionViewOf(status, err)))
314
+ return () => {
315
+ watched.stop()
316
+ subscription.unsubscribe()
317
+ }
162
318
  }
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { TableRelationship } from "./select-types.js"
2
+ import type { CacheStatus } from "./query-cache.js"
2
3
  import type { SupatypeError } from "./errors.js"
3
4
 
4
5
  // ─── Auth types ───────────────────────────────────────────────────────────────
@@ -240,7 +241,7 @@ export interface QueryResult<TData> {
240
241
  error: SupatypeError | null
241
242
  count: number | null
242
243
  meta?: {
243
- cacheStatus?: "HIT" | "MISS" | "BYPASS" | undefined
244
+ cacheStatus?: CacheStatus | undefined
244
245
  /** Present only when the response named restricted columns. Absent means "not stated". */
245
246
  maskedFields?: MaskedField[] | undefined
246
247
  } | undefined
@@ -332,6 +333,39 @@ export type UpdateOptions<TDef extends TableDef> =
332
333
  */
333
334
  export interface SupatypeModels {}
334
335
  export interface SupatypeBuckets {}
336
+ export interface SupatypeChannels {}
337
+
338
+ /** What one `{param}` of a channel pattern holds: a number for an Integer parameter, else text. */
339
+ type TopicParam<TParams, TName extends string> =
340
+ TParams extends { [K in TName]: number } ? `${number}` : string
341
+
342
+ /** A pattern with every `{param}` and a trailing `*` replaced by the text that can stand there. */
343
+ type TopicOfPattern<TPattern extends string, TParams> =
344
+ TPattern extends `${infer Head}{${infer Name}}${infer Rest}`
345
+ ? `${Head}${TopicParam<TParams, Name>}${TopicOfPattern<Rest, TParams>}`
346
+ : TPattern extends `${infer Head}*`
347
+ ? `${Head}${string}`
348
+ : TPattern
349
+
350
+ /**
351
+ * The topics a set of declared channels can name, as template literal types. `{ "lot:{id}": ... }`
352
+ * gives `` `lot:${string}` ``, `"lobby:*"` gives `` `lobby:${string}` ``, and an Integer parameter
353
+ * gives `` `${number}` `` in its place. Generated code fills {@link SupatypeChannels}; this takes the
354
+ * declarations as an argument so it can be checked without augmenting that interface.
355
+ */
356
+ export type DeclaredTopics<TChannels> = {
357
+ [P in keyof TChannels & string]: TopicOfPattern<P, TChannels[P] extends { params: infer R } ? R : never>
358
+ }[keyof TChannels & string]
359
+
360
+ /** The topics the project's schema declares. `never` until `supatype generate` has run. */
361
+ export type DeclaredTopic = DeclaredTopics<SupatypeChannels>
362
+
363
+ /**
364
+ * A channel name: a declared topic, which autocompletes, or any other string, which an `open`
365
+ * realtime server still admits. The `string & {}` keeps the literal suggestions from collapsing
366
+ * into plain `string`.
367
+ */
368
+ export type ChannelName = DeclaredTopic | (string & {})
335
369
  export interface SupatypeFunctions {}
336
370
 
337
371
  /**
@@ -0,0 +1,84 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest"
2
+ import { AuthClient } from "../src/auth.js"
3
+ import type { AuthStorage } from "../src/types.js"
4
+ import { fetchReturning } from "./support/fetch-mock.js"
5
+
6
+ const URL_ = "http://localhost:9999"
7
+ const HEADERS = { apikey: "k", "Content-Type": "application/json" }
8
+
9
+ function memoryStorage(): AuthStorage & { data: Map<string, string> } {
10
+ const data = new Map<string, string>()
11
+ return {
12
+ data,
13
+ getItem: async (k: string) => data.get(k) ?? null,
14
+ setItem: async (k: string, v: string) => void data.set(k, v),
15
+ removeItem: async (k: string) => void data.delete(k),
16
+ }
17
+ }
18
+
19
+ function tokenWith(claims: Record<string, unknown>): string {
20
+ const enc = (o: unknown): string => Buffer.from(JSON.stringify(o)).toString("base64url")
21
+ return `${enc({ alg: "HS256" })}.${enc({ exp: 4102444800, ...claims })}.sig`
22
+ }
23
+
24
+ const ANON_RESPONSE = {
25
+ access_token: tokenWith({ is_anonymous: true }),
26
+ refresh_token: "r",
27
+ token_type: "bearer",
28
+ expires_in: 3600,
29
+ user: {
30
+ id: "u1",
31
+ is_anonymous: true,
32
+ created_at: "2024-01-01T00:00:00Z",
33
+ updated_at: "2024-01-01T00:00:00Z",
34
+ identities: [
35
+ { id: "i1", user_id: "u1", identity_id: "x", provider: "anonymous", identity_data: { a: 1 }, created_at: "c", updated_at: "u", last_sign_in_at: "l" },
36
+ ],
37
+ factors: [{ id: "f1", factor_type: "totp", status: "verified", friendly_name: "phone", created_at: "c", updated_at: "u" }],
38
+ },
39
+ }
40
+
41
+ describe("restored session keeps the user's camelCase fields", () => {
42
+ beforeEach(() => vi.restoreAllMocks())
43
+
44
+ it("isAnonymous survives anonymous sign-in, persist and restore", async () => {
45
+ const storage = memoryStorage()
46
+ const first = new AuthClient(URL_, HEADERS, { storage })
47
+ await first.whenReady()
48
+ vi.stubGlobal("fetch", fetchReturning(ANON_RESPONSE, 200))
49
+ const signedIn = await first.signInAnonymously()
50
+ expect(signedIn.data.user?.isAnonymous).toBe(true)
51
+ await vi.waitFor(() => expect(storage.data.size).toBe(1))
52
+
53
+ const second = new AuthClient(URL_, HEADERS, { storage })
54
+ await second.whenReady()
55
+ const { data } = await second.getSession()
56
+ expect(data.session?.user.isAnonymous).toBe(true)
57
+ })
58
+
59
+ it("identities and factors survive a restore", async () => {
60
+ const storage = memoryStorage()
61
+ const first = new AuthClient(URL_, HEADERS, { storage })
62
+ await first.whenReady()
63
+ vi.stubGlobal("fetch", fetchReturning(ANON_RESPONSE, 200))
64
+ const signedIn = await first.signInAnonymously()
65
+ await vi.waitFor(() => expect(storage.data.size).toBe(1))
66
+
67
+ const second = new AuthClient(URL_, HEADERS, { storage })
68
+ await second.whenReady()
69
+ const restored = (await second.getSession()).data.session?.user
70
+ expect(restored?.identities).toEqual(signedIn.data.user?.identities)
71
+ expect(restored?.factors).toEqual(signedIn.data.user?.factors)
72
+ })
73
+
74
+ it("takes isAnonymous from the token claim when the stored user lacks it", async () => {
75
+ const storage = memoryStorage()
76
+ storage.data.set(
77
+ "supatype.auth.session",
78
+ JSON.stringify({ accessToken: tokenWith({ is_anonymous: true }), refreshToken: "r", tokenType: "bearer", expiresIn: 3600, user: { id: "u1" } }),
79
+ )
80
+ const client = new AuthClient(URL_, HEADERS, { storage })
81
+ await client.whenReady()
82
+ expect((await client.getSession()).data.session?.user.isAnonymous).toBe(true)
83
+ })
84
+ })
@@ -211,6 +211,17 @@ describe("AuthClient.signInWithPassword()", () => {
211
211
  expect(url).toBe(`${SUPATYPE_URL}/token?grant_type=password`)
212
212
  })
213
213
 
214
+ it("sends the captcha token the way the auth server reads it, and sends nothing when there is none", async () => {
215
+ const fetch = mockFetch(TOKEN_RESPONSE)
216
+ vi.stubGlobal("fetch", fetch)
217
+
218
+ await freshClient().signInWithPassword({ email: "a@b.com", password: "pass", options: { captchaToken: "captcha-123" } })
219
+ expect(jsonBody(fetchCall(fetch).init)["supatype_meta_security"]).toEqual({ captcha_token: "captcha-123" })
220
+
221
+ await freshClient().signInWithPassword({ email: "a@b.com", password: "pass" })
222
+ expect(jsonBody(fetchCall(fetch, 1).init)).not.toHaveProperty("supatype_meta_security")
223
+ })
224
+
214
225
  it("returns error on invalid credentials", async () => {
215
226
  vi.stubGlobal("fetch", mockFetch({ error_description: "Invalid login credentials" }, false, 400))
216
227
 
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The bindings' shared channel helpers carry the `private` option to the join, and keep the typed
3
+ * refusal a private join can get instead of flattening it to a message.
4
+ */
5
+
6
+ import { afterEach, describe, expect, it } from "vitest"
7
+ import { channelSlot, watchChannel } from "../src/channel-watch.js"
8
+ import { RealtimeChannelError } from "../src/errors.js"
9
+ import type { SubscriptionView } from "../src/table-subscription.js"
10
+ import { ackNewestJoin, simulateServerMessage, subscribeFrames } from "./helpers/mock-websocket.js"
11
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
12
+
13
+ let harness: SocketSwapHarness
14
+
15
+ afterEach(() => harness.restore())
16
+
17
+ function greet(features: string[]): void {
18
+ simulateServerMessage(harness.socket(), { type: "system", status: "ok", message: "authenticated", features })
19
+ }
20
+
21
+ describe("watchChannel with private: true", () => {
22
+ it("joins as private", async () => {
23
+ harness = createSocketSwapHarness()
24
+ watchChannel(harness.realtime, "lot:42", () => undefined, () => undefined, { private: true })
25
+ await harness.settle()
26
+ greet(["private_channels"])
27
+ expect(subscribeFrames(harness.socket(), "lot:42")[0]?.["private"]).toBe(true)
28
+ })
29
+
30
+ it("shows the typed error, with its reason, when the join is refused", async () => {
31
+ harness = createSocketSwapHarness()
32
+ const views: SubscriptionView[] = []
33
+ watchChannel(harness.realtime, "lot:42", () => undefined, (view) => views.push(view), { private: true })
34
+ await harness.settle()
35
+ greet(["private_channels"])
36
+ simulateServerMessage(harness.socket(), {
37
+ type: "system",
38
+ status: "error",
39
+ message: "lot:42 was opened as private, but no Channel declaration matches it",
40
+ channel: "lot:42",
41
+ ref: subscribeFrames(harness.socket(), "lot:42")[0]?.["ref"],
42
+ })
43
+ const error = views.at(-1)?.error
44
+ expect(views.at(-1)?.status).toBe("error")
45
+ expect(error).toBeInstanceOf(RealtimeChannelError)
46
+ expect(error instanceof RealtimeChannelError && error.reason).toBe("not_declared")
47
+ })
48
+
49
+ it("shows the unsupported-server error without sending a join", async () => {
50
+ harness = createSocketSwapHarness()
51
+ const views: SubscriptionView[] = []
52
+ watchChannel(harness.realtime, "lot:42", () => undefined, (view) => views.push(view), { private: true })
53
+ await harness.settle()
54
+ greet([])
55
+ expect(subscribeFrames(harness.socket(), "lot:42")).toHaveLength(0)
56
+ const error = views.at(-1)?.error
57
+ expect(error instanceof RealtimeChannelError && error.reason).toBe("unsupported_server")
58
+ })
59
+ })
60
+
61
+ describe("channelSlot with private: true", () => {
62
+ it("joins every channel it moves to as private", async () => {
63
+ harness = createSocketSwapHarness()
64
+ const slot = channelSlot(harness.realtime, () => undefined, () => undefined, { private: true })
65
+ slot.join("lot:1")
66
+ await harness.settle()
67
+ greet(["private_channels"])
68
+ expect(subscribeFrames(harness.socket(), "lot:1")[0]?.["private"]).toBe(true)
69
+ // Leaving the only channel closes the socket, so the next one meets a new socket and its greeting.
70
+ slot.join("lot:2")
71
+ await harness.settle()
72
+ greet(["private_channels"])
73
+ expect(subscribeFrames(harness.socket(), "lot:2")[0]?.["private"]).toBe(true)
74
+ })
75
+ })
76
+
77
+ describe("watchChannel and channelSlot with a refused send", () => {
78
+ const frame = { type: "system", status: "error", code: "send_denied", message: "not allowed", channel: "lot:42" } as const
79
+
80
+ it("hands a refused send to onRefused and leaves the view connected", async () => {
81
+ harness = createSocketSwapHarness()
82
+ const views: SubscriptionView[] = []
83
+ const refused: unknown[] = []
84
+ watchChannel(harness.realtime, "lot:42", () => undefined, (view) => views.push(view), { private: true }, (r) => refused.push(r))
85
+ await harness.settle()
86
+ greet(["private_channels"])
87
+ ackNewestJoin(harness.socket(), "lot:42")
88
+ simulateServerMessage(harness.socket(), frame)
89
+ expect(refused).toEqual([{ channel: "lot:42", code: "send_denied", message: "not allowed" }])
90
+ expect(views.at(-1)?.status).toBe("connected")
91
+ })
92
+
93
+ it("does the same through a slot", async () => {
94
+ harness = createSocketSwapHarness()
95
+ const refused: unknown[] = []
96
+ const slot = channelSlot(harness.realtime, () => undefined, () => undefined, { private: true }, (r) => refused.push(r))
97
+ slot.join("lot:42")
98
+ await harness.settle()
99
+ greet(["private_channels"])
100
+ ackNewestJoin(harness.socket(), "lot:42")
101
+ simulateServerMessage(harness.socket(), frame)
102
+ expect(refused).toHaveLength(1)
103
+ slot.leave()
104
+ })
105
+ })
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `watchChannel` and `watchConnection`: what the Vue, Svelte and Solid `useChannel` equivalents share.
3
+ */
4
+
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
6
+ import { channelSlot, watchChannel, watchConnection, type SubscriptionView, type RealtimeConnectionState } from "../src/bindings.js"
7
+ import { sentFrames, simulateServerMessage, subscribedChannels } from "./helpers/mock-websocket.js"
8
+ import { createSocketSwapHarness, type SocketSwapHarness } from "./helpers/socket-swap.js"
9
+
10
+ let harness: SocketSwapHarness
11
+
12
+ beforeEach(() => {
13
+ harness = createSocketSwapHarness()
14
+ })
15
+ afterEach(() => harness.restore())
16
+
17
+ describe("watchChannel", () => {
18
+ it("hands setup the channel, joins, and reports the status as a binding view", async () => {
19
+ const views: SubscriptionView[] = []
20
+ const heard = vi.fn()
21
+ watchChannel(
22
+ harness.realtime,
23
+ "auction:1",
24
+ (channel) => channel.onBroadcast("outbid", heard),
25
+ (view) => views.push(view),
26
+ )
27
+ await harness.settle()
28
+ harness.ackJoins()
29
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "auction:1", event: "outbid", payload: { n: 1 } })
30
+
31
+ expect(subscribedChannels(harness.socket())).toEqual(["auction:1"])
32
+ expect(views.map((v) => v.status)).toEqual(["connected"])
33
+ expect(heard).toHaveBeenCalledWith({ n: 1 })
34
+ })
35
+
36
+ it("leaves the channel on the returned unsubscribe", async () => {
37
+ const stop = watchChannel(harness.realtime, "auction:1", () => undefined, () => undefined)
38
+ await harness.settle()
39
+ stop()
40
+
41
+ expect(sentFrames(harness.socket()).some((f) => f["type"] === "unsubscribe" && f["channel"] === "auction:1")).toBe(true)
42
+ })
43
+ })
44
+
45
+ describe("watchConnection", () => {
46
+ it("reports the state it has now, then each change, and stops on unsubscribe", async () => {
47
+ const seen: RealtimeConnectionState[] = []
48
+ const stop = watchConnection(harness.realtime, (state) => seen.push(state))
49
+ expect(seen).toEqual(["disconnected"])
50
+
51
+ harness.realtime.channel("public:task").subscribe(() => undefined)
52
+ await harness.settle()
53
+ expect(seen).toEqual(["disconnected", "connecting", "connected"])
54
+
55
+ stop()
56
+ harness.realtime.disconnect()
57
+ expect(seen).toHaveLength(3)
58
+ })
59
+ })
60
+
61
+ describe("channelSlot", () => {
62
+ it("leaves the old channel and joins the new one, dropping the old one's listeners", async () => {
63
+ const heard: string[] = []
64
+ const views: SubscriptionView[] = []
65
+ const slot = channelSlot(
66
+ harness.realtime,
67
+ (channel) => channel.onBroadcast("ping", () => heard.push("ping")),
68
+ (view) => views.push(view),
69
+ )
70
+ slot.join("room:1")
71
+ await harness.settle()
72
+ harness.ackJoins()
73
+ expect(views.map((v) => v.status)).toEqual(["connected"])
74
+
75
+ slot.join("room:2")
76
+ expect(views.map((v) => v.status)).toEqual(["connected", "connecting"])
77
+ await harness.settle()
78
+ expect(sentFrames(harness.sockets[0] ?? harness.socket()).some((f) => f["type"] === "unsubscribe" && f["channel"] === "room:1")).toBe(true)
79
+
80
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:1", event: "ping", payload: {} })
81
+ expect(heard).toEqual([])
82
+ harness.ackJoins()
83
+ simulateServerMessage(harness.socket(), { type: "broadcast", channel: "room:2", event: "ping", payload: {} })
84
+ expect(heard).toEqual(["ping"])
85
+ slot.leave()
86
+ })
87
+
88
+ it("does nothing when asked to join the channel it is already on", async () => {
89
+ const setup = vi.fn()
90
+ const slot = channelSlot(harness.realtime, setup, () => undefined)
91
+ slot.join("room:1")
92
+ slot.join("room:1")
93
+ await harness.settle()
94
+ expect(setup).toHaveBeenCalledTimes(1)
95
+ slot.leave()
96
+ })
97
+ })