@supatype/client 0.9.2 → 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.
- package/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +112 -77
- package/.turbo/turbo-typecheck.log +2 -2
- package/CHANGELOG.md +123 -20
- package/README.md +18 -0
- package/dist/auth.d.ts +4 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +38 -13
- package/dist/auth.js.map +1 -1
- package/dist/bindings.d.ts +3 -0
- package/dist/bindings.d.ts.map +1 -1
- package/dist/bindings.js +1 -0
- package/dist/bindings.js.map +1 -1
- package/dist/channel-watch.d.ts +42 -0
- package/dist/channel-watch.d.ts.map +1 -0
- package/dist/channel-watch.js +59 -0
- package/dist/channel-watch.js.map +1 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +31 -0
- package/dist/errors.js.map +1 -1
- package/dist/exact-values.d.ts +18 -5
- package/dist/exact-values.d.ts.map +1 -1
- package/dist/exact-values.js +76 -12
- package/dist/exact-values.js.map +1 -1
- package/dist/field-kinds-registry.d.ts +1 -1
- package/dist/field-kinds-registry.d.ts.map +1 -1
- package/dist/field-kinds-registry.js +20 -2
- package/dist/field-kinds-registry.js.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/public-env.d.ts +13 -0
- package/dist/public-env.d.ts.map +1 -0
- package/dist/public-env.js +23 -0
- package/dist/public-env.js.map +1 -0
- package/dist/query-cache.d.ts +2 -1
- package/dist/query-cache.d.ts.map +1 -1
- package/dist/query-cache.js.map +1 -1
- package/dist/query.js +1 -1
- package/dist/query.js.map +1 -1
- package/dist/realtime-refusals.d.ts +35 -0
- package/dist/realtime-refusals.d.ts.map +1 -0
- package/dist/realtime-refusals.js +73 -0
- package/dist/realtime-refusals.js.map +1 -0
- package/dist/realtime.d.ts +70 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +198 -18
- package/dist/realtime.js.map +1 -1
- package/dist/runtime-env.d.ts +2 -0
- package/dist/runtime-env.d.ts.map +1 -1
- package/dist/runtime-env.js +5 -0
- package/dist/runtime-env.js.map +1 -1
- package/dist/table-subscription.d.ts +23 -9
- package/dist/table-subscription.d.ts.map +1 -1
- package/dist/table-subscription.js +155 -23
- package/dist/table-subscription.js.map +1 -1
- package/dist/types.d.ts +29 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
- package/src/auth.ts +40 -12
- package/src/bindings.ts +3 -0
- package/src/channel-watch.ts +86 -0
- package/src/errors.ts +54 -0
- package/src/exact-values.ts +101 -13
- package/src/field-kinds-registry.ts +2 -3
- package/src/index.ts +13 -1
- package/src/public-env.ts +22 -0
- package/src/query-cache.ts +2 -1
- package/src/query.ts +1 -1
- package/src/realtime-refusals.ts +100 -0
- package/src/realtime.ts +256 -20
- package/src/runtime-env.ts +6 -0
- package/src/table-subscription.ts +186 -30
- package/src/types.ts +35 -1
- package/tests/auth-restore-user.test.ts +84 -0
- package/tests/auth.test.ts +11 -0
- package/tests/channel-watch-private.test.ts +105 -0
- package/tests/channel-watch.test.ts +97 -0
- package/tests/exact-response.test.ts +101 -0
- package/tests/exact-values.test.ts +57 -0
- package/tests/field-kinds-registry.test.ts +12 -0
- package/tests/helpers/close-event.ts +12 -0
- package/tests/helpers/fake-client.ts +38 -0
- package/tests/public-env.test.ts +43 -0
- package/tests/query-cache.test.ts +1 -1
- package/tests/realtime-connection.test.ts +228 -0
- package/tests/realtime-exact-values.test.ts +42 -0
- package/tests/realtime-private-channels.test.ts +377 -0
- package/tests/realtime-refusal-error.test.ts +2 -1
- package/tests/realtime-typed-channels.test.ts +49 -0
- package/tests/runtime-env.test.ts +14 -0
- package/tests/table-subscription-rows.test.ts +136 -0
- package/tests/table-subscription.test.ts +4 -3
- package/tsconfig.tsbuildinfo +1 -1
- package/type-tests/declared-channels.ts +30 -0
- package/type-tests/tsconfig.json +4 -0
package/src/exact-values.ts
CHANGED
|
@@ -15,25 +15,74 @@
|
|
|
15
15
|
* module exists to remove.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import { isJsonObject } from "./json.js"
|
|
18
|
+
import { isJsonObject, isOneOf } from "./json.js"
|
|
19
19
|
|
|
20
|
-
/**
|
|
21
|
-
|
|
20
|
+
/**
|
|
21
|
+
* The shapes a column can need. `numeric` covers both `decimal` and `money`. The `[]` forms are
|
|
22
|
+
* Postgres arrays of the same, which protect and convert each element the way the single value is.
|
|
23
|
+
*/
|
|
24
|
+
export type ExactKind = "bigint" | "numeric" | "bigint[]" | "numeric[]"
|
|
22
25
|
|
|
23
26
|
/** Column name to kind, for the table being read. */
|
|
24
27
|
export type ExactFields = Readonly<Record<string, ExactKind>>
|
|
25
28
|
|
|
29
|
+
/** Whether this client knows the kind. A newer generator or service may name ones it does not. */
|
|
30
|
+
export const isExactKind = isOneOf(["bigint", "numeric", "bigint[]", "numeric[]"])
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The columns whose kind this client knows. A kind it does not know is ignored, not refused: that
|
|
34
|
+
* column's value passes through as sent, so a future kind never costs a whole row or change.
|
|
35
|
+
*/
|
|
36
|
+
export function knownExactKinds(columns: Readonly<Record<string, string>>): ExactFields {
|
|
37
|
+
const known: Record<string, ExactKind> = {}
|
|
38
|
+
for (const [column, kind] of Object.entries(columns)) {
|
|
39
|
+
if (isExactKind(kind)) known[column] = kind
|
|
40
|
+
}
|
|
41
|
+
return known
|
|
42
|
+
}
|
|
43
|
+
|
|
26
44
|
const WHITESPACE = new Set([" ", "\t", "\n", "\r"])
|
|
27
45
|
const QUOTE = '"'
|
|
28
46
|
|
|
29
|
-
/**
|
|
47
|
+
/**
|
|
48
|
+
* A numeric literal found as the value of a key, or as an element of an array that is, with where
|
|
49
|
+
* it sits in the text. For an element, `key` and `depth` are those of the column holding the
|
|
50
|
+
* array, however deeply the element is nested in it.
|
|
51
|
+
*/
|
|
30
52
|
type KeyedNumber = {
|
|
31
53
|
readonly key: string
|
|
32
54
|
readonly depth: number
|
|
55
|
+
readonly element: boolean
|
|
33
56
|
readonly start: number
|
|
34
57
|
readonly end: number
|
|
35
58
|
}
|
|
36
59
|
|
|
60
|
+
/** An open `{` or `[`, and the column an array belongs to when it is one's value. */
|
|
61
|
+
type Frame = {
|
|
62
|
+
readonly container: "{" | "["
|
|
63
|
+
readonly column: string | null
|
|
64
|
+
readonly columnDepth: number
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The frame for a container just opened. An array that is a key's value belongs to that column, and
|
|
69
|
+
* so does an array nested directly inside it, which is how a multi-dimensional column arrives.
|
|
70
|
+
*/
|
|
71
|
+
function openFrame(
|
|
72
|
+
container: "{" | "[",
|
|
73
|
+
parent: Frame | undefined,
|
|
74
|
+
valueKey: string | null,
|
|
75
|
+
depth: number,
|
|
76
|
+
): Frame {
|
|
77
|
+
if (container === "[" && parent?.container === "[" && parent.column !== null) {
|
|
78
|
+
return { container, column: parent.column, columnDepth: parent.columnDepth }
|
|
79
|
+
}
|
|
80
|
+
if (container === "[" && valueKey !== null) {
|
|
81
|
+
return { container, column: valueKey, columnDepth: depth }
|
|
82
|
+
}
|
|
83
|
+
return { container, column: null, columnDepth: depth }
|
|
84
|
+
}
|
|
85
|
+
|
|
37
86
|
/**
|
|
38
87
|
* Walk the JSON text and report every numeric literal that is the value of a key.
|
|
39
88
|
*
|
|
@@ -44,6 +93,9 @@ function forEachKeyedNumber(body: string, visit: (found: KeyedNumber) => void):
|
|
|
44
93
|
let i = 0
|
|
45
94
|
let depth = 0
|
|
46
95
|
let pendingKey: string | null = null
|
|
96
|
+
// The key whose value is being read, so a `[` can tell which column it opens.
|
|
97
|
+
let valueKey: string | null = null
|
|
98
|
+
const frames: Frame[] = []
|
|
47
99
|
|
|
48
100
|
while (i < body.length) {
|
|
49
101
|
const ch = body.charAt(i)
|
|
@@ -52,31 +104,46 @@ function forEachKeyedNumber(body: string, visit: (found: KeyedNumber) => void):
|
|
|
52
104
|
const end = endOfString(body, i)
|
|
53
105
|
const raw = body.slice(i, end)
|
|
54
106
|
i = end
|
|
107
|
+
valueKey = null
|
|
55
108
|
pendingKey = nextMeaningfulChar(body, i) === ":" ? readKey(raw) : null
|
|
56
109
|
continue
|
|
57
110
|
}
|
|
58
111
|
|
|
59
112
|
if (ch === "{" || ch === "[") {
|
|
113
|
+
frames.push(openFrame(ch, frames[frames.length - 1], valueKey, depth))
|
|
114
|
+
valueKey = null
|
|
60
115
|
depth += 1
|
|
61
116
|
i += 1
|
|
62
117
|
continue
|
|
63
118
|
}
|
|
64
119
|
|
|
65
120
|
if (ch === "}" || ch === "]") {
|
|
121
|
+
frames.pop()
|
|
66
122
|
depth -= 1
|
|
67
123
|
i += 1
|
|
68
124
|
continue
|
|
69
125
|
}
|
|
70
126
|
|
|
127
|
+
const owner = frames[frames.length - 1]
|
|
128
|
+
if (owner?.container === "[" && owner.column !== null && (ch === "-" || isDigit(ch))) {
|
|
129
|
+
const end = endOfNumber(body, i)
|
|
130
|
+
if (end > i) {
|
|
131
|
+
visit({ key: owner.column, depth: owner.columnDepth, element: true, start: i, end })
|
|
132
|
+
i = end
|
|
133
|
+
continue
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
71
137
|
if (ch === ":") {
|
|
72
138
|
i += 1
|
|
73
139
|
while (i < body.length && WHITESPACE.has(body.charAt(i))) i += 1
|
|
74
140
|
const key = pendingKey
|
|
75
141
|
pendingKey = null
|
|
142
|
+
valueKey = key
|
|
76
143
|
if (key !== null) {
|
|
77
144
|
const end = endOfNumber(body, i)
|
|
78
145
|
if (end > i) {
|
|
79
|
-
visit({ key, depth, start: i, end })
|
|
146
|
+
visit({ key, depth, element: false, start: i, end })
|
|
80
147
|
i = end
|
|
81
148
|
}
|
|
82
149
|
}
|
|
@@ -103,7 +170,10 @@ export function quoteExactNumbers(body: string, fields: ExactFields): string {
|
|
|
103
170
|
|
|
104
171
|
const spans: KeyedNumber[] = []
|
|
105
172
|
forEachKeyedNumber(body, (found) => {
|
|
106
|
-
if (found.depth
|
|
173
|
+
if (found.depth !== rowDepth) return
|
|
174
|
+
const kind = fields[found.key]
|
|
175
|
+
// An element only counts inside an array column, and a bare value only outside one.
|
|
176
|
+
if (kind !== undefined && isArrayKind(kind) === found.element) spans.push(found)
|
|
107
177
|
})
|
|
108
178
|
if (spans.length === 0) return body
|
|
109
179
|
|
|
@@ -122,9 +192,12 @@ export function quoteExactNumbers(body: string, fields: ExactFields): string {
|
|
|
122
192
|
/**
|
|
123
193
|
* The columns whose literals will not survive `JSON.parse`.
|
|
124
194
|
*
|
|
125
|
-
* The safety net for when column metadata could not be loaded
|
|
126
|
-
* would quietly restore the corruption this module exists to
|
|
127
|
-
* over-reporting here costs a clear error and under-reporting
|
|
195
|
+
* The safety net for when column metadata could not be loaded, or does not describe a column.
|
|
196
|
+
* Without it a failed metadata fetch would quietly restore the corruption this module exists to
|
|
197
|
+
* remove. Reports at any depth, since over-reporting here costs a clear error and under-reporting
|
|
198
|
+
* costs a wrong number. A literal inside an array counts, at any nesting depth, and is reported
|
|
199
|
+
* under the column holding the array. Columns registered as exact kinds are quoted before this
|
|
200
|
+
* runs, so they are protected rather than reported.
|
|
128
201
|
*/
|
|
129
202
|
export function findLossyNumbers(body: string): string[] {
|
|
130
203
|
const names: string[] = []
|
|
@@ -174,16 +247,31 @@ export function coerceRecordKinds(
|
|
|
174
247
|
let copy: Record<string, unknown> | null = null
|
|
175
248
|
|
|
176
249
|
for (const [name, kind] of Object.entries(fields)) {
|
|
177
|
-
if (kind !== "bigint") continue
|
|
178
250
|
const current = source[name]
|
|
179
|
-
if (typeof current
|
|
180
|
-
|
|
181
|
-
|
|
251
|
+
if (kind === "bigint" && typeof current === "string") {
|
|
252
|
+
copy ??= { ...source }
|
|
253
|
+
copy[name] = BigInt(current)
|
|
254
|
+
} else if (kind === "bigint[]" && Array.isArray(current)) {
|
|
255
|
+
copy ??= { ...source }
|
|
256
|
+
copy[name] = bigintsIn(current)
|
|
257
|
+
}
|
|
182
258
|
}
|
|
183
259
|
|
|
184
260
|
return copy ?? source
|
|
185
261
|
}
|
|
186
262
|
|
|
263
|
+
function isArrayKind(kind: ExactKind): boolean {
|
|
264
|
+
return kind === "bigint[]" || kind === "numeric[]"
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** An array with every quoted element a native bigint, at any depth. Null stays null. */
|
|
268
|
+
function bigintsIn(items: readonly unknown[]): unknown[] {
|
|
269
|
+
return items.map((item) => {
|
|
270
|
+
if (typeof item === "string") return BigInt(item)
|
|
271
|
+
return Array.isArray(item) ? bigintsIn(item) : item
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
|
|
187
275
|
/** Whether parsing this literal as a double changes the value it names. */
|
|
188
276
|
function isLossy(literal: string): boolean {
|
|
189
277
|
const asNumber = Number(literal)
|
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
* had. The gap could not be reported because nothing could detect it. Here, absence is a fact:
|
|
17
17
|
* {@link fieldKindsAreRegistered} is false, and the caller can say so.
|
|
18
18
|
*/
|
|
19
|
-
import type
|
|
20
|
-
import { isJsonObject
|
|
19
|
+
import { isExactKind, type ExactFields, type ExactKind } from "./exact-values.js"
|
|
20
|
+
import { isJsonObject } from "./json.js"
|
|
21
21
|
|
|
22
22
|
/** Table name to its exact-value columns. */
|
|
23
23
|
export type ExactFieldsByTable = Readonly<Record<string, ExactFields>>
|
|
@@ -38,7 +38,6 @@ export type UnrecognisedFieldKindsDocument = {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
const SUPPORTED_VERSION = 1
|
|
41
|
-
const isExactKind = isOneOf(["bigint", "numeric"])
|
|
42
41
|
const NO_FIELDS: ExactFields = {}
|
|
43
42
|
|
|
44
43
|
// Module level, and deliberately not per client. Server-side rendering builds a client per
|
package/src/index.ts
CHANGED
|
@@ -64,6 +64,10 @@ export type {
|
|
|
64
64
|
TableUpdate,
|
|
65
65
|
SupatypeModels,
|
|
66
66
|
SupatypeBuckets,
|
|
67
|
+
SupatypeChannels,
|
|
68
|
+
DeclaredTopic,
|
|
69
|
+
DeclaredTopics,
|
|
70
|
+
ChannelName,
|
|
67
71
|
SupatypeFunctions,
|
|
68
72
|
AugmentedDatabase,
|
|
69
73
|
DraftUpdateOptions,
|
|
@@ -99,11 +103,13 @@ export { QueryCache, defaultQueryCache } from "./query-cache.js"
|
|
|
99
103
|
export { StorageClient, BucketClient } from "./storage.js"
|
|
100
104
|
export type { StorageObject, StorageFolder, StorageListEntry, ListOptions, RemovedObject, StorageReference, TransformOptions } from "./storage.js"
|
|
101
105
|
export { RealtimeClient } from "./realtime.js"
|
|
102
|
-
export type { RealtimeEvent, RealtimePayload, ChannelStatus, ChannelStatusCallback, PresenceEntry } from "./realtime.js"
|
|
106
|
+
export type { RealtimeEvent, RealtimePayload, ChannelStatus, ChannelStatusCallback, ChannelOptions, ChannelSubscription, PresenceEntry, RealtimeConnectionState, RealtimeConnectionListener } from "./realtime.js"
|
|
107
|
+
export type { ChannelActionRefusal, ChannelActionRefusalCode } from "./realtime-refusals.js"
|
|
103
108
|
// The bindings' shared subscription helpers are on `@supatype/client/bindings`, not here.
|
|
104
109
|
export type { TableSubscribeOptions, TableSubscription } from "./table-subscription.js"
|
|
105
110
|
export * from "./errors.js"
|
|
106
111
|
export { MissingClientValuesError, type ClientValue } from "./setup-fault.js"
|
|
112
|
+
export { publicEnv } from "./public-env.js"
|
|
107
113
|
|
|
108
114
|
// Called by the generated `supatype/generated/client.ts`, which is how a project tells the client which
|
|
109
115
|
// columns hold values a JSON parser would destroy. Exported because generated code imports it;
|
|
@@ -567,6 +573,8 @@ class FunctionsClient {
|
|
|
567
573
|
|
|
568
574
|
export interface SupatypeClient<TDatabase extends AnyDatabase = AugmentedDatabase> {
|
|
569
575
|
url: string
|
|
576
|
+
/** The public anon key: as given, else as the page has set it; empty while neither has one. */
|
|
577
|
+
readonly anonKey: string
|
|
570
578
|
/** Service role key, if provided at construction time. Used by developer tools for admin API calls. */
|
|
571
579
|
serviceRoleKey: string | undefined
|
|
572
580
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
@@ -775,6 +783,10 @@ export function createClient<TDatabase extends AnyDatabase = AugmentedDatabase>(
|
|
|
775
783
|
get url(): string {
|
|
776
784
|
return target.currentUrl()
|
|
777
785
|
},
|
|
786
|
+
/** The anon key: as given, else as the page has set it; empty while neither has one. */
|
|
787
|
+
get anonKey(): string {
|
|
788
|
+
return target.currentAnonKey()
|
|
789
|
+
},
|
|
778
790
|
serviceRoleKey: config.serviceRoleKey,
|
|
779
791
|
|
|
780
792
|
from<TTable extends keyof TDatabase["public"]["Tables"] & string>(
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One of the site's own public values, read at page load.
|
|
3
|
+
*
|
|
4
|
+
* `/supatype-env.js` sets `window.__SUPATYPE_ENV__ = { url, anonKey, env: { NAME: "value" } }`, and
|
|
5
|
+
* the names under `env` are the ones set in `build.publicEnv` of `supatype.config.ts` or in Studio's
|
|
6
|
+
* Static site settings. They are not secret: every visitor can read them.
|
|
7
|
+
*
|
|
8
|
+
* The page is read on each call, not when the module loads, because the script may load after the
|
|
9
|
+
* module that asks. A value the script did not set, or a page whose script has not run, is undefined.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { isJsonObject } from "./json.js"
|
|
13
|
+
|
|
14
|
+
/** The value of public value `name`, or undefined when the page has no such value. */
|
|
15
|
+
export function publicEnv(name: string): string | undefined {
|
|
16
|
+
const page = globalThis.__SUPATYPE_ENV__
|
|
17
|
+
if (!isJsonObject(page)) return undefined
|
|
18
|
+
const values = page["env"]
|
|
19
|
+
if (!isJsonObject(values) || !Object.hasOwn(values, name)) return undefined
|
|
20
|
+
const value = values[name]
|
|
21
|
+
return typeof value === "string" ? value : undefined
|
|
22
|
+
}
|
package/src/query-cache.ts
CHANGED
|
@@ -14,7 +14,8 @@ export interface QueryCacheOptions {
|
|
|
14
14
|
key?: string | undefined
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
/** HIT, MISS and BYPASS come from the server cache; CLIENT is an answer from this client's own memory cache. */
|
|
18
|
+
export type CacheStatus = "HIT" | "MISS" | "BYPASS" | "CLIENT" | undefined
|
|
18
19
|
|
|
19
20
|
interface CacheEntry<T> {
|
|
20
21
|
result: QueryResult<T>
|
package/src/query.ts
CHANGED
|
@@ -405,7 +405,7 @@ export class QueryBuilder<TRow> extends FilterBuilder implements PromiseLike<Que
|
|
|
405
405
|
this.applyServerCacheHeader({ ...(await this.getHeaders()), ...mergedExtra })
|
|
406
406
|
|
|
407
407
|
const cached = await this.cachedResult(url, resolveRequestHeaders)
|
|
408
|
-
if (cached) return withMeta(cached, { cacheStatus: "
|
|
408
|
+
if (cached) return withMeta(cached, { cacheStatus: "CLIENT" })
|
|
409
409
|
|
|
410
410
|
let res: Response
|
|
411
411
|
try {
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { RealtimeChannelError, type RealtimeChannelErrorReason } from "./errors.js"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the client says when a `private: true` join meets a server that would ignore the flag and
|
|
5
|
+
* admit an open channel. The join is never sent.
|
|
6
|
+
*/
|
|
7
|
+
export const UNSUPPORTED_SERVER_MESSAGE = "this realtime server does not enforce private channels; upgrade it"
|
|
8
|
+
|
|
9
|
+
/** The feature a server announces on its first frame when it enforces private channels. */
|
|
10
|
+
export const PRIVATE_CHANNELS_FEATURE = "private_channels"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The refusals of something sent on a channel that is itself fine: a broadcast, a presence track,
|
|
14
|
+
* or a payload the channel's send rule rejects. They are not a failed join, so they never move the
|
|
15
|
+
* channel's status; the app hears of them through `onRefused`.
|
|
16
|
+
*/
|
|
17
|
+
export type ChannelActionRefusalCode = "send_denied" | "track_denied" | "payload_refused"
|
|
18
|
+
|
|
19
|
+
/** What `onRefused` hands its callback: which channel, why (the server's fixed code), and in words. */
|
|
20
|
+
export interface ChannelActionRefusal {
|
|
21
|
+
channel: string
|
|
22
|
+
code: ChannelActionRefusalCode
|
|
23
|
+
message: string
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What a refusal frame turned out to be: a reason for the channel's error, or an action refusal. */
|
|
27
|
+
export type RefusalKind = Exclude<RealtimeChannelErrorReason, "unsupported_server"> | ChannelActionRefusalCode
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Every code the server sends (packages/realtime `refusal-codes.ts`). `unsupported_server` is the
|
|
31
|
+
* client's own and is not on the wire.
|
|
32
|
+
*/
|
|
33
|
+
const KNOWN_KINDS: ReadonlyMap<string, RefusalKind> = new Map<string, RefusalKind>(
|
|
34
|
+
(
|
|
35
|
+
[
|
|
36
|
+
"join_denied",
|
|
37
|
+
"not_declared",
|
|
38
|
+
"does_not_fit",
|
|
39
|
+
"unavailable",
|
|
40
|
+
"shared_instance",
|
|
41
|
+
"withdrawn",
|
|
42
|
+
"send_denied",
|
|
43
|
+
"track_denied",
|
|
44
|
+
"payload_refused",
|
|
45
|
+
"refused",
|
|
46
|
+
] as const
|
|
47
|
+
).map((code) => [code, code]),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
/** Whether `kind` is a refusal of an action on a healthy channel rather than of the channel. */
|
|
51
|
+
export function isActionRefusal(kind: RefusalKind): kind is ChannelActionRefusalCode {
|
|
52
|
+
return kind === "send_denied" || kind === "track_denied" || kind === "payload_refused"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The sentences the realtime server refused with before it sent codes (packages/realtime
|
|
57
|
+
* `refusals`), each as the code it now carries. A fallback for an older server only: a frame with a
|
|
58
|
+
* `code` is never read by its sentence, which may be reworded. Dropped once no supported server
|
|
59
|
+
* predates codes.
|
|
60
|
+
*/
|
|
61
|
+
const LEGACY_SENTENCES: ReadonlyArray<readonly [RegExp, RefusalKind]> = [
|
|
62
|
+
[/^access to .+ was withdrawn: /, "withdrawn"],
|
|
63
|
+
[/^not allowed to join /, "join_denied"],
|
|
64
|
+
[/ was opened as private, but no Channel declaration matches it$/, "not_declared"],
|
|
65
|
+
[/ does not fit /, "does_not_fit"],
|
|
66
|
+
[/^could not check access to .+ because the database did not answer; retry$/, "unavailable"],
|
|
67
|
+
[/^private channels are not available on a shared realtime instance$/, "shared_instance"],
|
|
68
|
+
[/^not allowed to broadcast .+: the send rule of .+ refused the payload$/, "payload_refused"],
|
|
69
|
+
[/^not allowed to broadcast on /, "send_denied"],
|
|
70
|
+
[/ declares no send rule, so only the service role may /, "send_denied"],
|
|
71
|
+
[/^not allowed to track presence on /, "track_denied"],
|
|
72
|
+
[/ declares no track rule, so only the service role may /, "track_denied"],
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
function readSentence(message: string): RefusalKind {
|
|
76
|
+
for (const [pattern, kind] of LEGACY_SENTENCES) {
|
|
77
|
+
if (pattern.test(message)) return kind
|
|
78
|
+
}
|
|
79
|
+
return "refused"
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* What a channel-scoped refusal frame is. The server's `code` decides; a code this client does not
|
|
84
|
+
* know is `refused` (a newer server, with the server's own words as the message). Only a frame with
|
|
85
|
+
* no code at all, from an older server, is read from its sentence.
|
|
86
|
+
*/
|
|
87
|
+
export function classifyRefusal(code: string | undefined, message: string): RefusalKind {
|
|
88
|
+
if (code === undefined) return readSentence(message)
|
|
89
|
+
return KNOWN_KINDS.get(code) ?? "refused"
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The typed error for a channel-scoped refusal frame that fails or ends a channel's join. */
|
|
93
|
+
export function channelRefusal(channel: string, message: string, kind: RefusalKind): RealtimeChannelError {
|
|
94
|
+
return new RealtimeChannelError(message, channel, isActionRefusal(kind) ? "refused" : kind)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The error a private join gets from a server that does not announce `private_channels`. */
|
|
98
|
+
export function unsupportedServer(channel: string): RealtimeChannelError {
|
|
99
|
+
return new RealtimeChannelError(UNSUPPORTED_SERVER_MESSAGE, channel, "unsupported_server")
|
|
100
|
+
}
|