usebecky 0.0.0-stage → 0.2.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/README.md +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
2
|
+
const OPEN = 1;
|
|
3
|
+
const g = globalThis;
|
|
4
|
+
function warn(msg) {
|
|
5
|
+
try {
|
|
6
|
+
g.console?.warn?.(`[usebecky] ${msg}`);
|
|
7
|
+
}
|
|
8
|
+
catch { }
|
|
9
|
+
}
|
|
10
|
+
function toError(e) {
|
|
11
|
+
return new UseBeckyError({ code: e?.code ?? 'realtime_error', message: e?.message ?? 'Realtime error.', hint: e?.hint, status: 0 });
|
|
12
|
+
}
|
|
13
|
+
export class RealtimeClient {
|
|
14
|
+
baseUrl;
|
|
15
|
+
key;
|
|
16
|
+
getToken;
|
|
17
|
+
WS;
|
|
18
|
+
heartbeatMs;
|
|
19
|
+
heartbeatTimeoutMs;
|
|
20
|
+
delays;
|
|
21
|
+
idleMs;
|
|
22
|
+
ws = null;
|
|
23
|
+
connecting = false;
|
|
24
|
+
token = null;
|
|
25
|
+
attempts = 0;
|
|
26
|
+
reconnectTimer = null;
|
|
27
|
+
heartbeatTimer = null;
|
|
28
|
+
pongTimer = null;
|
|
29
|
+
idleTimer = null;
|
|
30
|
+
nextId = 1;
|
|
31
|
+
subs = new Map();
|
|
32
|
+
channelMap = new Map();
|
|
33
|
+
_status = 'idle';
|
|
34
|
+
warnedNoWs = false;
|
|
35
|
+
constructor(init) {
|
|
36
|
+
this.baseUrl = init.url.replace(/\/+$/, '');
|
|
37
|
+
this.key = init.key;
|
|
38
|
+
this.getToken = init.getToken;
|
|
39
|
+
const o = init.options ?? {};
|
|
40
|
+
this.WS = o.WebSocket;
|
|
41
|
+
this.heartbeatMs = o.heartbeatIntervalMs ?? 25_000;
|
|
42
|
+
this.heartbeatTimeoutMs = o.heartbeatTimeoutMs ?? 10_000;
|
|
43
|
+
this.delays = o.reconnectDelaysMs ?? [1_000, 2_000, 5_000, 10_000, 30_000];
|
|
44
|
+
this.idleMs = o.idleTimeoutMs ?? 1_000;
|
|
45
|
+
try {
|
|
46
|
+
if (typeof g.window === 'object' && typeof g.addEventListener === 'function') {
|
|
47
|
+
g.addEventListener('online', () => {
|
|
48
|
+
if (!this.ws && this.hasWork())
|
|
49
|
+
this.connectNow();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch { }
|
|
54
|
+
}
|
|
55
|
+
/** Connection status. */
|
|
56
|
+
get status() {
|
|
57
|
+
return this._status;
|
|
58
|
+
}
|
|
59
|
+
subscribe(table, a, b) {
|
|
60
|
+
const options = typeof a === 'function' ? {} : (a ?? {});
|
|
61
|
+
const callback = typeof a === 'function' ? a : b;
|
|
62
|
+
if (typeof callback !== 'function')
|
|
63
|
+
throw new TypeError('baas.realtime.subscribe(table, options, callback): callback must be a function.');
|
|
64
|
+
const sub = { id: `sub${this.nextId++}`, table, event: options.event ?? '*', filter: options.filter, callback, onSubscribed: options.onSubscribed, onError: options.onError };
|
|
65
|
+
this.subs.set(sub.id, sub);
|
|
66
|
+
this.sendSubscribe(sub);
|
|
67
|
+
this.ensureConnected();
|
|
68
|
+
let stopped = false;
|
|
69
|
+
return () => {
|
|
70
|
+
if (stopped)
|
|
71
|
+
return;
|
|
72
|
+
stopped = true;
|
|
73
|
+
this.subs.delete(sub.id);
|
|
74
|
+
this.send({ type: 'unsubscribe', id: sub.id });
|
|
75
|
+
this.maybeIdle();
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** A broadcast + presence channel (chat rooms, cursors, "who's online"). */
|
|
79
|
+
channel(name) {
|
|
80
|
+
let ch = this.channelMap.get(name);
|
|
81
|
+
if (!ch) {
|
|
82
|
+
ch = new RealtimeChannel(this, name);
|
|
83
|
+
this.channelMap.set(name, ch);
|
|
84
|
+
this.send({ type: 'join', channel: name });
|
|
85
|
+
this.ensureConnected();
|
|
86
|
+
}
|
|
87
|
+
return ch;
|
|
88
|
+
}
|
|
89
|
+
/** Close the connection and drop every subscription and channel. */
|
|
90
|
+
disconnect() {
|
|
91
|
+
this.subs.clear();
|
|
92
|
+
for (const ch of this.channelMap.values())
|
|
93
|
+
ch._reset();
|
|
94
|
+
this.channelMap.clear();
|
|
95
|
+
this.close();
|
|
96
|
+
}
|
|
97
|
+
/** Called by the auth client when the user signs in/out or the token is refreshed. */
|
|
98
|
+
setAuth(token) {
|
|
99
|
+
if (token === this.token)
|
|
100
|
+
return;
|
|
101
|
+
const hadToken = !!this.token;
|
|
102
|
+
this.token = token;
|
|
103
|
+
if (!this.ws)
|
|
104
|
+
return;
|
|
105
|
+
if (token && this.ws.readyState === OPEN)
|
|
106
|
+
this.send({ type: 'access_token', token });
|
|
107
|
+
else if (!token && hadToken) {
|
|
108
|
+
// Signed out: reconnect anonymously so RLS sees the anon role.
|
|
109
|
+
this.dropSocket();
|
|
110
|
+
if (this.hasWork())
|
|
111
|
+
this.connectNow();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// ---- internals -------------------------------------------------------------------------
|
|
115
|
+
/** @internal */
|
|
116
|
+
_channelLeft(name) {
|
|
117
|
+
this.channelMap.delete(name);
|
|
118
|
+
this.send({ type: 'leave', channel: name });
|
|
119
|
+
this.maybeIdle();
|
|
120
|
+
}
|
|
121
|
+
/** @internal */
|
|
122
|
+
send(msg) {
|
|
123
|
+
if (this.ws && this.ws.readyState === OPEN) {
|
|
124
|
+
try {
|
|
125
|
+
this.ws.send(JSON.stringify(msg));
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
sendSubscribe(sub) {
|
|
133
|
+
const msg = { type: 'subscribe', id: sub.id, table: sub.table, event: sub.event };
|
|
134
|
+
if (sub.filter)
|
|
135
|
+
msg.filter = sub.filter;
|
|
136
|
+
this.send(msg);
|
|
137
|
+
}
|
|
138
|
+
hasWork() {
|
|
139
|
+
return this.subs.size > 0 || this.channelMap.size > 0;
|
|
140
|
+
}
|
|
141
|
+
ensureConnected() {
|
|
142
|
+
if (this.idleTimer) {
|
|
143
|
+
clearTimeout(this.idleTimer);
|
|
144
|
+
this.idleTimer = null;
|
|
145
|
+
}
|
|
146
|
+
if (this.ws || this.connecting || this.reconnectTimer)
|
|
147
|
+
return;
|
|
148
|
+
this.connectNow();
|
|
149
|
+
}
|
|
150
|
+
maybeIdle() {
|
|
151
|
+
if (this.hasWork() || this.idleTimer)
|
|
152
|
+
return;
|
|
153
|
+
this.idleTimer = setTimeout(() => {
|
|
154
|
+
this.idleTimer = null;
|
|
155
|
+
if (!this.hasWork())
|
|
156
|
+
this.close();
|
|
157
|
+
}, this.idleMs);
|
|
158
|
+
this.idleTimer?.unref?.();
|
|
159
|
+
}
|
|
160
|
+
connectNow() {
|
|
161
|
+
if (this.ws || this.connecting)
|
|
162
|
+
return;
|
|
163
|
+
if (this.reconnectTimer) {
|
|
164
|
+
clearTimeout(this.reconnectTimer);
|
|
165
|
+
this.reconnectTimer = null;
|
|
166
|
+
}
|
|
167
|
+
this.connecting = true;
|
|
168
|
+
this._status = this.attempts > 0 ? 'reconnecting' : 'connecting';
|
|
169
|
+
this.getToken()
|
|
170
|
+
.catch(() => null)
|
|
171
|
+
.then((token) => {
|
|
172
|
+
this.connecting = false;
|
|
173
|
+
if (this.ws || !this.hasWork()) {
|
|
174
|
+
if (!this.ws)
|
|
175
|
+
this._status = 'idle';
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
this.open(token);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
open(token) {
|
|
182
|
+
const WS = this.WS ?? g.WebSocket;
|
|
183
|
+
if (typeof WS !== 'function') {
|
|
184
|
+
if (!this.warnedNoWs) {
|
|
185
|
+
this.warnedNoWs = true;
|
|
186
|
+
warn('Realtime needs WebSocket, which this runtime does not have. Pass one: createClient(url, key, { realtime: { WebSocket } }).');
|
|
187
|
+
}
|
|
188
|
+
this._status = 'idle';
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
this.token = token;
|
|
192
|
+
const params = new URLSearchParams({ apikey: this.key });
|
|
193
|
+
if (token)
|
|
194
|
+
params.set('token', token);
|
|
195
|
+
const url = `${this.baseUrl.replace(/^http/, 'ws')}/realtime/v1/websocket?${params.toString()}`;
|
|
196
|
+
let ws;
|
|
197
|
+
try {
|
|
198
|
+
ws = new WS(url);
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
warn(`Could not open the realtime connection: ${err.message}`);
|
|
202
|
+
this.scheduleReconnect();
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
this.ws = ws;
|
|
206
|
+
ws.onopen = () => {
|
|
207
|
+
if (this.ws !== ws)
|
|
208
|
+
return;
|
|
209
|
+
this.attempts = 0;
|
|
210
|
+
this._status = 'open';
|
|
211
|
+
for (const sub of this.subs.values())
|
|
212
|
+
this.sendSubscribe(sub);
|
|
213
|
+
for (const ch of this.channelMap.values()) {
|
|
214
|
+
ch._reset();
|
|
215
|
+
this.send({ type: 'join', channel: ch.name });
|
|
216
|
+
}
|
|
217
|
+
this.startHeartbeat();
|
|
218
|
+
};
|
|
219
|
+
ws.onmessage = (ev) => {
|
|
220
|
+
if (this.ws !== ws)
|
|
221
|
+
return;
|
|
222
|
+
this.onMessage(ev?.data);
|
|
223
|
+
};
|
|
224
|
+
ws.onclose = () => {
|
|
225
|
+
if (this.ws !== ws)
|
|
226
|
+
return;
|
|
227
|
+
this.dropSocket();
|
|
228
|
+
if (this.hasWork())
|
|
229
|
+
this.scheduleReconnect();
|
|
230
|
+
};
|
|
231
|
+
ws.onerror = () => {
|
|
232
|
+
// A close event always follows; reconnect happens there.
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
onMessage(raw) {
|
|
236
|
+
let text;
|
|
237
|
+
if (typeof raw === 'string')
|
|
238
|
+
text = raw;
|
|
239
|
+
else if (raw instanceof ArrayBuffer || ArrayBuffer.isView(raw))
|
|
240
|
+
text = new TextDecoder().decode(raw);
|
|
241
|
+
else
|
|
242
|
+
return;
|
|
243
|
+
let msg;
|
|
244
|
+
try {
|
|
245
|
+
msg = JSON.parse(text);
|
|
246
|
+
}
|
|
247
|
+
catch {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
switch (msg?.type) {
|
|
251
|
+
case 'pong':
|
|
252
|
+
if (this.pongTimer)
|
|
253
|
+
clearTimeout(this.pongTimer);
|
|
254
|
+
this.pongTimer = null;
|
|
255
|
+
return;
|
|
256
|
+
case 'subscribed': {
|
|
257
|
+
const sub = this.subs.get(msg.id);
|
|
258
|
+
if (sub?.onSubscribed)
|
|
259
|
+
safe(() => sub.onSubscribed());
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
case 'change': {
|
|
263
|
+
const sub = this.subs.get(msg.id);
|
|
264
|
+
if (!sub)
|
|
265
|
+
return;
|
|
266
|
+
if (sub.event !== '*' && msg.event !== sub.event)
|
|
267
|
+
return;
|
|
268
|
+
const change = { event: msg.event, table: msg.table ?? sub.table, new: msg.new ?? null, old: msg.old ?? null, commit_timestamp: msg.commit_timestamp ?? new Date().toISOString() };
|
|
269
|
+
safe(() => sub.callback(change));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
case 'joined':
|
|
273
|
+
this.channelMap.get(msg.channel)?._joined(typeof msg.presence_key === 'string' ? msg.presence_key : null);
|
|
274
|
+
return;
|
|
275
|
+
case 'broadcast':
|
|
276
|
+
this.channelMap.get(msg.channel)?._broadcast(msg.event, msg.payload);
|
|
277
|
+
return;
|
|
278
|
+
case 'presence_state':
|
|
279
|
+
this.channelMap.get(msg.channel)?._presence(msg.state ?? {});
|
|
280
|
+
return;
|
|
281
|
+
case 'error': {
|
|
282
|
+
const err = toError(msg.error);
|
|
283
|
+
const sub = msg.id ? this.subs.get(msg.id) : undefined;
|
|
284
|
+
if (sub) {
|
|
285
|
+
if (sub.onError)
|
|
286
|
+
safe(() => sub.onError(err));
|
|
287
|
+
else
|
|
288
|
+
warn(`Realtime subscription to "${sub.table}" failed: ${err.message}${err.hint ? ' ' + err.hint : ''}`);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const ch = msg.channel ? this.channelMap.get(msg.channel) : undefined;
|
|
292
|
+
if (ch)
|
|
293
|
+
ch._error(err);
|
|
294
|
+
else
|
|
295
|
+
warn(`Realtime error: ${err.message}${err.hint ? ' ' + err.hint : ''}`);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
startHeartbeat() {
|
|
301
|
+
this.stopHeartbeat();
|
|
302
|
+
this.heartbeatTimer = setInterval(() => {
|
|
303
|
+
if (!this.ws || this.ws.readyState !== OPEN)
|
|
304
|
+
return;
|
|
305
|
+
if (this.pongTimer)
|
|
306
|
+
return; // still waiting
|
|
307
|
+
this.send({ type: 'ping' });
|
|
308
|
+
this.pongTimer = setTimeout(() => {
|
|
309
|
+
this.pongTimer = null;
|
|
310
|
+
// No pong: the connection is dead even if the socket thinks otherwise.
|
|
311
|
+
const ws = this.ws;
|
|
312
|
+
this.dropSocket();
|
|
313
|
+
try {
|
|
314
|
+
ws?.close();
|
|
315
|
+
}
|
|
316
|
+
catch { }
|
|
317
|
+
if (this.hasWork())
|
|
318
|
+
this.scheduleReconnect();
|
|
319
|
+
}, this.heartbeatTimeoutMs);
|
|
320
|
+
this.pongTimer?.unref?.();
|
|
321
|
+
}, this.heartbeatMs);
|
|
322
|
+
this.heartbeatTimer?.unref?.();
|
|
323
|
+
}
|
|
324
|
+
stopHeartbeat() {
|
|
325
|
+
if (this.heartbeatTimer)
|
|
326
|
+
clearInterval(this.heartbeatTimer);
|
|
327
|
+
if (this.pongTimer)
|
|
328
|
+
clearTimeout(this.pongTimer);
|
|
329
|
+
this.heartbeatTimer = null;
|
|
330
|
+
this.pongTimer = null;
|
|
331
|
+
}
|
|
332
|
+
/** Forget the current socket (without reconnecting). */
|
|
333
|
+
dropSocket() {
|
|
334
|
+
const ws = this.ws;
|
|
335
|
+
this.ws = null;
|
|
336
|
+
this.stopHeartbeat();
|
|
337
|
+
for (const ch of this.channelMap.values())
|
|
338
|
+
ch._reset();
|
|
339
|
+
this._status = 'idle';
|
|
340
|
+
if (ws) {
|
|
341
|
+
ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null;
|
|
342
|
+
try {
|
|
343
|
+
if (ws.readyState === OPEN || ws.readyState === 0)
|
|
344
|
+
ws.close();
|
|
345
|
+
}
|
|
346
|
+
catch { }
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
scheduleReconnect() {
|
|
350
|
+
if (this.reconnectTimer)
|
|
351
|
+
return;
|
|
352
|
+
const base = this.delays[Math.min(this.attempts, this.delays.length - 1)] ?? 1000;
|
|
353
|
+
const delay = Math.round(base * (0.8 + Math.random() * 0.4));
|
|
354
|
+
this.attempts++;
|
|
355
|
+
this._status = 'reconnecting';
|
|
356
|
+
this.reconnectTimer = setTimeout(() => {
|
|
357
|
+
this.reconnectTimer = null;
|
|
358
|
+
if (this.hasWork())
|
|
359
|
+
this.connectNow();
|
|
360
|
+
else
|
|
361
|
+
this._status = 'idle';
|
|
362
|
+
}, delay);
|
|
363
|
+
this.reconnectTimer?.unref?.();
|
|
364
|
+
}
|
|
365
|
+
close() {
|
|
366
|
+
if (this.reconnectTimer)
|
|
367
|
+
clearTimeout(this.reconnectTimer);
|
|
368
|
+
if (this.idleTimer)
|
|
369
|
+
clearTimeout(this.idleTimer);
|
|
370
|
+
this.reconnectTimer = null;
|
|
371
|
+
this.idleTimer = null;
|
|
372
|
+
this.attempts = 0;
|
|
373
|
+
this.dropSocket();
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
function safe(fn) {
|
|
377
|
+
try {
|
|
378
|
+
fn();
|
|
379
|
+
}
|
|
380
|
+
catch (err) {
|
|
381
|
+
try {
|
|
382
|
+
g.console?.error?.('[usebecky] Error in realtime callback:', err);
|
|
383
|
+
}
|
|
384
|
+
catch { }
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
export class RealtimeChannel {
|
|
388
|
+
name;
|
|
389
|
+
client;
|
|
390
|
+
handlers = new Map();
|
|
391
|
+
presenceHandlers = new Set();
|
|
392
|
+
errorHandlers = new Set();
|
|
393
|
+
state = {};
|
|
394
|
+
tracked = null;
|
|
395
|
+
queue = [];
|
|
396
|
+
isJoined = false;
|
|
397
|
+
left = false;
|
|
398
|
+
key = null;
|
|
399
|
+
constructor(client, name) {
|
|
400
|
+
this.client = client;
|
|
401
|
+
this.name = name;
|
|
402
|
+
}
|
|
403
|
+
/** Your key in the presence state (set once joined). */
|
|
404
|
+
get presenceKey() {
|
|
405
|
+
return this.key;
|
|
406
|
+
}
|
|
407
|
+
/** True once the server confirmed the join. */
|
|
408
|
+
get joined() {
|
|
409
|
+
return this.isJoined;
|
|
410
|
+
}
|
|
411
|
+
/** Listen for a broadcast event (`'*'` for all). Returns a function that stops listening. */
|
|
412
|
+
on(event, callback) {
|
|
413
|
+
let set = this.handlers.get(event);
|
|
414
|
+
if (!set)
|
|
415
|
+
this.handlers.set(event, (set = new Set()));
|
|
416
|
+
set.add(callback);
|
|
417
|
+
return () => {
|
|
418
|
+
set.delete(callback);
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
/** Send a message to everyone else in the channel. */
|
|
422
|
+
send(event, payload = {}) {
|
|
423
|
+
if (this.left)
|
|
424
|
+
return warn(`Channel "${this.name}" was left; create it again with baas.realtime.channel().`);
|
|
425
|
+
const msg = { type: 'broadcast', channel: this.name, event, payload };
|
|
426
|
+
if (!this.isJoined || !this.client.send(msg))
|
|
427
|
+
this.queue.push(msg);
|
|
428
|
+
}
|
|
429
|
+
/** Share your presence state (e.g. `{ name: 'Ada' }`). Re-sent automatically after reconnects. */
|
|
430
|
+
track(state) {
|
|
431
|
+
this.tracked = state;
|
|
432
|
+
if (this.isJoined)
|
|
433
|
+
this.client.send({ type: 'presence', channel: this.name, state });
|
|
434
|
+
}
|
|
435
|
+
/** Stop sharing your presence. */
|
|
436
|
+
untrack() {
|
|
437
|
+
this.tracked = null;
|
|
438
|
+
if (this.isJoined)
|
|
439
|
+
this.client.send({ type: 'presence', channel: this.name, state: null });
|
|
440
|
+
}
|
|
441
|
+
/** Called with everyone's presence (`{ [key]: state }`) whenever it changes. */
|
|
442
|
+
onPresence(callback) {
|
|
443
|
+
this.presenceHandlers.add(callback);
|
|
444
|
+
if (Object.keys(this.state).length)
|
|
445
|
+
safe(() => callback(this.state));
|
|
446
|
+
return () => {
|
|
447
|
+
this.presenceHandlers.delete(callback);
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
/** Called if the server reports an error for this channel. */
|
|
451
|
+
onError(callback) {
|
|
452
|
+
this.errorHandlers.add(callback);
|
|
453
|
+
return () => {
|
|
454
|
+
this.errorHandlers.delete(callback);
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
/** Current presence state. */
|
|
458
|
+
presence() {
|
|
459
|
+
return this.state;
|
|
460
|
+
}
|
|
461
|
+
/** Leave the channel and stop all its listeners. */
|
|
462
|
+
leave() {
|
|
463
|
+
if (this.left)
|
|
464
|
+
return;
|
|
465
|
+
this.left = true;
|
|
466
|
+
if (this.tracked && this.isJoined)
|
|
467
|
+
this.client.send({ type: 'presence', channel: this.name, state: null });
|
|
468
|
+
this.handlers.clear();
|
|
469
|
+
this.presenceHandlers.clear();
|
|
470
|
+
this.queue = [];
|
|
471
|
+
this.isJoined = false;
|
|
472
|
+
this.client._channelLeft(this.name);
|
|
473
|
+
}
|
|
474
|
+
/** @internal */
|
|
475
|
+
_reset() {
|
|
476
|
+
this.isJoined = false;
|
|
477
|
+
}
|
|
478
|
+
/** @internal */
|
|
479
|
+
_joined(presenceKey = null) {
|
|
480
|
+
this.isJoined = true;
|
|
481
|
+
if (presenceKey)
|
|
482
|
+
this.key = presenceKey;
|
|
483
|
+
if (this.tracked)
|
|
484
|
+
this.client.send({ type: 'presence', channel: this.name, state: this.tracked });
|
|
485
|
+
const queued = this.queue;
|
|
486
|
+
this.queue = [];
|
|
487
|
+
for (const msg of queued)
|
|
488
|
+
if (!this.client.send(msg))
|
|
489
|
+
this.queue.push(msg);
|
|
490
|
+
}
|
|
491
|
+
/** @internal */
|
|
492
|
+
_broadcast(event, payload) {
|
|
493
|
+
for (const key of [event, '*']) {
|
|
494
|
+
const set = this.handlers.get(key);
|
|
495
|
+
if (set)
|
|
496
|
+
for (const cb of [...set])
|
|
497
|
+
safe(() => cb(payload, event));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
/** @internal */
|
|
501
|
+
_presence(state) {
|
|
502
|
+
this.state = state;
|
|
503
|
+
for (const cb of [...this.presenceHandlers])
|
|
504
|
+
safe(() => cb(state));
|
|
505
|
+
}
|
|
506
|
+
/** @internal */
|
|
507
|
+
_error(err) {
|
|
508
|
+
if (this.errorHandlers.size === 0)
|
|
509
|
+
warn(`Realtime channel "${this.name}": ${err.message}`);
|
|
510
|
+
for (const cb of [...this.errorHandlers])
|
|
511
|
+
safe(() => cb(err));
|
|
512
|
+
}
|
|
513
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { HttpClient } from '../lib/http.ts';
|
|
2
|
+
import type { Result } from '../lib/types.ts';
|
|
3
|
+
/** Report filters: exact matches per visit; an array means "any of these". `'(none)'` matches visits without a value
|
|
4
|
+
* (not for `page` / `event`). Different filters must all match. */
|
|
5
|
+
export interface AnalyticsFilters {
|
|
6
|
+
/** The website's hostname, like `'shop.example.com'`: one site of the project. */
|
|
7
|
+
hostname?: string | string[];
|
|
8
|
+
/** ISO country code, like `'DE'`. */
|
|
9
|
+
country?: string | string[];
|
|
10
|
+
region?: string | string[];
|
|
11
|
+
city?: string | string[];
|
|
12
|
+
/** utm_source or the referrer's host (`'google.com'`). */
|
|
13
|
+
source?: string | string[];
|
|
14
|
+
channel?: string | string[];
|
|
15
|
+
campaign?: string | string[];
|
|
16
|
+
medium?: string | string[];
|
|
17
|
+
/** The visit viewed this path. */
|
|
18
|
+
page?: string | string[];
|
|
19
|
+
landing_page?: string | string[];
|
|
20
|
+
/** `'desktop'`, `'mobile'` or `'tablet'`. */
|
|
21
|
+
device?: string | string[];
|
|
22
|
+
browser?: string | string[];
|
|
23
|
+
os?: string | string[];
|
|
24
|
+
language?: string | string[];
|
|
25
|
+
/** The visit sent this event. */
|
|
26
|
+
event?: string | string[];
|
|
27
|
+
}
|
|
28
|
+
/** Which days a report covers. */
|
|
29
|
+
export interface AnalyticsPeriod {
|
|
30
|
+
/** `'today'`, `'yesterday'`, `'7d'`, `'30d'` (default), `'90d'`, `'12m'`, `'24m'`. Or `from` + `to`. */
|
|
31
|
+
range?: 'today' | 'yesterday' | '7d' | '30d' | '90d' | '12m' | '24m';
|
|
32
|
+
/** First day (`'2026-11-01'` or a Date), with `to`; both days count. */
|
|
33
|
+
from?: string | Date;
|
|
34
|
+
to?: string | Date;
|
|
35
|
+
/** IANA time zone for the day boundaries, like `'Europe/Berlin'` (default UTC). */
|
|
36
|
+
tz?: string;
|
|
37
|
+
/** `true`: every number also gets the period right before (`{ value, previous }`). */
|
|
38
|
+
compare?: boolean;
|
|
39
|
+
filters?: AnalyticsFilters;
|
|
40
|
+
}
|
|
41
|
+
/** A number of a report: `previous` is the period before (null without `compare`). */
|
|
42
|
+
export interface AnalyticsMetric {
|
|
43
|
+
value: number;
|
|
44
|
+
previous: number | null;
|
|
45
|
+
}
|
|
46
|
+
/** What every report starts with: the period it covers and the filters it used. */
|
|
47
|
+
export interface AnalyticsPeriodView {
|
|
48
|
+
range: string;
|
|
49
|
+
granularity: 'hour' | 'day' | 'week' | 'month';
|
|
50
|
+
from: string;
|
|
51
|
+
to: string;
|
|
52
|
+
tz: string;
|
|
53
|
+
previous_from?: string;
|
|
54
|
+
previous_to?: string;
|
|
55
|
+
filters: Partial<Record<keyof AnalyticsFilters, string[]>>;
|
|
56
|
+
/** Only when the filters matched very many visits: the counts are estimated from 1 in `sample_rate` visits. */
|
|
57
|
+
sample_rate?: number;
|
|
58
|
+
}
|
|
59
|
+
export interface AnalyticsOverview extends AnalyticsPeriodView {
|
|
60
|
+
kpis: {
|
|
61
|
+
visitors: AnalyticsMetric;
|
|
62
|
+
sessions: AnalyticsMetric;
|
|
63
|
+
pageviews: AnalyticsMetric;
|
|
64
|
+
views_per_session: AnalyticsMetric;
|
|
65
|
+
bounce_rate: AnalyticsMetric;
|
|
66
|
+
engaged_sessions: AnalyticsMetric;
|
|
67
|
+
engagement_rate: AnalyticsMetric;
|
|
68
|
+
avg_engagement_ms: AnalyticsMetric;
|
|
69
|
+
time_per_visit_ms: AnalyticsMetric;
|
|
70
|
+
time_per_page_ms: AnalyticsMetric;
|
|
71
|
+
avg_session_ms: AnalyticsMetric;
|
|
72
|
+
conversions: AnalyticsMetric;
|
|
73
|
+
conversion_rate: AnalyticsMetric;
|
|
74
|
+
};
|
|
75
|
+
/** One point per hour / day / week / month (`t`: when it starts), oldest first. */
|
|
76
|
+
series: {
|
|
77
|
+
t: string;
|
|
78
|
+
visitors: number;
|
|
79
|
+
sessions: number;
|
|
80
|
+
pageviews: number;
|
|
81
|
+
conversions: number;
|
|
82
|
+
}[];
|
|
83
|
+
previous_series: {
|
|
84
|
+
t: string;
|
|
85
|
+
visitors: number;
|
|
86
|
+
sessions: number;
|
|
87
|
+
pageviews: number;
|
|
88
|
+
conversions: number;
|
|
89
|
+
}[] | null;
|
|
90
|
+
/** Visitors in the last 5 minutes (the whole project, unfiltered). */
|
|
91
|
+
active_now: number;
|
|
92
|
+
privacy_mode_percent: number;
|
|
93
|
+
}
|
|
94
|
+
/** The one-dimension reports. */
|
|
95
|
+
export type AnalyticsDimension = 'pages' | 'landing_pages' | 'exit_pages' | 'sources' | 'referrers' | 'channels' | 'campaigns' | 'mediums' | 'countries' | 'regions' | 'cities' | 'languages' | 'devices' | 'browsers' | 'os' | 'screen_sizes' | 'visitor_types' | 'hostnames' | 'events' | 'outbound_links' | 'downloads' | 'searches' | 'not_found';
|
|
96
|
+
/** A row of a report: `value` (the page, country code, source, ...), a `label` where there is a nicer name, and its
|
|
97
|
+
* numbers (visitors, sessions, pageviews, bounce_rate, share, ... depending on the report). */
|
|
98
|
+
export interface AnalyticsRow {
|
|
99
|
+
value: string | null;
|
|
100
|
+
label?: string;
|
|
101
|
+
visitors?: number;
|
|
102
|
+
sessions?: number;
|
|
103
|
+
pageviews?: number;
|
|
104
|
+
events?: number;
|
|
105
|
+
/** Percent of the report's total. */
|
|
106
|
+
share?: number;
|
|
107
|
+
[metric: string]: unknown;
|
|
108
|
+
}
|
|
109
|
+
export interface AnalyticsReport extends AnalyticsPeriodView {
|
|
110
|
+
dimension: AnalyticsDimension;
|
|
111
|
+
/** The totals of the period (visitors, sessions, pageviews, bounce_rate, ...). */
|
|
112
|
+
overview: Record<string, number | AnalyticsMetric>;
|
|
113
|
+
/** The rows, in `sort` order. */
|
|
114
|
+
rows: AnalyticsRow[];
|
|
115
|
+
/** Rows matching the search, for "showing 10 of 87". */
|
|
116
|
+
total_rows: number;
|
|
117
|
+
/** Pass back as `cursor` for the next page; `null` on the last one. */
|
|
118
|
+
next_cursor: string | null;
|
|
119
|
+
}
|
|
120
|
+
export interface AnalyticsReportOptions extends AnalyticsPeriod {
|
|
121
|
+
/** Rows per page, 1–100 (default 10). */
|
|
122
|
+
limit?: number;
|
|
123
|
+
/** The number to sort by (`'visitors'`, `'sessions'`, `'pageviews'`, `'bounce_rate'`, ...); default the main one. */
|
|
124
|
+
sort?: string;
|
|
125
|
+
dir?: 'asc' | 'desc';
|
|
126
|
+
/** Search the values (contains, case-insensitive). */
|
|
127
|
+
search?: string;
|
|
128
|
+
/** `next_cursor` of the page before. */
|
|
129
|
+
cursor?: string;
|
|
130
|
+
}
|
|
131
|
+
export interface AnalyticsTimeseries extends AnalyticsPeriodView {
|
|
132
|
+
metric: string;
|
|
133
|
+
dimension: 'channels' | 'devices' | 'countries';
|
|
134
|
+
/** One line per top value. */
|
|
135
|
+
series: {
|
|
136
|
+
value: string | null;
|
|
137
|
+
label?: string;
|
|
138
|
+
total: number;
|
|
139
|
+
points: {
|
|
140
|
+
t: string;
|
|
141
|
+
v: number;
|
|
142
|
+
}[];
|
|
143
|
+
}[];
|
|
144
|
+
}
|
|
145
|
+
export interface AnalyticsTimeseriesOptions extends AnalyticsPeriod {
|
|
146
|
+
metric?: 'visitors' | 'sessions' | 'pageviews' | 'conversions' | 'bounce_rate' | 'engagement_rate' | 'avg_engagement_ms';
|
|
147
|
+
dimension?: 'channels' | 'devices' | 'countries';
|
|
148
|
+
/** Lines, 1–10 (default 5). */
|
|
149
|
+
limit?: number;
|
|
150
|
+
}
|
|
151
|
+
export interface ServerAnalytics {
|
|
152
|
+
/**
|
|
153
|
+
* The headline numbers of a period (visitors, visits, page views, bounce and engagement rate, conversions) and the
|
|
154
|
+
* chart under them.
|
|
155
|
+
*
|
|
156
|
+
* ```ts
|
|
157
|
+
* const { data } = await baas.analytics.overview({ range: '30d', filters: { hostname: 'shop.example.com' } })
|
|
158
|
+
* console.log(data?.kpis.visitors.value)
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
overview(options?: AnalyticsPeriod): Promise<Result<AnalyticsOverview>>;
|
|
162
|
+
/**
|
|
163
|
+
* One report (top pages, sources, countries, devices, ...), a page of rows at a time.
|
|
164
|
+
*
|
|
165
|
+
* ```ts
|
|
166
|
+
* const { data } = await baas.analytics.report('pages', { range: '7d', filters: { hostname: 'shop.example.com' }, limit: 20 })
|
|
167
|
+
* for (const row of data?.rows ?? []) console.log(row.value, row.pageviews)
|
|
168
|
+
* ```
|
|
169
|
+
* Errors: `invalid_dimension`, `invalid_filter`, `invalid_range`, `plan_required` (further back than the plan keeps),
|
|
170
|
+
* `query_too_broad`.
|
|
171
|
+
*/
|
|
172
|
+
report(dimension: AnalyticsDimension, options?: AnalyticsReportOptions): Promise<Result<AnalyticsReport>>;
|
|
173
|
+
/** One number over time, one line per channel, device or country. */
|
|
174
|
+
timeseries(options?: AnalyticsTimeseriesOptions): Promise<Result<AnalyticsTimeseries>>;
|
|
175
|
+
}
|
|
176
|
+
export declare function createServerAnalytics(http: HttpClient): ServerAnalytics;
|