@supatype/client 0.1.0-alpha.6
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 +4 -0
- package/.turbo/turbo-test.log +7 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/dist/auth.d.ts +243 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +560 -0
- package/dist/auth.js.map +1 -0
- package/dist/error-codes-doc.d.ts +31 -0
- package/dist/error-codes-doc.d.ts.map +1 -0
- package/dist/error-codes-doc.js +294 -0
- package/dist/error-codes-doc.js.map +1 -0
- package/dist/errors.d.ts +197 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +162 -0
- package/dist/errors.js.map +1 -0
- package/dist/fetch-with-retry.d.ts +49 -0
- package/dist/fetch-with-retry.d.ts.map +1 -0
- package/dist/fetch-with-retry.js +150 -0
- package/dist/fetch-with-retry.js.map +1 -0
- package/dist/index.d.ts +137 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +225 -0
- package/dist/index.js.map +1 -0
- package/dist/query.d.ts +53 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +216 -0
- package/dist/query.js.map +1 -0
- package/dist/realtime.d.ts +69 -0
- package/dist/realtime.d.ts.map +1 -0
- package/dist/realtime.js +279 -0
- package/dist/realtime.js.map +1 -0
- package/dist/retry.d.ts +24 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +25 -0
- package/dist/retry.js.map +1 -0
- package/dist/serverless-docs.d.ts +38 -0
- package/dist/serverless-docs.d.ts.map +1 -0
- package/dist/serverless-docs.js +83 -0
- package/dist/serverless-docs.js.map +1 -0
- package/dist/storage.d.ts +79 -0
- package/dist/storage.d.ts.map +1 -0
- package/dist/storage.js +130 -0
- package/dist/storage.js.map +1 -0
- package/dist/types.d.ts +141 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +26 -0
- package/src/auth.ts +713 -0
- package/src/error-codes-doc.ts +315 -0
- package/src/errors.ts +201 -0
- package/src/fetch-with-retry.ts +200 -0
- package/src/index.ts +418 -0
- package/src/query.ts +280 -0
- package/src/realtime.ts +418 -0
- package/src/retry.ts +35 -0
- package/src/serverless-docs.ts +107 -0
- package/src/storage.ts +182 -0
- package/src/types.ts +184 -0
- package/tests/auth.test.ts +282 -0
- package/tests/mfa-totp-integration.test.ts +359 -0
- package/tests/query.test.ts +286 -0
- package/tests/rate-limit-integration.test.ts +185 -0
- package/tests/realtime-multi-tenant-integration.test.ts +372 -0
- package/tests/retry-integration.test.ts +212 -0
- package/tests/serverless.test.ts +115 -0
- package/tests/storage-quota-integration.test.ts +189 -0
- package/tests/storage-upload-limit-integration.test.ts +185 -0
- package/tests/types.test.ts +123 -0
- package/tsconfig.json +11 -0
- package/tsconfig.tsbuildinfo +1 -0
package/src/query.ts
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import type { QueryResult, SupatypeError } from "./types.js"
|
|
2
|
+
|
|
3
|
+
// ─── QueryBuilder ─────────────────────────────────────────────────────────────
|
|
4
|
+
|
|
5
|
+
export class QueryBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
6
|
+
private readonly baseUrl: string
|
|
7
|
+
private readonly path: string
|
|
8
|
+
private readonly headers: Record<string, string>
|
|
9
|
+
private readonly params: URLSearchParams
|
|
10
|
+
|
|
11
|
+
constructor(
|
|
12
|
+
baseUrl: string,
|
|
13
|
+
path: string,
|
|
14
|
+
headers: Record<string, string>,
|
|
15
|
+
columns?: string | undefined,
|
|
16
|
+
) {
|
|
17
|
+
this.baseUrl = baseUrl
|
|
18
|
+
this.path = path
|
|
19
|
+
this.headers = { ...headers }
|
|
20
|
+
this.params = new URLSearchParams()
|
|
21
|
+
if (columns !== undefined) {
|
|
22
|
+
this.params.set("select", columns)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
select(columns: string): this {
|
|
27
|
+
this.params.set("select", columns)
|
|
28
|
+
return this
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
eq(column: string, value: unknown): this {
|
|
32
|
+
this.params.append(column, `eq.${String(value)}`)
|
|
33
|
+
return this
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
neq(column: string, value: unknown): this {
|
|
37
|
+
this.params.append(column, `neq.${String(value)}`)
|
|
38
|
+
return this
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
gt(column: string, value: unknown): this {
|
|
42
|
+
this.params.append(column, `gt.${String(value)}`)
|
|
43
|
+
return this
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
gte(column: string, value: unknown): this {
|
|
47
|
+
this.params.append(column, `gte.${String(value)}`)
|
|
48
|
+
return this
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
lt(column: string, value: unknown): this {
|
|
52
|
+
this.params.append(column, `lt.${String(value)}`)
|
|
53
|
+
return this
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
lte(column: string, value: unknown): this {
|
|
57
|
+
this.params.append(column, `lte.${String(value)}`)
|
|
58
|
+
return this
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
like(column: string, pattern: string): this {
|
|
62
|
+
this.params.append(column, `like.${pattern}`)
|
|
63
|
+
return this
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
ilike(column: string, pattern: string): this {
|
|
67
|
+
this.params.append(column, `ilike.${pattern}`)
|
|
68
|
+
return this
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
in(column: string, values: unknown[]): this {
|
|
72
|
+
this.params.append(column, `in.(${values.map(String).join(",")})`)
|
|
73
|
+
return this
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
is(column: string, value: null | boolean): this {
|
|
77
|
+
this.params.append(column, `is.${String(value)}`)
|
|
78
|
+
return this
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
contains(column: string, value: unknown): this {
|
|
82
|
+
this.params.append(column, `cs.${JSON.stringify(value)}`)
|
|
83
|
+
return this
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
containedBy(column: string, value: unknown): this {
|
|
87
|
+
this.params.append(column, `cd.${JSON.stringify(value)}`)
|
|
88
|
+
return this
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
order(
|
|
92
|
+
column: string,
|
|
93
|
+
opts?: { ascending?: boolean | undefined; nullsFirst?: boolean | undefined } | undefined,
|
|
94
|
+
): this {
|
|
95
|
+
const dir = opts?.ascending === false ? "desc" : "asc"
|
|
96
|
+
const nulls = opts?.nullsFirst === true ? "nullsfirst" : "nullslast"
|
|
97
|
+
this.params.append("order", `${column}.${dir}.${nulls}`)
|
|
98
|
+
return this
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
limit(count: number): this {
|
|
102
|
+
this.params.set("limit", String(count))
|
|
103
|
+
return this
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Set the locale for resolving localized fields. */
|
|
107
|
+
locale(code: string): this {
|
|
108
|
+
this.headers["Accept-Language"] = code
|
|
109
|
+
return this
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
range(from: number, to: number): this {
|
|
113
|
+
this.headers["Range"] = `${from}-${to}`
|
|
114
|
+
this.headers["Range-Unit"] = "items"
|
|
115
|
+
return this
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Return a single row (errors if none or many found). */
|
|
119
|
+
async single(): Promise<QueryResult<TRow>> {
|
|
120
|
+
const headers = {
|
|
121
|
+
...this.headers,
|
|
122
|
+
Accept: "application/vnd.pgrst.object+json",
|
|
123
|
+
}
|
|
124
|
+
const { data, error } = await this._fetch(headers)
|
|
125
|
+
if (error !== null) return { data: null, error, count: null }
|
|
126
|
+
return { data: data as unknown as TRow, error: null, count: 1 }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Return a single row or null (errors if many found). */
|
|
130
|
+
async maybeSingle(): Promise<QueryResult<TRow | null>> {
|
|
131
|
+
const { data, error, count } = await this._fetch(this.headers)
|
|
132
|
+
if (error !== null) return { data: null, error, count: null }
|
|
133
|
+
const rows = data as TRow[]
|
|
134
|
+
const row = rows.length > 0 ? (rows[0] ?? null) : null
|
|
135
|
+
return { data: row, error: null, count }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
then<R1 = QueryResult<TRow[]>, R2 = never>(
|
|
139
|
+
onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
140
|
+
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
141
|
+
): PromiseLike<R1 | R2> {
|
|
142
|
+
return this._fetch(this.headers).then(onfulfilled, onrejected)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private async _fetch(headers: Record<string, string>): Promise<QueryResult<TRow[]>> {
|
|
146
|
+
const qs = this.params.toString()
|
|
147
|
+
const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
148
|
+
let res: Response
|
|
149
|
+
try {
|
|
150
|
+
res = await fetch(url, { headers })
|
|
151
|
+
} catch (e) {
|
|
152
|
+
return {
|
|
153
|
+
data: null,
|
|
154
|
+
error: { message: e instanceof Error ? e.message : "Network error" },
|
|
155
|
+
count: null,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const contentRange = res.headers.get("content-range")
|
|
160
|
+
const count =
|
|
161
|
+
contentRange !== null
|
|
162
|
+
? parseInt(contentRange.split("/")[1] ?? "0", 10)
|
|
163
|
+
: null
|
|
164
|
+
|
|
165
|
+
if (!res.ok) {
|
|
166
|
+
const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
|
|
167
|
+
return {
|
|
168
|
+
data: null,
|
|
169
|
+
error: {
|
|
170
|
+
message: String(err["message"] ?? err["hint"] ?? "Request failed"),
|
|
171
|
+
status: res.status,
|
|
172
|
+
...(err["code"] !== undefined && { code: String(err["code"]) }),
|
|
173
|
+
},
|
|
174
|
+
count: null,
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const json = await res.json() as TRow[]
|
|
179
|
+
return { data: json, error: null, count }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ─── MutationBuilder ──────────────────────────────────────────────────────────
|
|
184
|
+
|
|
185
|
+
type HttpMethod = "POST" | "PATCH" | "DELETE"
|
|
186
|
+
|
|
187
|
+
export class MutationBuilder<TRow> implements PromiseLike<QueryResult<TRow[]>> {
|
|
188
|
+
private readonly baseUrl: string
|
|
189
|
+
private readonly path: string
|
|
190
|
+
private readonly headers: Record<string, string>
|
|
191
|
+
private readonly method: HttpMethod
|
|
192
|
+
private readonly body: unknown
|
|
193
|
+
private readonly params: URLSearchParams
|
|
194
|
+
|
|
195
|
+
constructor(
|
|
196
|
+
baseUrl: string,
|
|
197
|
+
path: string,
|
|
198
|
+
headers: Record<string, string>,
|
|
199
|
+
method: HttpMethod,
|
|
200
|
+
body?: unknown,
|
|
201
|
+
opts?: { upsert?: boolean | undefined } | undefined,
|
|
202
|
+
) {
|
|
203
|
+
this.baseUrl = baseUrl
|
|
204
|
+
this.path = path
|
|
205
|
+
this.headers = { ...headers }
|
|
206
|
+
this.method = method
|
|
207
|
+
this.body = body
|
|
208
|
+
this.params = new URLSearchParams()
|
|
209
|
+
|
|
210
|
+
if (opts?.upsert === true) {
|
|
211
|
+
this.headers["Prefer"] = "resolution=merge-duplicates"
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Return inserted/updated rows
|
|
215
|
+
if (method !== "DELETE") {
|
|
216
|
+
this.headers["Prefer"] = (this.headers["Prefer"] ?? "") + ",return=representation"
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
eq(column: string, value: unknown): this {
|
|
221
|
+
this.params.append(column, `eq.${String(value)}`)
|
|
222
|
+
return this
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
neq(column: string, value: unknown): this {
|
|
226
|
+
this.params.append(column, `neq.${String(value)}`)
|
|
227
|
+
return this
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
then<R1 = QueryResult<TRow[]>, R2 = never>(
|
|
231
|
+
onfulfilled?: ((value: QueryResult<TRow[]>) => R1 | PromiseLike<R1>) | null | undefined,
|
|
232
|
+
onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined,
|
|
233
|
+
): PromiseLike<R1 | R2> {
|
|
234
|
+
return this._execute().then(onfulfilled, onrejected)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
private async _execute(): Promise<QueryResult<TRow[]>> {
|
|
238
|
+
const qs = this.params.toString()
|
|
239
|
+
const url = `${this.baseUrl}${this.path}${qs ? `?${qs}` : ""}`
|
|
240
|
+
let res: Response
|
|
241
|
+
try {
|
|
242
|
+
res = await fetch(url, {
|
|
243
|
+
method: this.method,
|
|
244
|
+
headers: this.headers,
|
|
245
|
+
...(this.body !== undefined && { body: JSON.stringify(this.body) }),
|
|
246
|
+
})
|
|
247
|
+
} catch (e) {
|
|
248
|
+
return {
|
|
249
|
+
data: null,
|
|
250
|
+
error: { message: e instanceof Error ? e.message : "Network error" },
|
|
251
|
+
count: null,
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (!res.ok) {
|
|
256
|
+
const err = await res.json().catch(() => ({ message: "Error" })) as Record<string, unknown>
|
|
257
|
+
return {
|
|
258
|
+
data: null,
|
|
259
|
+
error: {
|
|
260
|
+
message: String(err["message"] ?? err["hint"] ?? "Request failed"),
|
|
261
|
+
status: res.status,
|
|
262
|
+
...(err["code"] !== undefined && { code: String(err["code"]) }),
|
|
263
|
+
},
|
|
264
|
+
count: null,
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (res.status === 204) {
|
|
269
|
+
return { data: [], error: null, count: 0 }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const json = await res.json() as TRow | TRow[]
|
|
273
|
+
const data = Array.isArray(json) ? json : [json]
|
|
274
|
+
return { data, error: null, count: data.length }
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ─── StorageError ─────────────────────────────────────────────────────────────
|
|
279
|
+
|
|
280
|
+
export type { SupatypeError }
|
package/src/realtime.ts
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
export type RealtimeEvent = "INSERT" | "UPDATE" | "DELETE" | "*"
|
|
2
|
+
|
|
3
|
+
export interface RealtimePayload<TRow> {
|
|
4
|
+
eventType: RealtimeEvent
|
|
5
|
+
new: TRow | null
|
|
6
|
+
old: TRow | null
|
|
7
|
+
schema: string
|
|
8
|
+
table: string
|
|
9
|
+
commitTimestamp: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
type RealtimeCallback<TRow> = (payload: RealtimePayload<TRow>) => void
|
|
13
|
+
|
|
14
|
+
export type ChannelStatus = "SUBSCRIBED" | "SUBSCRIBING" | "CLOSED" | "CHANNEL_ERROR" | "TIMED_OUT"
|
|
15
|
+
|
|
16
|
+
interface ChannelSubscription<TRow> {
|
|
17
|
+
on(
|
|
18
|
+
event: "postgres_changes",
|
|
19
|
+
opts: {
|
|
20
|
+
event: RealtimeEvent
|
|
21
|
+
schema?: string | undefined
|
|
22
|
+
table?: string | undefined
|
|
23
|
+
filter?: string | undefined
|
|
24
|
+
},
|
|
25
|
+
callback: RealtimeCallback<TRow>,
|
|
26
|
+
): ChannelSubscription<TRow>
|
|
27
|
+
/** Listen for presence changes. */
|
|
28
|
+
onPresence(
|
|
29
|
+
callback: (event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void,
|
|
30
|
+
): ChannelSubscription<TRow>
|
|
31
|
+
/** Listen for broadcast events. */
|
|
32
|
+
onBroadcast(
|
|
33
|
+
event: string,
|
|
34
|
+
callback: (payload: Record<string, unknown>) => void,
|
|
35
|
+
): ChannelSubscription<TRow>
|
|
36
|
+
/** Subscribe to the channel, opening the WebSocket if needed. */
|
|
37
|
+
subscribe(callback?: ((status: ChannelStatus) => void) | undefined): ChannelSubscription<TRow>
|
|
38
|
+
/** Unsubscribe and clean up. */
|
|
39
|
+
unsubscribe(): void
|
|
40
|
+
/** Send a broadcast event to the channel. */
|
|
41
|
+
broadcast(event: string, payload: Record<string, unknown>): void
|
|
42
|
+
/** Track presence in this channel. */
|
|
43
|
+
track(payload: Record<string, unknown>): void
|
|
44
|
+
/** Stop tracking presence. */
|
|
45
|
+
untrack(): void
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface PresenceEntry {
|
|
49
|
+
user_id: string
|
|
50
|
+
[key: string]: unknown
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ─── Server message types (subset matching @supatype/realtime) ───────────────
|
|
54
|
+
|
|
55
|
+
interface ServerChangeMessage {
|
|
56
|
+
type: "change"
|
|
57
|
+
channel: string
|
|
58
|
+
event: "INSERT" | "UPDATE" | "DELETE"
|
|
59
|
+
payload: { old: Record<string, unknown> | null; new: Record<string, unknown> | null }
|
|
60
|
+
timestamp: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface ServerPresenceMessage {
|
|
64
|
+
type: "presence"
|
|
65
|
+
channel: string
|
|
66
|
+
joins: PresenceEntry[]
|
|
67
|
+
leaves: PresenceEntry[]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface ServerBroadcastMessage {
|
|
71
|
+
type: "broadcast"
|
|
72
|
+
channel: string
|
|
73
|
+
event: string
|
|
74
|
+
payload: Record<string, unknown>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface ServerSystemMessage {
|
|
78
|
+
type: "system"
|
|
79
|
+
status: "ok" | "error"
|
|
80
|
+
message: string
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
type ServerMessage = ServerChangeMessage | ServerPresenceMessage | ServerBroadcastMessage | ServerSystemMessage
|
|
84
|
+
|
|
85
|
+
// ─── Realtime client ─────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
export class RealtimeClient {
|
|
88
|
+
private readonly url: string
|
|
89
|
+
private readonly headers: Record<string, string>
|
|
90
|
+
private ws: WebSocket | null = null
|
|
91
|
+
private channels = new Map<string, ChannelState>()
|
|
92
|
+
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
|
93
|
+
private reconnectAttempts = 0
|
|
94
|
+
private maxReconnectAttempts = 10
|
|
95
|
+
private baseReconnectDelay = 1000
|
|
96
|
+
|
|
97
|
+
constructor(url: string, headers: Record<string, string>) {
|
|
98
|
+
// Convert http(s) URL to ws(s) URL
|
|
99
|
+
this.url = url.replace(/^http/, "ws")
|
|
100
|
+
this.headers = headers
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
channel<TRow = Record<string, unknown>>(name: string): ChannelSubscription<TRow> {
|
|
104
|
+
const state = this.getOrCreateChannel(name)
|
|
105
|
+
|
|
106
|
+
const sub: ChannelSubscription<TRow> = {
|
|
107
|
+
on(_event, opts, callback) {
|
|
108
|
+
state.pgListeners.push({
|
|
109
|
+
event: opts.event,
|
|
110
|
+
schema: opts.schema ?? "public",
|
|
111
|
+
table: opts.table ?? name.split(":").pop() ?? name,
|
|
112
|
+
filter: opts.filter,
|
|
113
|
+
callback: callback as RealtimeCallback<Record<string, unknown>>,
|
|
114
|
+
})
|
|
115
|
+
return sub
|
|
116
|
+
},
|
|
117
|
+
|
|
118
|
+
onPresence(callback) {
|
|
119
|
+
state.presenceListeners.push(callback)
|
|
120
|
+
return sub
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
onBroadcast(event, callback) {
|
|
124
|
+
if (!state.broadcastListeners.has(event)) {
|
|
125
|
+
state.broadcastListeners.set(event, [])
|
|
126
|
+
}
|
|
127
|
+
state.broadcastListeners.get(event)!.push(callback)
|
|
128
|
+
return sub
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
subscribe: (callback) => {
|
|
132
|
+
state.statusCallback = callback ?? null
|
|
133
|
+
this.ensureConnection()
|
|
134
|
+
this.sendSubscribe(state)
|
|
135
|
+
return sub
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
unsubscribe: () => {
|
|
139
|
+
this.sendUnsubscribe(state)
|
|
140
|
+
this.channels.delete(name)
|
|
141
|
+
// Close WebSocket if no channels left
|
|
142
|
+
if (this.channels.size === 0) {
|
|
143
|
+
this.disconnect()
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
|
|
147
|
+
broadcast: (event, payload) => {
|
|
148
|
+
this.sendMessage({
|
|
149
|
+
type: "broadcast",
|
|
150
|
+
channel: name,
|
|
151
|
+
event,
|
|
152
|
+
payload,
|
|
153
|
+
})
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
track: (payload) => {
|
|
157
|
+
this.sendMessage({
|
|
158
|
+
type: "presence_track",
|
|
159
|
+
channel: name,
|
|
160
|
+
payload,
|
|
161
|
+
})
|
|
162
|
+
},
|
|
163
|
+
|
|
164
|
+
untrack: () => {
|
|
165
|
+
this.sendMessage({
|
|
166
|
+
type: "presence_untrack",
|
|
167
|
+
channel: name,
|
|
168
|
+
})
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return sub
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Remove a channel by name. */
|
|
176
|
+
removeChannel(name: string): void {
|
|
177
|
+
const state = this.channels.get(name)
|
|
178
|
+
if (state) {
|
|
179
|
+
this.sendUnsubscribe(state)
|
|
180
|
+
this.channels.delete(name)
|
|
181
|
+
}
|
|
182
|
+
if (this.channels.size === 0) {
|
|
183
|
+
this.disconnect()
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Disconnect the WebSocket entirely. */
|
|
188
|
+
disconnect(): void {
|
|
189
|
+
if (this.reconnectTimer) {
|
|
190
|
+
clearTimeout(this.reconnectTimer)
|
|
191
|
+
this.reconnectTimer = null
|
|
192
|
+
}
|
|
193
|
+
if (this.ws) {
|
|
194
|
+
this.ws.close(1000, "client disconnect")
|
|
195
|
+
this.ws = null
|
|
196
|
+
}
|
|
197
|
+
this.reconnectAttempts = 0
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ─── Internal ──────────────────────────────────────────────────────────
|
|
201
|
+
|
|
202
|
+
private getOrCreateChannel(name: string): ChannelState {
|
|
203
|
+
let state = this.channels.get(name)
|
|
204
|
+
if (!state) {
|
|
205
|
+
state = {
|
|
206
|
+
name,
|
|
207
|
+
pgListeners: [],
|
|
208
|
+
presenceListeners: [],
|
|
209
|
+
broadcastListeners: new Map(),
|
|
210
|
+
statusCallback: null,
|
|
211
|
+
subscribed: false,
|
|
212
|
+
}
|
|
213
|
+
this.channels.set(name, state)
|
|
214
|
+
}
|
|
215
|
+
return state
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private ensureConnection(): void {
|
|
219
|
+
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Build URL with token from apikey header
|
|
224
|
+
const token = this.headers["apikey"] ?? this.headers["Authorization"]?.replace("Bearer ", "")
|
|
225
|
+
const wsUrl = token ? `${this.url}?token=${encodeURIComponent(token)}` : this.url
|
|
226
|
+
|
|
227
|
+
this.ws = new WebSocket(wsUrl)
|
|
228
|
+
|
|
229
|
+
this.ws.onopen = () => {
|
|
230
|
+
this.reconnectAttempts = 0
|
|
231
|
+
// Re-subscribe all channels
|
|
232
|
+
for (const state of this.channels.values()) {
|
|
233
|
+
if (!state.subscribed) {
|
|
234
|
+
this.sendSubscribe(state)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
this.ws.onmessage = (event) => {
|
|
240
|
+
try {
|
|
241
|
+
const msg = JSON.parse(String(event.data)) as ServerMessage
|
|
242
|
+
this.handleServerMessage(msg)
|
|
243
|
+
} catch {
|
|
244
|
+
// Ignore unparseable messages
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
this.ws.onclose = () => {
|
|
249
|
+
this.ws = null
|
|
250
|
+
// Mark all channels as unsubscribed
|
|
251
|
+
for (const state of this.channels.values()) {
|
|
252
|
+
state.subscribed = false
|
|
253
|
+
}
|
|
254
|
+
// Attempt reconnection with exponential backoff
|
|
255
|
+
if (this.channels.size > 0) {
|
|
256
|
+
this.scheduleReconnect()
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
this.ws.onerror = () => {
|
|
261
|
+
// onclose will fire after onerror
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private scheduleReconnect(): void {
|
|
266
|
+
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
267
|
+
for (const state of this.channels.values()) {
|
|
268
|
+
state.statusCallback?.("TIMED_OUT")
|
|
269
|
+
}
|
|
270
|
+
return
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const delay = this.baseReconnectDelay * Math.pow(2, this.reconnectAttempts)
|
|
274
|
+
this.reconnectAttempts++
|
|
275
|
+
|
|
276
|
+
for (const state of this.channels.values()) {
|
|
277
|
+
state.statusCallback?.("SUBSCRIBING")
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
this.reconnectTimer = setTimeout(() => {
|
|
281
|
+
this.ensureConnection()
|
|
282
|
+
}, delay)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private handleServerMessage(msg: ServerMessage): void {
|
|
286
|
+
switch (msg.type) {
|
|
287
|
+
case "system":
|
|
288
|
+
this.handleSystem(msg)
|
|
289
|
+
break
|
|
290
|
+
case "change":
|
|
291
|
+
this.handleChange(msg)
|
|
292
|
+
break
|
|
293
|
+
case "presence":
|
|
294
|
+
this.handlePresence(msg)
|
|
295
|
+
break
|
|
296
|
+
case "broadcast":
|
|
297
|
+
this.handleBroadcastMsg(msg)
|
|
298
|
+
break
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
private handleSystem(msg: ServerSystemMessage): void {
|
|
303
|
+
// When server confirms subscription
|
|
304
|
+
if (msg.status === "ok" && msg.message.startsWith("subscribed to ")) {
|
|
305
|
+
const channel = msg.message.replace("subscribed to ", "")
|
|
306
|
+
const state = this.channels.get(channel)
|
|
307
|
+
if (state) {
|
|
308
|
+
state.subscribed = true
|
|
309
|
+
state.statusCallback?.("SUBSCRIBED")
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (msg.status === "error") {
|
|
314
|
+
// Find which channel this error relates to — broadcast to all as fallback
|
|
315
|
+
for (const state of this.channels.values()) {
|
|
316
|
+
state.statusCallback?.("CHANNEL_ERROR")
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private handleChange(msg: ServerChangeMessage): void {
|
|
322
|
+
const state = this.channels.get(msg.channel)
|
|
323
|
+
if (!state) return
|
|
324
|
+
|
|
325
|
+
// Parse channel to get schema/table
|
|
326
|
+
const parts = msg.channel.split(":")
|
|
327
|
+
const schema = parts.length >= 2 ? parts[0]! : "public"
|
|
328
|
+
const table = parts.length >= 2 ? parts[1]! : parts[0]!
|
|
329
|
+
|
|
330
|
+
const payload: RealtimePayload<Record<string, unknown>> = {
|
|
331
|
+
eventType: msg.event,
|
|
332
|
+
new: msg.payload.new,
|
|
333
|
+
old: msg.payload.old,
|
|
334
|
+
schema,
|
|
335
|
+
table,
|
|
336
|
+
commitTimestamp: msg.timestamp,
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
for (const listener of state.pgListeners) {
|
|
340
|
+
if (listener.event !== "*" && listener.event !== msg.event) continue
|
|
341
|
+
listener.callback(payload)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
private handlePresence(msg: ServerPresenceMessage): void {
|
|
346
|
+
const state = this.channels.get(msg.channel)
|
|
347
|
+
if (!state) return
|
|
348
|
+
|
|
349
|
+
for (const listener of state.presenceListeners) {
|
|
350
|
+
listener({ joins: msg.joins, leaves: msg.leaves })
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
private handleBroadcastMsg(msg: ServerBroadcastMessage): void {
|
|
355
|
+
const state = this.channels.get(msg.channel)
|
|
356
|
+
if (!state) return
|
|
357
|
+
|
|
358
|
+
const listeners = state.broadcastListeners.get(msg.event)
|
|
359
|
+
if (listeners) {
|
|
360
|
+
for (const listener of listeners) {
|
|
361
|
+
listener(msg.payload)
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private sendSubscribe(state: ChannelState): void {
|
|
367
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
|
|
368
|
+
|
|
369
|
+
// Build filter from the first pg listener (if any)
|
|
370
|
+
const firstListener = state.pgListeners[0]
|
|
371
|
+
const filter: Record<string, string> = {}
|
|
372
|
+
if (firstListener?.filter) {
|
|
373
|
+
// Parse PostgREST filter format "column=eq.value" into { column: "eq.value" }
|
|
374
|
+
for (const part of firstListener.filter.split(",")) {
|
|
375
|
+
const eqIdx = part.indexOf("=")
|
|
376
|
+
if (eqIdx > 0) {
|
|
377
|
+
filter[part.slice(0, eqIdx)] = part.slice(eqIdx + 1)
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
this.sendMessage({
|
|
383
|
+
type: "subscribe",
|
|
384
|
+
channel: state.name,
|
|
385
|
+
event: firstListener?.event ?? "*",
|
|
386
|
+
filter: Object.keys(filter).length > 0 ? filter : undefined,
|
|
387
|
+
})
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
private sendUnsubscribe(state: ChannelState): void {
|
|
391
|
+
this.sendMessage({ type: "unsubscribe", channel: state.name })
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
private sendMessage(msg: Record<string, unknown>): void {
|
|
395
|
+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
|
396
|
+
this.ws.send(JSON.stringify(msg))
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// ─── Internal types ──────────────────────────────────────────────────────────
|
|
402
|
+
|
|
403
|
+
interface PgListener {
|
|
404
|
+
event: RealtimeEvent
|
|
405
|
+
schema: string
|
|
406
|
+
table: string
|
|
407
|
+
filter: string | undefined
|
|
408
|
+
callback: RealtimeCallback<Record<string, unknown>>
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
interface ChannelState {
|
|
412
|
+
name: string
|
|
413
|
+
pgListeners: PgListener[]
|
|
414
|
+
presenceListeners: Array<(event: { joins: PresenceEntry[]; leaves: PresenceEntry[] }) => void>
|
|
415
|
+
broadcastListeners: Map<string, Array<(payload: Record<string, unknown>) => void>>
|
|
416
|
+
statusCallback: ((status: ChannelStatus) => void) | null
|
|
417
|
+
subscribed: boolean
|
|
418
|
+
}
|