@supatype/client 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 (118) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +112 -72
  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 +13 -0
  7. package/dist/auth.d.ts.map +1 -1
  8. package/dist/auth.js +53 -13
  9. package/dist/auth.js.map +1 -1
  10. package/dist/bindings.d.ts +4 -1
  11. package/dist/bindings.d.ts.map +1 -1
  12. package/dist/bindings.js +2 -1
  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 +7 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +6 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/latest-rows.d.ts +15 -0
  35. package/dist/latest-rows.d.ts.map +1 -1
  36. package/dist/latest-rows.js +14 -7
  37. package/dist/latest-rows.js.map +1 -1
  38. package/dist/public-env.d.ts +13 -0
  39. package/dist/public-env.d.ts.map +1 -0
  40. package/dist/public-env.js +23 -0
  41. package/dist/public-env.js.map +1 -0
  42. package/dist/query-cache.d.ts +2 -1
  43. package/dist/query-cache.d.ts.map +1 -1
  44. package/dist/query-cache.js.map +1 -1
  45. package/dist/query.d.ts +7 -0
  46. package/dist/query.d.ts.map +1 -1
  47. package/dist/query.js +12 -4
  48. package/dist/query.js.map +1 -1
  49. package/dist/realtime-refusals.d.ts +35 -0
  50. package/dist/realtime-refusals.d.ts.map +1 -0
  51. package/dist/realtime-refusals.js +73 -0
  52. package/dist/realtime-refusals.js.map +1 -0
  53. package/dist/realtime.d.ts +87 -8
  54. package/dist/realtime.d.ts.map +1 -1
  55. package/dist/realtime.js +304 -51
  56. package/dist/realtime.js.map +1 -1
  57. package/dist/runtime-env.d.ts +2 -0
  58. package/dist/runtime-env.d.ts.map +1 -1
  59. package/dist/runtime-env.js +45 -5
  60. package/dist/runtime-env.js.map +1 -1
  61. package/dist/table-subscription.d.ts +27 -11
  62. package/dist/table-subscription.d.ts.map +1 -1
  63. package/dist/table-subscription.js +159 -25
  64. package/dist/table-subscription.js.map +1 -1
  65. package/dist/types.d.ts +34 -1
  66. package/dist/types.d.ts.map +1 -1
  67. package/dist/types.js.map +1 -1
  68. package/package.json +2 -2
  69. package/src/auth.ts +55 -12
  70. package/src/bindings.ts +4 -1
  71. package/src/channel-watch.ts +86 -0
  72. package/src/errors.ts +54 -0
  73. package/src/exact-values.ts +101 -13
  74. package/src/field-kinds-registry.ts +2 -3
  75. package/src/index.ts +14 -2
  76. package/src/latest-rows.ts +24 -7
  77. package/src/public-env.ts +22 -0
  78. package/src/query-cache.ts +2 -1
  79. package/src/query.ts +12 -4
  80. package/src/realtime-refusals.ts +100 -0
  81. package/src/realtime.ts +385 -56
  82. package/src/runtime-env.ts +53 -5
  83. package/src/table-subscription.ts +190 -32
  84. package/src/types.ts +40 -1
  85. package/tests/auth-restore-user.test.ts +84 -0
  86. package/tests/auth-sso.test.ts +32 -1
  87. package/tests/auth.test.ts +11 -0
  88. package/tests/channel-watch-private.test.ts +105 -0
  89. package/tests/channel-watch.test.ts +97 -0
  90. package/tests/exact-response.test.ts +101 -0
  91. package/tests/exact-values.test.ts +57 -0
  92. package/tests/examples-runtime-env.test.ts +135 -0
  93. package/tests/field-kinds-registry.test.ts +12 -0
  94. package/tests/helpers/close-event.ts +12 -0
  95. package/tests/helpers/fake-client.ts +38 -0
  96. package/tests/helpers/mock-websocket.ts +22 -0
  97. package/tests/helpers/reactive-options-binding.ts +99 -0
  98. package/tests/public-env.test.ts +43 -0
  99. package/tests/query-cache.test.ts +1 -1
  100. package/tests/query.test.ts +39 -2
  101. package/tests/realtime-connection.test.ts +228 -0
  102. package/tests/realtime-exact-values.test.ts +42 -0
  103. package/tests/realtime-multi-tenant-integration.test.ts +0 -1
  104. package/tests/realtime-private-channels.test.ts +377 -0
  105. package/tests/realtime-refusal-error.test.ts +80 -0
  106. package/tests/realtime-rows-after-broadcast.test.ts +205 -0
  107. package/tests/realtime-session-auth.test.ts +0 -1
  108. package/tests/realtime-shared-channel.test.ts +9 -27
  109. package/tests/realtime-typed-channels.test.ts +49 -0
  110. package/tests/runtime-env-expo.test.ts +58 -0
  111. package/tests/runtime-env.test.ts +49 -0
  112. package/tests/subscribe-frame.test.ts +48 -0
  113. package/tests/table-subscription-rows.test.ts +136 -0
  114. package/tests/table-subscription.test.ts +4 -3
  115. package/tsconfig.json +2 -1
  116. package/tsconfig.tsbuildinfo +1 -1
  117. package/type-tests/declared-channels.ts +30 -0
  118. package/type-tests/tsconfig.json +4 -0
