@altenginenet/sdk 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +429 -2
- package/dist/auth.cjs +312 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +1 -0
- package/dist/auth.d.ts +1 -0
- package/dist/auth.js +11 -0
- package/dist/auth.js.map +1 -0
- package/dist/channel.cjs +249 -0
- package/dist/channel.cjs.map +1 -0
- package/dist/channel.d.cts +1 -0
- package/dist/channel.d.ts +1 -0
- package/dist/channel.js +7 -0
- package/dist/channel.js.map +1 -0
- package/dist/chunk-6Q4X4E7X.js +291 -0
- package/dist/chunk-6Q4X4E7X.js.map +1 -0
- package/dist/chunk-NAQQAMY7.js +225 -0
- package/dist/chunk-NAQQAMY7.js.map +1 -0
- package/dist/client-rCIrl668.d.cts +201 -0
- package/dist/client-rCIrl668.d.ts +201 -0
- package/dist/index.cjs +1974 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1951 -0
- package/dist/index.d.ts +1951 -0
- package/dist/index.js +1431 -0
- package/dist/index.js.map +1 -0
- package/dist/socket-DqIm8vll.d.cts +144 -0
- package/dist/socket-DqIm8vll.d.ts +144 -0
- package/examples/first-write.mjs +14 -0
- package/package.json +85 -4
package/dist/auth.cjs
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/auth/client.ts
|
|
21
|
+
var client_exports = {};
|
|
22
|
+
__export(client_exports, {
|
|
23
|
+
AuthClient: () => AuthClient,
|
|
24
|
+
defaultStorage: () => defaultStorage,
|
|
25
|
+
memoryStorage: () => memoryStorage
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(client_exports);
|
|
28
|
+
|
|
29
|
+
// src/errors.ts
|
|
30
|
+
var AltEngineError = class extends Error {
|
|
31
|
+
code;
|
|
32
|
+
status;
|
|
33
|
+
details;
|
|
34
|
+
/** Seconds to wait before retrying, from the `Retry-After` header (429s). */
|
|
35
|
+
retryAfter;
|
|
36
|
+
constructor(opts) {
|
|
37
|
+
super(opts.message);
|
|
38
|
+
this.name = "AltEngineError";
|
|
39
|
+
this.code = opts.code;
|
|
40
|
+
this.status = opts.status;
|
|
41
|
+
this.details = opts.details;
|
|
42
|
+
this.retryAfter = opts.retryAfter;
|
|
43
|
+
}
|
|
44
|
+
/** Whether the request can be safely retried after a backoff. 429 always carries
|
|
45
|
+
* Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */
|
|
46
|
+
get retryable() {
|
|
47
|
+
if (this.status === 429) return true;
|
|
48
|
+
return this.status === 502 || this.status === 503 || this.status === 504;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
var AltEngineNetworkError = class extends Error {
|
|
52
|
+
cause;
|
|
53
|
+
constructor(message, cause) {
|
|
54
|
+
super(message);
|
|
55
|
+
this.name = "AltEngineNetworkError";
|
|
56
|
+
this.cause = cause;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/constants.ts
|
|
61
|
+
var DEFAULT_BASE_URL = "https://api.altengine.net";
|
|
62
|
+
var DEV_BASE_URL = "http://127.0.0.1:9191";
|
|
63
|
+
var seg = (s) => encodeURIComponent(String(s));
|
|
64
|
+
|
|
65
|
+
// src/auth/storage.ts
|
|
66
|
+
function memoryStorage() {
|
|
67
|
+
const map = /* @__PURE__ */ new Map();
|
|
68
|
+
return {
|
|
69
|
+
get: (k) => map.get(k) ?? null,
|
|
70
|
+
set: (k, v) => void map.set(k, v),
|
|
71
|
+
remove: (k) => void map.delete(k)
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function defaultStorage() {
|
|
75
|
+
try {
|
|
76
|
+
const ls = globalThis.localStorage;
|
|
77
|
+
if (!ls) return memoryStorage();
|
|
78
|
+
const probe = "__altengine_probe__";
|
|
79
|
+
ls.setItem(probe, "1");
|
|
80
|
+
ls.removeItem(probe);
|
|
81
|
+
return {
|
|
82
|
+
get: (k) => ls.getItem(k),
|
|
83
|
+
set: (k, v) => ls.setItem(k, v),
|
|
84
|
+
remove: (k) => ls.removeItem(k)
|
|
85
|
+
};
|
|
86
|
+
} catch {
|
|
87
|
+
return memoryStorage();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/auth/client.ts
|
|
92
|
+
var nowSec = () => Math.floor(Date.now() / 1e3);
|
|
93
|
+
var AuthClient = class {
|
|
94
|
+
instance;
|
|
95
|
+
baseUrl;
|
|
96
|
+
base;
|
|
97
|
+
storage;
|
|
98
|
+
key;
|
|
99
|
+
fetchImpl;
|
|
100
|
+
skew;
|
|
101
|
+
listeners = /* @__PURE__ */ new Set();
|
|
102
|
+
session;
|
|
103
|
+
/** In-flight refresh, so concurrent requests share one round trip. */
|
|
104
|
+
refreshing = null;
|
|
105
|
+
constructor(opts) {
|
|
106
|
+
if (!opts.instance) throw new Error("AuthClient requires an `instance`");
|
|
107
|
+
this.instance = opts.instance;
|
|
108
|
+
this.baseUrl = (opts.baseUrl ?? (opts.dev ? DEV_BASE_URL : DEFAULT_BASE_URL)).replace(/\/+$/, "");
|
|
109
|
+
this.base = `${this.baseUrl}/v1/auth/${seg(opts.instance)}`;
|
|
110
|
+
this.storage = opts.storage ?? defaultStorage();
|
|
111
|
+
this.key = opts.storageKey ?? `altengine.auth.${opts.instance}`;
|
|
112
|
+
const f = opts.fetch ?? globalThis.fetch;
|
|
113
|
+
if (!f) throw new Error("no fetch implementation available; pass { fetch }");
|
|
114
|
+
this.fetchImpl = f;
|
|
115
|
+
this.skew = opts.refreshSkewSeconds ?? 30;
|
|
116
|
+
this.session = this.load();
|
|
117
|
+
}
|
|
118
|
+
// --- session state ------------------------------------------------------
|
|
119
|
+
/** The signed-in user, or null. Reads persisted state, so it survives reloads. */
|
|
120
|
+
get user() {
|
|
121
|
+
return this.session?.user ?? null;
|
|
122
|
+
}
|
|
123
|
+
get isSignedIn() {
|
|
124
|
+
return !!this.session?.id_token;
|
|
125
|
+
}
|
|
126
|
+
/** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */
|
|
127
|
+
onChange(fn) {
|
|
128
|
+
this.listeners.add(fn);
|
|
129
|
+
return () => void this.listeners.delete(fn);
|
|
130
|
+
}
|
|
131
|
+
emit() {
|
|
132
|
+
for (const fn of this.listeners) {
|
|
133
|
+
try {
|
|
134
|
+
fn(this.user);
|
|
135
|
+
} catch {
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
load() {
|
|
140
|
+
try {
|
|
141
|
+
const raw = this.storage.get(this.key);
|
|
142
|
+
return raw ? JSON.parse(raw) : null;
|
|
143
|
+
} catch {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
save(s) {
|
|
148
|
+
this.session = s;
|
|
149
|
+
try {
|
|
150
|
+
if (s) this.storage.set(this.key, JSON.stringify(s));
|
|
151
|
+
else this.storage.remove(this.key);
|
|
152
|
+
} catch {
|
|
153
|
+
}
|
|
154
|
+
this.emit();
|
|
155
|
+
}
|
|
156
|
+
adopt(t) {
|
|
157
|
+
const user = t.user ?? this.session?.user ?? null;
|
|
158
|
+
this.save({ id_token: t.id_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user });
|
|
159
|
+
return { ...t, user };
|
|
160
|
+
}
|
|
161
|
+
// --- transport ----------------------------------------------------------
|
|
162
|
+
async call(method, path, body, bearer) {
|
|
163
|
+
const headers = {};
|
|
164
|
+
if (bearer) headers["authorization"] = `Bearer ${bearer}`;
|
|
165
|
+
if (body !== void 0) headers["content-type"] = "application/json";
|
|
166
|
+
let res;
|
|
167
|
+
try {
|
|
168
|
+
res = await this.fetchImpl(this.base + path, {
|
|
169
|
+
method,
|
|
170
|
+
headers,
|
|
171
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
172
|
+
});
|
|
173
|
+
} catch (err) {
|
|
174
|
+
throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);
|
|
175
|
+
}
|
|
176
|
+
if (!res.ok) throw await toError(res);
|
|
177
|
+
if (res.status === 204) return void 0;
|
|
178
|
+
return await res.json();
|
|
179
|
+
}
|
|
180
|
+
// --- config -------------------------------------------------------------
|
|
181
|
+
/** The instance's public sign-in configuration — which fields the sign-up form
|
|
182
|
+
* collects, which one is the login identity, and which methods are enabled.
|
|
183
|
+
* Fetch this to render a sign-in UI that matches the instance's settings. */
|
|
184
|
+
async config() {
|
|
185
|
+
return this.call("GET", "/config");
|
|
186
|
+
}
|
|
187
|
+
// --- sign up / in / out -------------------------------------------------
|
|
188
|
+
/** Create an account. Pass the configured sign-up fields plus `password`,
|
|
189
|
+
* e.g. `{ email, name, password }`. Signs the new user in. */
|
|
190
|
+
async signUp(fields) {
|
|
191
|
+
const t = await this.call("POST", "/signup", fields);
|
|
192
|
+
return this.adopt(t);
|
|
193
|
+
}
|
|
194
|
+
/** Sign in with the identity field + password. When the account has two-factor
|
|
195
|
+
* enabled this resolves to `{ status: "mfa_required" }` and you must call
|
|
196
|
+
* {@link verifyMfa} with the code — no tokens are issued until then. */
|
|
197
|
+
async signIn(identifier, password) {
|
|
198
|
+
const t = await this.call("POST", "/signin", {
|
|
199
|
+
identifier,
|
|
200
|
+
password
|
|
201
|
+
});
|
|
202
|
+
if ("mfa_required" in t) return { status: "mfa_required", mfaToken: t.mfa_token };
|
|
203
|
+
return { status: "signed_in", session: this.adopt(t) };
|
|
204
|
+
}
|
|
205
|
+
/** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */
|
|
206
|
+
async verifyMfa(mfaToken, code) {
|
|
207
|
+
const t = await this.call("POST", "/2fa/verify", { mfa_token: mfaToken, code });
|
|
208
|
+
return this.adopt(t);
|
|
209
|
+
}
|
|
210
|
+
/** Start passwordless sign-in: emails a one-time code. Always resolves — the
|
|
211
|
+
* server never reveals whether the account exists. */
|
|
212
|
+
async passwordlessStart(identifier) {
|
|
213
|
+
await this.call("POST", "/passwordless/start", { identifier });
|
|
214
|
+
}
|
|
215
|
+
/** Finish passwordless sign-in with the emailed code. */
|
|
216
|
+
async passwordlessVerify(identifier, code) {
|
|
217
|
+
const t = await this.call("POST", "/passwordless/verify", {
|
|
218
|
+
identifier,
|
|
219
|
+
code
|
|
220
|
+
});
|
|
221
|
+
if ("mfa_required" in t) return { status: "mfa_required", mfaToken: t.mfa_token };
|
|
222
|
+
return { status: "signed_in", session: this.adopt(t) };
|
|
223
|
+
}
|
|
224
|
+
/** Start a password reset: emails a one-time code. Always resolves. */
|
|
225
|
+
async passwordResetStart(identifier) {
|
|
226
|
+
await this.call("POST", "/password/reset/start", { identifier });
|
|
227
|
+
}
|
|
228
|
+
/** Finish a password reset with the emailed code and a new password. */
|
|
229
|
+
async passwordResetVerify(identifier, code, password) {
|
|
230
|
+
await this.call("POST", "/password/reset/verify", { identifier, code, password });
|
|
231
|
+
}
|
|
232
|
+
/** The signed-in user, re-read from the server (picks up claim changes). */
|
|
233
|
+
async me() {
|
|
234
|
+
const tok = await this.getToken();
|
|
235
|
+
if (!tok) throw new AltEngineError({ code: "UNAUTHENTICATED", message: "not signed in", status: 401 });
|
|
236
|
+
const { user } = await this.call("GET", "/me", void 0, tok);
|
|
237
|
+
if (user && this.session) this.save({ ...this.session, user });
|
|
238
|
+
return user;
|
|
239
|
+
}
|
|
240
|
+
/** Revoke the refresh token server-side and clear local state. Always clears
|
|
241
|
+
* locally, even if the network call fails. */
|
|
242
|
+
async signOut() {
|
|
243
|
+
const rt = this.session?.refresh_token;
|
|
244
|
+
this.save(null);
|
|
245
|
+
if (rt) {
|
|
246
|
+
try {
|
|
247
|
+
await this.call("POST", "/signout", { refresh_token: rt });
|
|
248
|
+
} catch {
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
// --- tokens -------------------------------------------------------------
|
|
253
|
+
/** Force a refresh-token rotation and return the new id_token. */
|
|
254
|
+
async refresh() {
|
|
255
|
+
const rt = this.session?.refresh_token;
|
|
256
|
+
if (!rt) throw new AltEngineError({ code: "UNAUTHENTICATED", message: "not signed in", status: 401 });
|
|
257
|
+
const t = await this.call("POST", "/token/refresh", { refresh_token: rt });
|
|
258
|
+
this.adopt(t);
|
|
259
|
+
return t.id_token;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* The current id_token, refreshed first if it is expired or about to be.
|
|
263
|
+
* Returns `undefined` when nobody is signed in. This is the `TokenProvider`
|
|
264
|
+
* the SDK calls before every Datastore/Search/Channel request — pass the
|
|
265
|
+
* client as `new AltEngine({ auth })` and tokens stay fresh automatically.
|
|
266
|
+
*
|
|
267
|
+
* Concurrent callers share a single refresh. If the refresh fails because the
|
|
268
|
+
* session is truly gone (401/403), local state is cleared so the app can react
|
|
269
|
+
* via {@link onChange} instead of retrying forever.
|
|
270
|
+
*/
|
|
271
|
+
async getToken() {
|
|
272
|
+
const s = this.session;
|
|
273
|
+
if (!s?.id_token) return void 0;
|
|
274
|
+
if (s.expires_at - this.skew > nowSec()) return s.id_token;
|
|
275
|
+
if (!this.refreshing) {
|
|
276
|
+
this.refreshing = this.refresh().catch((err) => {
|
|
277
|
+
if (err instanceof AltEngineError && (err.status === 401 || err.status === 403)) {
|
|
278
|
+
this.save(null);
|
|
279
|
+
return void 0;
|
|
280
|
+
}
|
|
281
|
+
throw err;
|
|
282
|
+
}).finally(() => {
|
|
283
|
+
this.refreshing = null;
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
return this.refreshing;
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
async function toError(res) {
|
|
290
|
+
let code = "INTERNAL";
|
|
291
|
+
let message = `HTTP ${res.status}`;
|
|
292
|
+
let details;
|
|
293
|
+
try {
|
|
294
|
+
const parsed = await res.json();
|
|
295
|
+
if (parsed?.error) {
|
|
296
|
+
code = parsed.error.code ?? code;
|
|
297
|
+
message = parsed.error.message ?? message;
|
|
298
|
+
details = parsed.error.details;
|
|
299
|
+
}
|
|
300
|
+
} catch {
|
|
301
|
+
}
|
|
302
|
+
const ra = res.headers.get("retry-after");
|
|
303
|
+
const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : void 0;
|
|
304
|
+
return new AltEngineError({ code, message, status: res.status, details, retryAfter });
|
|
305
|
+
}
|
|
306
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
307
|
+
0 && (module.exports = {
|
|
308
|
+
AuthClient,
|
|
309
|
+
defaultStorage,
|
|
310
|
+
memoryStorage
|
|
311
|
+
});
|
|
312
|
+
//# sourceMappingURL=auth.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth/client.ts","../src/errors.ts","../src/constants.ts","../src/auth/storage.ts"],"sourcesContent":["/** AuthClient — the browser-side identity client for `/v1/auth/{instance}`.\n *\n * This is the piece that lets a client-side app talk to altengine with **no\n * backend of its own**: the end user signs in here, and the resulting `id_token`\n * is what Datastore/Channel requests carry. Access rules on the auth instance\n * decide what that user may read and write.\n *\n * Deliberately self-contained and API-key-free (like `ChannelSocket`) so it is\n * safe to ship to a browser — see the `@altenginenet/sdk/auth` subpath export.\n *\n * ```ts\n * import { AuthClient } from \"@altenginenet/sdk/auth\";\n * import { AltEngine } from \"@altenginenet/sdk\";\n *\n * const auth = new AuthClient({ instance: \"myapp-auth\" });\n * await auth.signIn(\"alice@example.com\", \"hunter2\");\n *\n * // Hand the client to the SDK: every request now carries the user's token.\n * const ae = new AltEngine({ auth });\n * const { documents } = await ae.datastore(\"myapp\").query(\"posts\", { limit: 20 });\n * ```\n */\n\nimport { AltEngineError, AltEngineNetworkError } from \"../errors.js\";\nimport { DEFAULT_BASE_URL, DEV_BASE_URL, seg } from \"../constants.js\";\nimport { defaultStorage, memoryStorage, type TokenStorage } from \"./storage.js\";\nimport type { AuthConfig, AuthSession, AuthUser, SignInResult, StoredSession, AuthTokens } from \"./types.js\";\n\nexport interface AuthClientOptions {\n /** The auth instance name, e.g. \"myapp-auth\". */\n instance: string;\n /** API origin override. Resolution order: this → `dev: true` → production. */\n baseUrl?: string;\n /** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */\n dev?: boolean;\n /** Where to persist the session (default: `localStorage`, else in-memory).\n * Pass `memoryStorage()` to keep the session out of storage entirely. */\n storage?: TokenStorage;\n /** Storage key prefix, so several apps/instances can share one origin.\n * Defaults to `altengine.auth.<instance>`. */\n storageKey?: string;\n /** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch;\n /** Refresh the id_token this many seconds before it expires (default 30). */\n refreshSkewSeconds?: number;\n}\n\ntype Listener = (user: AuthUser | null) => void;\n\nconst nowSec = () => Math.floor(Date.now() / 1000);\n\nexport class AuthClient {\n readonly instance: string;\n readonly baseUrl: string;\n\n private readonly base: string;\n private readonly storage: TokenStorage;\n private readonly key: string;\n private readonly fetchImpl: typeof globalThis.fetch;\n private readonly skew: number;\n private readonly listeners = new Set<Listener>();\n\n private session: StoredSession | null;\n /** In-flight refresh, so concurrent requests share one round trip. */\n private refreshing: Promise<string | undefined> | null = null;\n\n constructor(opts: AuthClientOptions) {\n if (!opts.instance) throw new Error(\"AuthClient requires an `instance`\");\n this.instance = opts.instance;\n this.baseUrl = (opts.baseUrl ?? (opts.dev ? DEV_BASE_URL : DEFAULT_BASE_URL)).replace(/\\/+$/, \"\");\n this.base = `${this.baseUrl}/v1/auth/${seg(opts.instance)}`;\n this.storage = opts.storage ?? defaultStorage();\n this.key = opts.storageKey ?? `altengine.auth.${opts.instance}`;\n const f = opts.fetch ?? globalThis.fetch;\n if (!f) throw new Error(\"no fetch implementation available; pass { fetch }\");\n this.fetchImpl = f;\n this.skew = opts.refreshSkewSeconds ?? 30;\n this.session = this.load();\n }\n\n // --- session state ------------------------------------------------------\n\n /** The signed-in user, or null. Reads persisted state, so it survives reloads. */\n get user(): AuthUser | null {\n return this.session?.user ?? null;\n }\n\n get isSignedIn(): boolean {\n return !!this.session?.id_token;\n }\n\n /** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */\n onChange(fn: Listener): () => void {\n this.listeners.add(fn);\n return () => void this.listeners.delete(fn);\n }\n\n private emit(): void {\n for (const fn of this.listeners) {\n try {\n fn(this.user);\n } catch {\n /* a listener must never break the auth flow */\n }\n }\n }\n\n private load(): StoredSession | null {\n try {\n const raw = this.storage.get(this.key);\n return raw ? (JSON.parse(raw) as StoredSession) : null;\n } catch {\n return null;\n }\n }\n\n private save(s: StoredSession | null): void {\n this.session = s;\n try {\n if (s) this.storage.set(this.key, JSON.stringify(s));\n else this.storage.remove(this.key);\n } catch {\n /* storage full / blocked — the session still works for this page */\n }\n this.emit();\n }\n\n private adopt(t: AuthTokens & { user?: AuthUser }): AuthSession {\n const user = t.user ?? this.session?.user ?? null;\n this.save({ id_token: t.id_token, refresh_token: t.refresh_token, expires_at: t.expires_at, user });\n return { ...t, user: user as AuthUser };\n }\n\n // --- transport ----------------------------------------------------------\n\n private async call<T>(method: string, path: string, body?: unknown, bearer?: string): Promise<T> {\n const headers: Record<string, string> = {};\n if (bearer) headers[\"authorization\"] = `Bearer ${bearer}`;\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n let res: Response;\n try {\n res = await this.fetchImpl(this.base + path, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n throw new AltEngineNetworkError(`request failed: ${method} ${path}`, err);\n }\n if (!res.ok) throw await toError(res);\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n\n // --- config -------------------------------------------------------------\n\n /** The instance's public sign-in configuration — which fields the sign-up form\n * collects, which one is the login identity, and which methods are enabled.\n * Fetch this to render a sign-in UI that matches the instance's settings. */\n async config(): Promise<AuthConfig> {\n return this.call<AuthConfig>(\"GET\", \"/config\");\n }\n\n // --- sign up / in / out -------------------------------------------------\n\n /** Create an account. Pass the configured sign-up fields plus `password`,\n * e.g. `{ email, name, password }`. Signs the new user in. */\n async signUp(fields: Record<string, unknown>): Promise<AuthSession> {\n const t = await this.call<AuthSession>(\"POST\", \"/signup\", fields);\n return this.adopt(t);\n }\n\n /** Sign in with the identity field + password. When the account has two-factor\n * enabled this resolves to `{ status: \"mfa_required\" }` and you must call\n * {@link verifyMfa} with the code — no tokens are issued until then. */\n async signIn(identifier: string, password: string): Promise<SignInResult> {\n const t = await this.call<AuthSession | { mfa_required: true; mfa_token: string }>(\"POST\", \"/signin\", {\n identifier,\n password,\n });\n if (\"mfa_required\" in t) return { status: \"mfa_required\", mfaToken: t.mfa_token };\n return { status: \"signed_in\", session: this.adopt(t) };\n }\n\n /** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */\n async verifyMfa(mfaToken: string, code: string): Promise<AuthSession> {\n const t = await this.call<AuthSession>(\"POST\", \"/2fa/verify\", { mfa_token: mfaToken, code });\n return this.adopt(t);\n }\n\n /** Start passwordless sign-in: emails a one-time code. Always resolves — the\n * server never reveals whether the account exists. */\n async passwordlessStart(identifier: string): Promise<void> {\n await this.call(\"POST\", \"/passwordless/start\", { identifier });\n }\n\n /** Finish passwordless sign-in with the emailed code. */\n async passwordlessVerify(identifier: string, code: string): Promise<SignInResult> {\n const t = await this.call<AuthSession | { mfa_required: true; mfa_token: string }>(\"POST\", \"/passwordless/verify\", {\n identifier,\n code,\n });\n if (\"mfa_required\" in t) return { status: \"mfa_required\", mfaToken: t.mfa_token };\n return { status: \"signed_in\", session: this.adopt(t) };\n }\n\n /** Start a password reset: emails a one-time code. Always resolves. */\n async passwordResetStart(identifier: string): Promise<void> {\n await this.call(\"POST\", \"/password/reset/start\", { identifier });\n }\n\n /** Finish a password reset with the emailed code and a new password. */\n async passwordResetVerify(identifier: string, code: string, password: string): Promise<void> {\n await this.call(\"POST\", \"/password/reset/verify\", { identifier, code, password });\n }\n\n /** The signed-in user, re-read from the server (picks up claim changes). */\n async me(): Promise<AuthUser> {\n const tok = await this.getToken();\n if (!tok) throw new AltEngineError({ code: \"UNAUTHENTICATED\", message: \"not signed in\", status: 401 });\n // The wire wraps the user in a `{ user }` envelope.\n const { user } = await this.call<{ user: AuthUser }>(\"GET\", \"/me\", undefined, tok);\n // Keep the cached user in step, so claim changes made elsewhere land locally too.\n if (user && this.session) this.save({ ...this.session, user });\n return user;\n }\n\n /** Revoke the refresh token server-side and clear local state. Always clears\n * locally, even if the network call fails. */\n async signOut(): Promise<void> {\n const rt = this.session?.refresh_token;\n this.save(null);\n if (rt) {\n try {\n await this.call(\"POST\", \"/signout\", { refresh_token: rt });\n } catch {\n /* best-effort: local state is already gone */\n }\n }\n }\n\n // --- tokens -------------------------------------------------------------\n\n /** Force a refresh-token rotation and return the new id_token. */\n async refresh(): Promise<string> {\n const rt = this.session?.refresh_token;\n if (!rt) throw new AltEngineError({ code: \"UNAUTHENTICATED\", message: \"not signed in\", status: 401 });\n const t = await this.call<AuthTokens>(\"POST\", \"/token/refresh\", { refresh_token: rt });\n this.adopt(t);\n return t.id_token;\n }\n\n /**\n * The current id_token, refreshed first if it is expired or about to be.\n * Returns `undefined` when nobody is signed in. This is the `TokenProvider`\n * the SDK calls before every Datastore/Search/Channel request — pass the\n * client as `new AltEngine({ auth })` and tokens stay fresh automatically.\n *\n * Concurrent callers share a single refresh. If the refresh fails because the\n * session is truly gone (401/403), local state is cleared so the app can react\n * via {@link onChange} instead of retrying forever.\n */\n async getToken(): Promise<string | undefined> {\n const s = this.session;\n if (!s?.id_token) return undefined;\n if (s.expires_at - this.skew > nowSec()) return s.id_token;\n if (!this.refreshing) {\n this.refreshing = this.refresh()\n .catch((err) => {\n if (err instanceof AltEngineError && (err.status === 401 || err.status === 403)) {\n this.save(null); // refresh token revoked/expired — session is over\n return undefined;\n }\n throw err; // transient (network/5xx): let the caller see it and retry\n })\n .finally(() => {\n this.refreshing = null;\n });\n }\n return this.refreshing;\n }\n}\n\nasync function toError(res: Response): Promise<AltEngineError> {\n let code = \"INTERNAL\";\n let message = `HTTP ${res.status}`;\n let details: unknown;\n try {\n const parsed = (await res.json()) as { error?: { code?: string; message?: string; details?: unknown } };\n if (parsed?.error) {\n code = parsed.error.code ?? code;\n message = parsed.error.message ?? message;\n details = parsed.error.details;\n }\n } catch {\n /* non-JSON error body */\n }\n const ra = res.headers.get(\"retry-after\");\n const retryAfter = ra !== null && !Number.isNaN(Number(ra)) ? Number(ra) : undefined;\n return new AltEngineError({ code, message, status: res.status, details, retryAfter });\n}\n\nexport { memoryStorage, defaultStorage, type TokenStorage };\n","/** Error codes emitted by the altengine API. The union is open (`string`) so new\n * server codes never break compilation. */\nexport type ErrorCode =\n | \"NOT_FOUND\"\n | \"INVALID_ARGUMENT\"\n | \"UNAUTHENTICATED\"\n | \"PERMISSION_DENIED\"\n | \"RATE_LIMITED\"\n | \"QUERY_TOO_COMPLEX\"\n | \"INDEX_REQUIRED\"\n | \"DOCUMENT_TOO_LARGE\"\n | \"INDEX_FULL\"\n | \"ALREADY_EXISTS\"\n | \"PRECONDITION_FAILED\"\n | \"INTERNAL\"\n | (string & {});\n\n/** A structured altengine API error: the `{error:{code,message,details?}}` envelope\n * plus transport context (HTTP status, Retry-After). */\nexport class AltEngineError extends Error {\n readonly code: ErrorCode;\n readonly status: number;\n readonly details?: unknown;\n /** Seconds to wait before retrying, from the `Retry-After` header (429s). */\n readonly retryAfter?: number;\n\n constructor(opts: { code: ErrorCode; message: string; status: number; details?: unknown; retryAfter?: number }) {\n super(opts.message);\n this.name = \"AltEngineError\";\n this.code = opts.code;\n this.status = opts.status;\n this.details = opts.details;\n this.retryAfter = opts.retryAfter;\n }\n\n /** Whether the request can be safely retried after a backoff. 429 always carries\n * Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */\n get retryable(): boolean {\n if (this.status === 429) return true;\n return this.status === 502 || this.status === 503 || this.status === 504;\n }\n}\n\n/** Thrown when the network/fetch layer fails before an HTTP response exists. */\nexport class AltEngineNetworkError extends Error {\n readonly cause?: unknown;\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"AltEngineNetworkError\";\n this.cause = cause;\n }\n}\n","/** Side-effect-free constants and path helpers shared by every client.\n *\n * These live apart from `http.ts` on purpose: the browser-safe entry points\n * (`@altenginenet/sdk/auth`, `@altenginenet/sdk/channel`) need the base URLs and path\n * encoders but must NOT pull in the API-key transport, which is a backend\n * credential path that has no business in a browser bundle. */\n\n/** Production API origin used when no override is given. */\nexport const DEFAULT_BASE_URL = \"https://api.altengine.net\";\n/** Where `altengine dev` (the local emulator) listens by default. */\nexport const DEV_BASE_URL = \"http://127.0.0.1:9191\";\n\n/** Encode one path segment (instance/index/collection/key names). */\nexport const seg = (s: string | number): string => encodeURIComponent(String(s));\n\n/** Encode a namespace path segment. The empty (default) namespace can't ride a\n * URL path — routers collapse the resulting \"//\", so it travels as the reserved\n * sentinel `_default` (the server maps it back to \"\"). */\nexport const nsSeg = (namespace: string): string => seg(namespace === \"\" ? \"_default\" : namespace);\n","/** Where the signed-in session is kept between page loads. Implement this to use\n * cookies, IndexedDB, React Native's AsyncStorage (via a sync cache), or nothing\n * at all. The default picks `localStorage` in the browser and falls back to an\n * in-memory store everywhere else (Node, SSR, private-mode failures). */\nexport interface TokenStorage {\n get(key: string): string | null;\n set(key: string, value: string): void;\n remove(key: string): void;\n}\n\n/** A `TokenStorage` that forgets everything when the process/tab goes away. */\nexport function memoryStorage(): TokenStorage {\n const map = new Map<string, string>();\n return {\n get: (k) => map.get(k) ?? null,\n set: (k, v) => void map.set(k, v),\n remove: (k) => void map.delete(k),\n };\n}\n\n/** `localStorage` when it's present AND writable, else an in-memory store.\n * Safari private mode throws on `setItem`, so this probes with a real write. */\nexport function defaultStorage(): TokenStorage {\n try {\n const ls = globalThis.localStorage;\n if (!ls) return memoryStorage();\n const probe = \"__altengine_probe__\";\n ls.setItem(probe, \"1\");\n ls.removeItem(probe);\n return {\n get: (k) => ls.getItem(k),\n set: (k, v) => ls.setItem(k, v),\n remove: (k) => ls.removeItem(k),\n };\n } catch {\n return memoryStorage();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET,YAAY,MAAoG;AAC9G,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO,KAAK;AACjB,SAAK,SAAS,KAAK;AACnB,SAAK,UAAU,KAAK;AACpB,SAAK,aAAa,KAAK;AAAA,EACzB;AAAA;AAAA;AAAA,EAIA,IAAI,YAAqB;AACvB,QAAI,KAAK,WAAW,IAAK,QAAO;AAChC,WAAO,KAAK,WAAW,OAAO,KAAK,WAAW,OAAO,KAAK,WAAW;AAAA,EACvE;AACF;AAGO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACtC;AAAA,EACT,YAAY,SAAiB,OAAiB;AAC5C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ;AAAA,EACf;AACF;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AAAA,IACzB;AAAA,EACF,QAAQ;AAAA,EAER;AACA,QAAM,KAAK,IAAI,QAAQ,IAAI,aAAa;AACxC,QAAM,aAAa,OAAO,QAAQ,CAAC,OAAO,MAAM,OAAO,EAAE,CAAC,IAAI,OAAO,EAAE,IAAI;AAC3E,SAAO,IAAI,eAAe,EAAE,MAAM,SAAS,QAAQ,IAAI,QAAQ,SAAS,WAAW,CAAC;AACtF;","names":[]}
|
package/dist/auth.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { A as AuthClient, a as AuthClientOptions, T as TokenStorage, h as defaultStorage, m as memoryStorage } from './client-rCIrl668.cjs';
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { A as AuthClient, a as AuthClientOptions, T as TokenStorage, h as defaultStorage, m as memoryStorage } from './client-rCIrl668.js';
|
package/dist/auth.js
ADDED
package/dist/auth.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/channel.cjs
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/channel/socket.ts
|
|
21
|
+
var socket_exports = {};
|
|
22
|
+
__export(socket_exports, {
|
|
23
|
+
ChannelSocket: () => ChannelSocket
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(socket_exports);
|
|
26
|
+
var WS_PROTOCOL = "altengine.v1";
|
|
27
|
+
var WS_TOKEN_PROTOCOL_PREFIX = "altengine.token.";
|
|
28
|
+
var CONNECTING = 0;
|
|
29
|
+
var OPEN = 1;
|
|
30
|
+
var ChannelSocket = class {
|
|
31
|
+
opts;
|
|
32
|
+
listeners = {
|
|
33
|
+
message: /* @__PURE__ */ new Set(),
|
|
34
|
+
state: /* @__PURE__ */ new Set(),
|
|
35
|
+
error: /* @__PURE__ */ new Set(),
|
|
36
|
+
refused: /* @__PURE__ */ new Set()
|
|
37
|
+
};
|
|
38
|
+
ws;
|
|
39
|
+
stateValue = "idle";
|
|
40
|
+
desired = /* @__PURE__ */ new Set();
|
|
41
|
+
explicitChannels;
|
|
42
|
+
closedByUser = false;
|
|
43
|
+
attempts = 0;
|
|
44
|
+
pingTimer;
|
|
45
|
+
lastActivity = 0;
|
|
46
|
+
reconnectTimer;
|
|
47
|
+
pendingSubscribes = [];
|
|
48
|
+
pendingPublishes = [];
|
|
49
|
+
constructor(opts) {
|
|
50
|
+
this.opts = opts;
|
|
51
|
+
this.explicitChannels = opts.channels !== void 0;
|
|
52
|
+
for (const c of opts.channels ?? []) this.desired.add(c);
|
|
53
|
+
}
|
|
54
|
+
get state() {
|
|
55
|
+
return this.stateValue;
|
|
56
|
+
}
|
|
57
|
+
on(event, fn) {
|
|
58
|
+
this.listeners[event].add(fn);
|
|
59
|
+
return () => this.listeners[event].delete(fn);
|
|
60
|
+
}
|
|
61
|
+
emit(event, payload) {
|
|
62
|
+
for (const fn of this.listeners[event]) fn(payload);
|
|
63
|
+
}
|
|
64
|
+
setState(s) {
|
|
65
|
+
if (this.stateValue === s) return;
|
|
66
|
+
this.stateValue = s;
|
|
67
|
+
this.emit("state", s);
|
|
68
|
+
}
|
|
69
|
+
/** Connect (resolves once the socket is open). Reconnects automatically until
|
|
70
|
+
* `close()` is called. */
|
|
71
|
+
async connect() {
|
|
72
|
+
this.closedByUser = false;
|
|
73
|
+
if (this.ws && (this.ws.readyState === OPEN || this.ws.readyState === CONNECTING)) return;
|
|
74
|
+
await this.dial();
|
|
75
|
+
}
|
|
76
|
+
/** Stop reconnecting and close the connection. */
|
|
77
|
+
close() {
|
|
78
|
+
this.closedByUser = true;
|
|
79
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
80
|
+
this.stopPing();
|
|
81
|
+
this.failPending(new Error("socket closed"));
|
|
82
|
+
this.ws?.close(1e3, "client close");
|
|
83
|
+
this.ws = void 0;
|
|
84
|
+
this.setState("closed");
|
|
85
|
+
}
|
|
86
|
+
/** Subscribe to more channels (tracked and re-applied after reconnects).
|
|
87
|
+
* Resolves with the server's ack. */
|
|
88
|
+
async subscribe(channels) {
|
|
89
|
+
for (const c of channels) this.desired.add(c);
|
|
90
|
+
this.explicitChannels = true;
|
|
91
|
+
if (!this.isOpen()) return [...this.desired];
|
|
92
|
+
return new Promise((resolve, reject) => {
|
|
93
|
+
this.pendingSubscribes.push({ channels, resolve, reject });
|
|
94
|
+
this.send({ type: "subscribe", channels });
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** Unsubscribe from channels. */
|
|
98
|
+
unsubscribe(channels) {
|
|
99
|
+
for (const c of channels) this.desired.delete(c);
|
|
100
|
+
this.explicitChannels = true;
|
|
101
|
+
if (this.isOpen()) this.send({ type: "unsubscribe", channels });
|
|
102
|
+
}
|
|
103
|
+
/** Publish over the socket (requires a ws-capable `publish` token). Resolves
|
|
104
|
+
* with the delivered count from the server's ack. */
|
|
105
|
+
async publish(channel, data) {
|
|
106
|
+
if (!this.isOpen()) throw new Error("socket is not open");
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
this.pendingPublishes.push({ resolve, reject });
|
|
109
|
+
this.send({ type: "publish", channel, data });
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
// --- internals ---
|
|
113
|
+
isOpen() {
|
|
114
|
+
return !!this.ws && this.ws.readyState === OPEN;
|
|
115
|
+
}
|
|
116
|
+
send(frame) {
|
|
117
|
+
this.ws?.send(typeof frame === "string" ? frame : JSON.stringify(frame));
|
|
118
|
+
}
|
|
119
|
+
/** Where to dial, and with which subprotocols. The token travels as a subprotocol
|
|
120
|
+
* (`altengine.token.<token>`, beside `altengine.v1`), never in the URL — except against an
|
|
121
|
+
* older server whose response has only `ws_url`, which is opened as it is. */
|
|
122
|
+
target(tok) {
|
|
123
|
+
const endpoint = tok.ws_endpoint ?? (tok.ws_url ? void 0 : this.opts.url);
|
|
124
|
+
let url;
|
|
125
|
+
let protocols;
|
|
126
|
+
if (endpoint) {
|
|
127
|
+
url = new URL(endpoint);
|
|
128
|
+
protocols = tok.protocols?.length ? tok.protocols : [WS_PROTOCOL, WS_TOKEN_PROTOCOL_PREFIX + tok.token];
|
|
129
|
+
} else if (tok.ws_url) {
|
|
130
|
+
url = new URL(tok.ws_url);
|
|
131
|
+
if (!url.searchParams.has("token")) url.searchParams.set("token", tok.token);
|
|
132
|
+
} else {
|
|
133
|
+
throw new Error("no WebSocket URL: token response had no ws_endpoint and no url option was set");
|
|
134
|
+
}
|
|
135
|
+
if (this.explicitChannels && this.desired.size) {
|
|
136
|
+
url.searchParams.set("channels", [...this.desired].join(","));
|
|
137
|
+
}
|
|
138
|
+
return { url: url.toString(), protocols };
|
|
139
|
+
}
|
|
140
|
+
async dial() {
|
|
141
|
+
this.setState(this.attempts === 0 ? "connecting" : "reconnecting");
|
|
142
|
+
let tok;
|
|
143
|
+
try {
|
|
144
|
+
tok = await this.opts.getToken();
|
|
145
|
+
} catch (err) {
|
|
146
|
+
this.emit("error", err instanceof Error ? err : new Error(String(err)));
|
|
147
|
+
this.scheduleReconnect();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const WS = this.opts.webSocket ?? globalThis.WebSocket;
|
|
151
|
+
if (!WS) throw new Error("no WebSocket implementation; pass { webSocket } (e.g. `ws` on Node < 22)");
|
|
152
|
+
await new Promise((resolve) => {
|
|
153
|
+
let settled = false;
|
|
154
|
+
const { url, protocols } = this.target(tok);
|
|
155
|
+
const ws = protocols ? new WS(url, protocols) : new WS(url);
|
|
156
|
+
this.ws = ws;
|
|
157
|
+
ws.onopen = () => {
|
|
158
|
+
settled = true;
|
|
159
|
+
this.attempts = 0;
|
|
160
|
+
this.lastActivity = Date.now();
|
|
161
|
+
this.setState("open");
|
|
162
|
+
this.startPing();
|
|
163
|
+
resolve();
|
|
164
|
+
};
|
|
165
|
+
ws.onmessage = (ev) => this.handleMessage(ev);
|
|
166
|
+
ws.onerror = () => {
|
|
167
|
+
};
|
|
168
|
+
ws.onclose = (ev) => {
|
|
169
|
+
this.stopPing();
|
|
170
|
+
this.failPending(new Error(`socket closed (${ev.code})`));
|
|
171
|
+
if (!settled) {
|
|
172
|
+
settled = true;
|
|
173
|
+
resolve();
|
|
174
|
+
}
|
|
175
|
+
if (!this.closedByUser) this.scheduleReconnect();
|
|
176
|
+
};
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
handleMessage(ev) {
|
|
180
|
+
this.lastActivity = Date.now();
|
|
181
|
+
const raw = typeof ev.data === "string" ? ev.data : "";
|
|
182
|
+
if (raw === "pong" || raw === "ping") return;
|
|
183
|
+
let frame;
|
|
184
|
+
try {
|
|
185
|
+
frame = JSON.parse(raw);
|
|
186
|
+
} catch {
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
switch (frame?.type) {
|
|
190
|
+
case "subscribed": {
|
|
191
|
+
const refused = Array.isArray(frame.refused) ? frame.refused : [];
|
|
192
|
+
const head = this.pendingSubscribes[0];
|
|
193
|
+
const acked = /* @__PURE__ */ new Set([...frame.channels ?? [], ...refused]);
|
|
194
|
+
if (head && head.channels.every((c) => acked.has(c))) {
|
|
195
|
+
this.pendingSubscribes.shift().resolve(frame.channels ?? []);
|
|
196
|
+
}
|
|
197
|
+
if (refused.length) this.emit("refused", refused);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
case "published":
|
|
201
|
+
this.pendingPublishes.shift()?.resolve(frame.delivered ?? 0);
|
|
202
|
+
return;
|
|
203
|
+
case "error": {
|
|
204
|
+
const err = new Error(typeof frame.error === "string" ? frame.error : JSON.stringify(frame.error));
|
|
205
|
+
(this.pendingPublishes.shift() ?? this.pendingSubscribes.shift())?.reject(err);
|
|
206
|
+
this.emit("error", err);
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
default:
|
|
210
|
+
if (frame && typeof frame.channel === "string" && frame.type === void 0) {
|
|
211
|
+
this.emit("message", frame);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
startPing() {
|
|
216
|
+
const interval = Math.min(this.opts.pingIntervalMs ?? 3e4, 6e4);
|
|
217
|
+
this.stopPing();
|
|
218
|
+
this.pingTimer = setInterval(() => {
|
|
219
|
+
if (!this.isOpen()) return;
|
|
220
|
+
if (Date.now() - this.lastActivity > interval * 1.5) {
|
|
221
|
+
this.ws?.close(4e3, "keepalive timeout");
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
this.send("ping");
|
|
225
|
+
}, interval);
|
|
226
|
+
}
|
|
227
|
+
stopPing() {
|
|
228
|
+
if (this.pingTimer) clearInterval(this.pingTimer);
|
|
229
|
+
this.pingTimer = void 0;
|
|
230
|
+
}
|
|
231
|
+
scheduleReconnect() {
|
|
232
|
+
if (this.closedByUser) return;
|
|
233
|
+
const base = this.opts.backoffBaseMs ?? 250;
|
|
234
|
+
const cap = this.opts.backoffMaxMs ?? 3e4;
|
|
235
|
+
const delay = Math.min(base * 2 ** this.attempts, cap) * (0.5 + Math.random() * 0.5);
|
|
236
|
+
this.attempts++;
|
|
237
|
+
this.setState("reconnecting");
|
|
238
|
+
this.reconnectTimer = setTimeout(() => void this.dial(), delay);
|
|
239
|
+
}
|
|
240
|
+
failPending(err) {
|
|
241
|
+
for (const p of this.pendingSubscribes.splice(0)) p.reject(err);
|
|
242
|
+
for (const p of this.pendingPublishes.splice(0)) p.reject(err);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
246
|
+
0 && (module.exports = {
|
|
247
|
+
ChannelSocket
|
|
248
|
+
});
|
|
249
|
+
//# sourceMappingURL=channel.cjs.map
|