@@ -67,13 +67,22 @@ function present(value: unknown): string | undefined {
67
67
  return typeof value === "string" && value.trim() !== "" ? value : undefined
68
68
  }
69
69
 
70
+ /**
71
+ * `url` without the "/" it may end in. Every path is joined on as `${url}/rest/v1/...`, and
72
+ * `https://api.example.com/` built `//rest/v1/...`, which the gateway refuses as a path with an
73
+ * empty part (0.9.1 release test RB2) and the server on native never routed to an API.
74
+ */
75
+ function withoutTrailingSlash(url: string): string {
76
+ return url.replace(/\/+$/, "")
77
+ }
78
+
70
79
  /** An absolute http or https address, else undefined. */
71
80
  function httpUrl(value: unknown): string | undefined {
72
81
  const text = present(value)
73
82
  if (text === undefined) return undefined
74
83
  try {
75
84
  const protocol = new URL(text).protocol
76
- return protocol === "http:" || protocol === "https:" ? text : undefined
85
+ return protocol === "http:" || protocol === "https:" ? withoutTrailingSlash(text) : undefined
77
86
  } catch {
78
87
  return undefined
79
88
  }
@@ -101,11 +110,18 @@ function buildTimeFix(n: MissingNames): string {
101
110
  )
102
111
  }
103
112
 
113
+ /** The opening every page-side message without the global shares. */
114
+ function noPageGlobal(n: MissingNames): string {
115
+ return (
116
+ `Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
117
+ `window.__SUPATYPE_ENV__ by its first request.\n`
118
+ )
119
+ }
120
+
104
121
  /** In a page: the page set no `__SUPATYPE_ENV__`, so the script that sets it comes first. */
105
122
  function pageMessage(n: MissingNames): string {
106
123
  return (
107
- `Supatype client has no ${n.labels}. createClient was given none, and the page had set no ` +
108
- `window.__SUPATYPE_ENV__ by its first request.\n` +
124
+ noPageGlobal(n) +
109
125
  `When Supatype hosts the app, add <script src="/supatype-env.js" vite-ignore></script> to index.html before ` +
110
126
  `the app's own script, and the server fills them in when the page loads. In a Next.js app, ` +
111
127
  `export GET from @supatype/ssr/next in app/supatype-env.js/route.ts, load it in the root layout ` +
@@ -114,6 +130,30 @@ function pageMessage(n: MissingNames): string {
114
130
  )
115
131
  }
116
132
 
133
+ /**
134
+ * Whether this runs in an Expo app. Expo's runtime sets `globalThis.expo`, on the web as on a phone.
135
+ * The app's own code reads the `EXPO_PUBLIC_` names, so which names were tried is not something the
136
+ * client can see; the global is the one sign it has.
137
+ */
138
+ function isExpoApp(): boolean {
139
+ const expo: unknown = Reflect.get(globalThis, "expo")
140
+ return typeof expo === "object" && expo !== null
141
+ }
142
+
143
+ /**
144
+ * In an Expo app: the page comes from `app/+html.tsx`, not an `index.html` (0.9.2 release test,
145
+ * N-S14), and a native build has no page at all.
146
+ */
147
+ function expoPageMessage(n: MissingNames): string {
148
+ return (
149
+ noPageGlobal(n) +
150
+ `On the web, when Supatype hosts the export, add <script src="/supatype-env.js" /> to the <head> of ` +
151
+ `app/+html.tsx (src/app/+html.tsx when the routes are in src/app), and the server fills them in when ` +
152
+ `the page loads; supatype init adds it to an Expo Router app. A native build has no page to read ` +
153
+ `them from, so it takes them at build time.\n${buildTimeFix(n)}`
154
+ )
155
+ }
156
+
117
157
  /** On a server there is no page: its own variables are what to set. */
118
158
  function serverMessage(n: MissingNames): string {
119
159
  return (
@@ -157,7 +197,8 @@ function pageFaultMessage(n: MissingNames): string {
157
197
  const script = pageEnvScript()
158
198
  const reason = present(pageEnv().error)
159
199
  if (reason !== undefined) return reasonMessage(n, script ?? "/supatype-env.js", reason)
160
- return script === undefined ? pageMessage(n) : scriptDidNotRunMessage(n, script)
200
+ if (script !== undefined) return scriptDidNotRunMessage(n, script)
201
+ return isExpoApp() ? expoPageMessage(n) : pageMessage(n)
161
202
  }
162
203
 
163
204
  /** Each missing value's label and every name it is set under, as the error words them. */
@@ -191,7 +232,8 @@ export class ClientTarget {
191
232
  #resolved: ResolvedClientTarget | undefined
192
233
 
193
234
  constructor(given: Pick<SupatypeClientConfig, "url" | "anonKey">) {
194
- this.#url = present(given.url)
235
+ const url = present(given.url)
236
+ this.#url = url === undefined ? undefined : withoutTrailingSlash(url)
195
237
  this.#anonKey = present(given.anonKey)
196
238
  }
197
239
 
@@ -212,6 +254,12 @@ export class ClientTarget {
212
254
  return this.#findUrl() ?? ""
213
255
  }
214
256
 
257
+ /** The anon key if it can be found now, else an empty string. Never throws. */
258
+ currentAnonKey(): string {
259
+ this.#anonKey ??= present(pageEnv().anonKey)
260
+ return this.#anonKey ?? ""
261
+ }
262
+
215
263
  /** The address as given or as the page has set it, kept once found. */
216
264
  #findUrl(): string | undefined {
217
265
  this.#url ??= httpUrl(pageEnv().url)
@@ -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
 
@@ -90,9 +102,11 @@ export function subscribeToTable<TRow>(
90
102
  * The status and error a binding shows for a channel status.
91
103
  *
92
104
  * A refused join and a reconnect that gave up are both errors: neither is going to deliver
93
- * anything without the caller doing something about it.
105
+ * anything without the caller doing something about it. A refusal shows the server's reason when
106
+ * the channel passed one (`err`), such as which table does not exist; "Subscription error" only
107
+ * when it did not.
94
108
  */
95
- export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
109
+ export function subscriptionViewOf(status: ChannelStatus, err?: Error | undefined): SubscriptionView {
96
110
  switch (status) {
97
111
  case "SUBSCRIBING":
98
112
  return { status: "connecting", error: null }
@@ -101,60 +115,204 @@ export function subscriptionViewOf(status: ChannelStatus): SubscriptionView {
101
115
  case "CLOSED":
102
116
  return { status: "disconnected", error: null }
103
117
  case "CHANNEL_ERROR":
104
- return { status: "error", error: new SupatypeError({ 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" }) }
105
120
  case "TIMED_OUT":
106
121
  return { status: "error", error: new SupatypeError({ message: "Realtime connection timed out" }) }
107
122
  }
108
123
  }
109
124
 
110
- function rowId(row: unknown): unknown {
111
- 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))
112
145
  }
113
146
 
114
147
  /**
115
- * 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).
116
149
  *
117
- * An insert or update always carries the new row; one without it (which the service does not send)
118
- * 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.
119
154
  */
120
- 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[] {
121
160
  const current = rows ?? []
122
- const next = payload.new
123
161
  switch (payload.eventType) {
124
162
  case "INSERT":
125
- return next === null ? current : [...current, next]
126
163
  case "UPDATE":
127
- return next === null ? current : current.map((row) => (rowId(row) === rowId(next) ? next : row))
128
- case "DELETE":
129
- 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
+ }
130
169
  default:
131
170
  return current
132
171
  }
133
172
  }
134
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
+
135
296
  /**
136
297
  * Subscribe to changes on a `public` table, and return the unsubscribe.
137
298
  *
138
299
  * The handlers are told the rows and the connection status; the binding decides where they live.
139
- * The status is watched on the channel `subscribeToTable` already joined, which is what its
140
- * 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.
141
304
  */
142
305
  export function watchTable<TRow>(
143
- realtime: RealtimeClient,
306
+ client: AnyClient,
144
307
  table: string,
145
308
  options: TableWatchOptions | undefined,
146
309
  handlers: TableWatchHandlers<TRow>,
147
310
  ): () => void {
148
- let rows: TRow[] | null = null
149
- const subscription = subscribeToTable<TRow>(
150
- realtime,
151
- table,
152
- (payload) => {
153
- rows = applyRowChange(rows, payload)
154
- handlers.rows(rows)
155
- },
156
- options,
157
- )
158
- subscription.channel.subscribe((status) => handlers.status(subscriptionViewOf(status)))
159
- 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
+ }
160
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 ───────────────────────────────────────────────────────────────
@@ -82,6 +83,11 @@ export interface SignInWithSSOOptions {
82
83
  * accepts it either way.
83
84
  */
84
85
  flowType?: AuthFlowType | undefined
86
+ /**
87
+ * Studio's own sign-in. The auth server then returns the browser to its Studio address and
88
+ * ignores `redirectTo`, as `studio=1` does for `signInWithOAuth`. Apps leave this unset.
89
+ */
90
+ studio?: boolean | undefined
85
91
  }
86
92
 
87
93
  /** Sign in through the SAML identity provider registered for the user's email domain. */
@@ -235,7 +241,7 @@ export interface QueryResult<TData> {
235
241
  error: SupatypeError | null
236
242
  count: number | null
237
243
  meta?: {
238
- cacheStatus?: "HIT" | "MISS" | "BYPASS" | undefined
244
+ cacheStatus?: CacheStatus | undefined
239
245
  /** Present only when the response named restricted columns. Absent means "not stated". */
240
246
  maskedFields?: MaskedField[] | undefined
241
247
  } | undefined
@@ -327,6 +333,39 @@ export type UpdateOptions<TDef extends TableDef> =
327
333
  */
328
334
  export interface SupatypeModels {}
329
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 & {})
330
369
  export interface SupatypeFunctions {}
331
370
 
332
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
+ })
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, afterEach } from "vitest"
2
- import { AuthClient } from "../src/auth.js"
2
+ import { AuthClient, ssoDomain } from "../src/auth.js"
3
3
  import { SupatypeError } from "../src/errors.js"
4
4
  import { createCodeChallengeS256, PKCE_METHOD_S256 } from "../src/pkce.js"
5
5
  import { fetchCall, fetchReturning, jsonBody } from "./support/fetch-mock.js"
@@ -73,6 +73,19 @@ describe("signInWithSSO request", () => {
73
73
  ...PKCE_FIELDS,
74
74
  })
75
75
  })
76
+
77
+ it("sends studio: true only when asked, so the server returns the browser to Studio", async () => {
78
+ stubBrowser(PAGE)
79
+ const fetch = fetchReturning({ url: IDP_URL })
80
+ vi.stubGlobal("fetch", fetch)
81
+ const client = new AuthClient(AUTH_URL, HEADERS)
82
+
83
+ await client.signInWithSSO({ domain: "acme.com", options: { studio: true } })
84
+ await client.signInWithSSO({ domain: "acme.com", options: { studio: false } })
85
+
86
+ expect(jsonBody(fetchCall(fetch, 0).init)).toEqual({ domain: "acme.com", skip_http_redirect: true, studio: true, ...PKCE_FIELDS })
87
+ expect(jsonBody(fetchCall(fetch, 1).init)).toEqual({ domain: "acme.com", skip_http_redirect: true, ...PKCE_FIELDS })
88
+ })
76
89
  })
77
90
 
78
91
  describe("signInWithSSO PKCE", () => {
@@ -258,3 +271,21 @@ describe("an SSO sign-in coming back to the app", () => {
258
271
  expect((await client.getSession()).data.session?.accessToken).toBe(token)
259
272
  })
260
273
  })
274
+
275
+ describe("ssoDomain: the domain SSO is looked up by", () => {
276
+ it("is the part after the last @, trimmed and lower-cased", () => {
277
+ expect(ssoDomain("Admin@Acme.COM")).toBe("acme.com")
278
+ expect(ssoDomain("odd@name@acme.com")).toBe("acme.com")
279
+ expect(ssoDomain(" you@ Acme.com ")).toBe("acme.com")
280
+ })
281
+
282
+ it("is the whole of a bare domain, which an SSO form may be typed with", () => {
283
+ expect(ssoDomain("Acme.com")).toBe("acme.com")
284
+ })
285
+
286
+ it("is null when nothing is left to look up", () => {
287
+ expect(ssoDomain("")).toBeNull()
288
+ expect(ssoDomain("admin@ ")).toBeNull()
289
+ expect(ssoDomain(" ")).toBeNull()
290
+ })
291
+ })
@@ -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