@chabi/js 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.
@@ -0,0 +1,334 @@
1
+ // src/errors.ts
2
+ var ChabiError = class extends Error {
3
+ info;
4
+ constructor(info) {
5
+ super(info.message);
6
+ this.name = "ChabiError";
7
+ this.info = info;
8
+ }
9
+ };
10
+ var MESSAGES = {
11
+ out_of_credits: "You're out of Chabi credits.",
12
+ app_limit: "You've reached the monthly limit you set for this app on Chabi.",
13
+ signed_out: "Sign in with Chabi to continue.",
14
+ access_denied: "You chose not to let this app use your Chabi plan.",
15
+ rate_limited: "Too many requests. Please wait a moment and try again.",
16
+ app_suspended: "This app can't use Chabi right now.",
17
+ bad_request: "Chabi couldn't handle that request.",
18
+ provider_error: "The AI provider is having trouble right now. Please try again.",
19
+ network: "Couldn't reach Chabi. Check your connection and try again.",
20
+ unknown: "Something went wrong. Please try again."
21
+ };
22
+ var str = (v) => typeof v === "string" && v ? v : void 0;
23
+ function kindOf(status, code) {
24
+ if (code === "insufficient_credits") return "out_of_credits";
25
+ if (code === "app_limit_reached") return "app_limit";
26
+ if (code === "app_suspended") return "app_suspended";
27
+ if (status === 401) return "signed_out";
28
+ if (status === 402) return "out_of_credits";
29
+ if (status === 403) return "app_suspended";
30
+ if (status === 429) return "rate_limited";
31
+ if (status >= 500) return "provider_error";
32
+ if (status >= 400) return "bad_request";
33
+ return "unknown";
34
+ }
35
+ function build(status, body, retryAfterHeader) {
36
+ const code = str(body?.code);
37
+ const kind = kindOf(status, code);
38
+ const info = { kind, status, message: MESSAGES[kind] };
39
+ if (code) info.code = code;
40
+ const upgradeUrl = str(body?.upgrade_url);
41
+ const manageUrl = str(body?.manage_url);
42
+ if (upgradeUrl) info.upgradeUrl = upgradeUrl;
43
+ if (manageUrl) info.manageUrl = manageUrl;
44
+ const retryAfter = Number(retryAfterHeader);
45
+ if (kind === "rate_limited" && retryAfterHeader && Number.isFinite(retryAfter)) info.retryAfter = retryAfter;
46
+ return info;
47
+ }
48
+ function describeError(e) {
49
+ if (e instanceof ChabiError) return e.info.message ? e.info : { ...e.info, message: MESSAGES[e.info.kind] };
50
+ const cause = e?.cause;
51
+ if (cause instanceof ChabiError) return describeError(cause);
52
+ const x = e;
53
+ if (x && typeof x === "object" && typeof x.status === "number") {
54
+ const outer = x.error;
55
+ const body = outer && typeof outer.error === "object" ? outer.error : outer;
56
+ const headers = x.headers;
57
+ const retry = typeof headers?.get === "function" ? headers.get("retry-after") : headers?.["retry-after"];
58
+ return build(x.status, body, retry);
59
+ }
60
+ const ctor = x?.constructor?.name;
61
+ if (e instanceof TypeError || typeof ctor === "string" && /Connection|Timeout/.test(ctor)) {
62
+ return { kind: "network", status: 0, message: MESSAGES.network };
63
+ }
64
+ return { kind: "unknown", status: 0, message: MESSAGES.unknown };
65
+ }
66
+ async function describeResponse(res) {
67
+ const body = await res.clone().json().catch(() => null);
68
+ return build(res.status, body?.error, res.headers.get("retry-after"));
69
+ }
70
+
71
+ // src/client.ts
72
+ var DEFAULT_BASE_URL = "https://chabi.dev";
73
+ var SIGN_OUT_CODES = /* @__PURE__ */ new Set(["missing_token", "token_revoked", "grant_revoked", "unknown_app"]);
74
+ var PLACEHOLDER_KEY = "chabi";
75
+ var ChabiBase = class {
76
+ constructor(core) {
77
+ this.core = core;
78
+ this.fetch = (input, init) => this.authorizedFetch(input, init);
79
+ }
80
+ core;
81
+ /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */
82
+ fetch;
83
+ get signedIn() {
84
+ return this.core.signedIn;
85
+ }
86
+ /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
87
+ openai() {
88
+ return { baseURL: `${this.core.baseUrl}/v1`, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };
89
+ }
90
+ /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
91
+ anthropic() {
92
+ return { baseURL: this.core.baseUrl, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };
93
+ }
94
+ /** The user's credit balance. */
95
+ async credits() {
96
+ const body = await this.getJson("/v1/credits");
97
+ return body.balance_credits;
98
+ }
99
+ /** The display name on the user's Chabi account, or null if they haven't set one. */
100
+ async me() {
101
+ const body = await this.getJson("/v1/me");
102
+ return { name: body.name ?? null };
103
+ }
104
+ /** Signs the user out of this app on this device. */
105
+ signOut() {
106
+ return this.core.end("signed_out");
107
+ }
108
+ /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */
109
+ onChange(listener) {
110
+ return this.core.onChange(listener);
111
+ }
112
+ async getJson(path) {
113
+ const res = await this.fetch(`${this.core.baseUrl}${path}`);
114
+ if (!res.ok) throw new ChabiError(await describeResponse(res));
115
+ return res.json();
116
+ }
117
+ async authorizedFetch(input, init) {
118
+ if (!this.isChabi(input)) return this.core.fetchImpl(input, init);
119
+ let token = await this.core.accessToken();
120
+ if (!token) return signedOutResponse();
121
+ const spare = input instanceof Request ? input.clone() : null;
122
+ const replayable = !(init?.body instanceof ReadableStream);
123
+ let res = await this.send(input, init, token);
124
+ if (res.status !== 401) return res;
125
+ let code = await errorCode(res);
126
+ if (code === "invalid_token") {
127
+ const fresh = await this.core.refreshAfterReject(token);
128
+ if (!fresh || !replayable) return res;
129
+ token = fresh;
130
+ res = await this.send(spare ?? input, init, token);
131
+ if (res.status !== 401) return res;
132
+ code = await errorCode(res);
133
+ }
134
+ if (code && SIGN_OUT_CODES.has(code)) await this.core.end("access_removed");
135
+ return res;
136
+ }
137
+ isChabi(input) {
138
+ try {
139
+ const url = new URL(input instanceof Request ? input.url : String(input));
140
+ return url.origin === new URL(this.core.baseUrl).origin;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+ send(input, init, token) {
146
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
147
+ headers.set("Authorization", `Bearer ${token}`);
148
+ headers.delete("x-api-key");
149
+ return this.core.fetchImpl(input, { ...init, headers });
150
+ }
151
+ };
152
+ var signedOutResponse = () => new Response(JSON.stringify({ error: { code: "missing_token", message: "Sign in with Chabi to continue." } }), {
153
+ status: 401,
154
+ headers: { "Content-Type": "application/json", "x-should-retry": "false" }
155
+ });
156
+ async function errorCode(res) {
157
+ const body = await res.clone().json().catch(() => null);
158
+ return typeof body?.error?.code === "string" ? body.error.code : void 0;
159
+ }
160
+
161
+ // src/pkce.ts
162
+ var base64url = (bytes) => {
163
+ let s = "";
164
+ for (const b of bytes) s += String.fromCharCode(b);
165
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
166
+ };
167
+ function randomString(bytes = 32) {
168
+ return base64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));
169
+ }
170
+ async function challengeFor(verifier) {
171
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
172
+ return base64url(new Uint8Array(digest));
173
+ }
174
+
175
+ // src/session.ts
176
+ var REFRESH_EARLY_MS = 6e4;
177
+ var SessionCore = class {
178
+ baseUrl;
179
+ clientId;
180
+ storage;
181
+ lock;
182
+ /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */
183
+ fetchImpl;
184
+ now;
185
+ tokens = null;
186
+ // Bumped by sign-in and sign-out, so a refresh that finishes afterwards can't bring an old session back.
187
+ generation = 0;
188
+ listeners = /* @__PURE__ */ new Set();
189
+ constructor(opts) {
190
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
191
+ this.clientId = opts.clientId;
192
+ this.storage = opts.storage;
193
+ this.lock = opts.lock;
194
+ this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));
195
+ this.now = opts.now ?? Date.now;
196
+ const loaded = this.storage.load();
197
+ if (!isPromise(loaded)) this.tokens = loaded;
198
+ else loaded.catch(() => {
199
+ });
200
+ }
201
+ get signedIn() {
202
+ return this.tokens !== null;
203
+ }
204
+ /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */
205
+ async load() {
206
+ this.tokens = await this.storage.load();
207
+ }
208
+ /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */
209
+ async accessToken() {
210
+ const t = this.tokens;
211
+ if (!t) return null;
212
+ if (t.expiresAt - this.now() > REFRESH_EARLY_MS) return t.accessToken;
213
+ return this.refreshLocked(t.refreshToken, null);
214
+ }
215
+ /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */
216
+ async refreshAfterReject(rejected) {
217
+ const t = this.tokens;
218
+ if (!t) return null;
219
+ if (t.accessToken !== rejected) return t.accessToken;
220
+ return this.refreshLocked(t.refreshToken, rejected);
221
+ }
222
+ /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */
223
+ async exchangeCode(p) {
224
+ const res = await this.tokenRequest({
225
+ grant_type: "authorization_code",
226
+ code: p.code,
227
+ redirect_uri: p.redirectUri,
228
+ client_id: this.clientId,
229
+ code_verifier: p.verifier
230
+ });
231
+ const tokens = res.ok ? await this.parseTokens(res) : null;
232
+ if (!tokens) {
233
+ throw new ChabiError({ kind: "signed_out", status: res.status, code: "sign_in_failed", message: "Sign-in didn't complete. Please try again." });
234
+ }
235
+ this.generation += 1;
236
+ await this.storage.save(tokens);
237
+ this.tokens = tokens;
238
+ this.emit(true, "signed_in");
239
+ }
240
+ /** Forgets the tokens (memory and storage) and tells listeners why. */
241
+ async end(reason) {
242
+ this.generation += 1;
243
+ const was = this.tokens !== null;
244
+ this.tokens = null;
245
+ await this.storage.clear();
246
+ if (was) this.emit(false, reason);
247
+ }
248
+ /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */
249
+ adopt(tokens) {
250
+ const was = this.tokens !== null;
251
+ if (!tokens) this.generation += 1;
252
+ this.tokens = tokens;
253
+ if (was !== (tokens !== null)) this.emit(tokens !== null, tokens ? "signed_in" : "signed_out");
254
+ }
255
+ onChange(listener) {
256
+ this.listeners.add(listener);
257
+ return () => void this.listeners.delete(listener);
258
+ }
259
+ emit(signedIn, reason) {
260
+ for (const l of [...this.listeners]) {
261
+ try {
262
+ l(signedIn, reason);
263
+ } catch {
264
+ }
265
+ }
266
+ }
267
+ refreshLocked(startedWith, rejected) {
268
+ return this.lock(async () => {
269
+ const generation = this.generation;
270
+ const stored = await this.storage.load();
271
+ if (generation !== this.generation) return null;
272
+ if (!stored) {
273
+ this.adopt(null);
274
+ return null;
275
+ }
276
+ if (stored.refreshToken !== startedWith) {
277
+ this.tokens = stored;
278
+ return stored.accessToken;
279
+ }
280
+ if (rejected === null && stored.expiresAt - this.now() > REFRESH_EARLY_MS) {
281
+ this.tokens = stored;
282
+ return stored.accessToken;
283
+ }
284
+ const res = await this.tokenRequest({ grant_type: "refresh_token", refresh_token: stored.refreshToken, client_id: this.clientId });
285
+ if (generation !== this.generation) return null;
286
+ if (!res.ok) {
287
+ if (res.status === 400 || res.status === 401) {
288
+ await this.end("expired");
289
+ return null;
290
+ }
291
+ throw new ChabiError({ kind: "provider_error", status: res.status, message: "Chabi is having trouble right now. Please try again." });
292
+ }
293
+ const fresh = await this.parseTokens(res);
294
+ if (generation !== this.generation) return null;
295
+ if (!fresh) throw new ChabiError({ kind: "unknown", status: res.status, message: "Chabi sent an unexpected reply. Please try again." });
296
+ await this.storage.save(fresh);
297
+ if (generation !== this.generation) {
298
+ if ((await this.storage.load())?.refreshToken === fresh.refreshToken) await this.storage.clear();
299
+ return null;
300
+ }
301
+ this.tokens = fresh;
302
+ return fresh.accessToken;
303
+ });
304
+ }
305
+ async tokenRequest(fields) {
306
+ try {
307
+ return await this.fetchImpl(`${this.baseUrl}/oauth/token`, {
308
+ method: "POST",
309
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
310
+ body: new URLSearchParams(fields).toString()
311
+ });
312
+ } catch {
313
+ throw new ChabiError({ kind: "network", status: 0, message: "Couldn't reach Chabi. Check your connection and try again." });
314
+ }
315
+ }
316
+ async parseTokens(res) {
317
+ const b = await res.json().catch(() => ({}));
318
+ if (typeof b.access_token !== "string" || typeof b.refresh_token !== "string" || typeof b.expires_in !== "number") return null;
319
+ return { accessToken: b.access_token, refreshToken: b.refresh_token, expiresAt: this.now() + b.expires_in * 1e3 };
320
+ }
321
+ };
322
+ var isPromise = (v) => typeof v?.then === "function";
323
+
324
+ export {
325
+ ChabiError,
326
+ describeError,
327
+ describeResponse,
328
+ DEFAULT_BASE_URL,
329
+ ChabiBase,
330
+ randomString,
331
+ challengeFor,
332
+ SessionCore
333
+ };
334
+ //# sourceMappingURL=chunk-PTMH3FUL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/pkce.ts","../src/session.ts"],"sourcesContent":["import type { ChabiErrorInfo, ErrorKind } from \"./types.js\";\n\n/** An error the SDK raises itself. `info` is what `describeError` returns for it. */\nexport class ChabiError extends Error {\n readonly info: ChabiErrorInfo;\n constructor(info: ChabiErrorInfo) {\n super(info.message);\n this.name = \"ChabiError\";\n this.info = info;\n }\n}\n\nconst MESSAGES: Record<ErrorKind, string> = {\n out_of_credits: \"You're out of Chabi credits.\",\n app_limit: \"You've reached the monthly limit you set for this app on Chabi.\",\n signed_out: \"Sign in with Chabi to continue.\",\n access_denied: \"You chose not to let this app use your Chabi plan.\",\n rate_limited: \"Too many requests. Please wait a moment and try again.\",\n app_suspended: \"This app can't use Chabi right now.\",\n bad_request: \"Chabi couldn't handle that request.\",\n provider_error: \"The AI provider is having trouble right now. Please try again.\",\n network: \"Couldn't reach Chabi. Check your connection and try again.\",\n unknown: \"Something went wrong. Please try again.\",\n};\n\ntype GatewayBody = { code?: unknown; message?: unknown; upgrade_url?: unknown; manage_url?: unknown };\n\nconst str = (v: unknown) => (typeof v === \"string\" && v ? v : undefined);\n\nfunction kindOf(status: number, code: string | undefined): ErrorKind {\n if (code === \"insufficient_credits\") return \"out_of_credits\";\n if (code === \"app_limit_reached\") return \"app_limit\";\n if (code === \"app_suspended\") return \"app_suspended\";\n if (status === 401) return \"signed_out\";\n if (status === 402) return \"out_of_credits\";\n if (status === 403) return \"app_suspended\";\n if (status === 429) return \"rate_limited\";\n if (status >= 500) return \"provider_error\";\n if (status >= 400) return \"bad_request\";\n return \"unknown\";\n}\n\nfunction build(status: number, body: GatewayBody | undefined, retryAfterHeader: string | null | undefined): ChabiErrorInfo {\n const code = str(body?.code);\n const kind = kindOf(status, code);\n const info: ChabiErrorInfo = { kind, status, message: MESSAGES[kind] };\n if (code) info.code = code;\n const upgradeUrl = str(body?.upgrade_url);\n const manageUrl = str(body?.manage_url);\n if (upgradeUrl) info.upgradeUrl = upgradeUrl;\n if (manageUrl) info.manageUrl = manageUrl;\n const retryAfter = Number(retryAfterHeader);\n if (kind === \"rate_limited\" && retryAfterHeader && Number.isFinite(retryAfter)) info.retryAfter = retryAfter;\n return info;\n}\n\n/**\n * Any error from a Chabi request in one shape: an OpenAI or Anthropic SDK error, a ChabiError, a failed fetch.\n * For a `Response` you got from `chabi.fetch` yourself, use `describeResponse`.\n */\nexport function describeError(e: unknown): ChabiErrorInfo {\n if (e instanceof ChabiError) return e.info.message ? e.info : { ...e.info, message: MESSAGES[e.info.kind] };\n // The official SDKs wrap anything chabi.fetch throws (a failed refresh, say) in their own connection error.\n const cause = (e as { cause?: unknown } | null)?.cause;\n if (cause instanceof ChabiError) return describeError(cause);\n const x = e as { status?: unknown; error?: unknown; headers?: unknown; name?: unknown } | null;\n if (x && typeof x === \"object\" && typeof x.status === \"number\") {\n // OpenAI's SDK puts the gateway's `error` object in err.error; Anthropic's puts the whole body there.\n const outer = x.error as { error?: GatewayBody } & GatewayBody | undefined;\n const body = outer && typeof outer.error === \"object\" ? outer.error : outer;\n const headers = x.headers as { get?: (k: string) => string | null } | Record<string, string> | undefined;\n const retry = typeof (headers as Headers | undefined)?.get === \"function\"\n ? (headers as Headers).get(\"retry-after\")\n : (headers as Record<string, string> | undefined)?.[\"retry-after\"];\n return build(x.status, body, retry);\n }\n // A failed fetch, or the SDKs' APIConnectionError (and its timeout subclass) wrapping one.\n const ctor = (x as { constructor?: { name?: unknown } } | null)?.constructor?.name;\n if (e instanceof TypeError || (typeof ctor === \"string\" && /Connection|Timeout/.test(ctor))) {\n return { kind: \"network\", status: 0, message: MESSAGES.network };\n }\n return { kind: \"unknown\", status: 0, message: MESSAGES.unknown };\n}\n\n/** `describeError` for a `Response`, such as one from `chabi.fetch` that wasn't ok. */\nexport async function describeResponse(res: Response): Promise<ChabiErrorInfo> {\n const body = (await res.clone().json().catch(() => null)) as { error?: GatewayBody } | null;\n return build(res.status, body?.error, res.headers.get(\"retry-after\"));\n}\n","import { ChabiError, describeResponse } from \"./errors.js\";\nimport type { SessionCore } from \"./session.js\";\nimport type { ChangeListener } from \"./types.js\";\n\n/** Where Chabi lives unless an app says otherwise. */\nexport const DEFAULT_BASE_URL = \"https://chabi.dev\";\n\n/** 401 codes that mean the user's access is gone: refreshing can't help, so the SDK signs out. */\nexport const SIGN_OUT_CODES = new Set([\"missing_token\", \"token_revoked\", \"grant_revoked\", \"unknown_app\"]);\n\n/** The placeholder API key handed to the official SDKs. `fetch` replaces it with the user's token. */\nconst PLACEHOLDER_KEY = \"chabi\";\n\ntype SdkConfig = { baseURL: string; apiKey: string; fetch: typeof fetch };\n\n/** What the browser and Node clients share: requests with the user's token, account calls and sign-out. */\nexport class ChabiBase {\n /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */\n readonly fetch: typeof fetch;\n\n constructor(protected readonly core: SessionCore) {\n this.fetch = (input, init) => this.authorizedFetch(input, init);\n }\n\n get signedIn(): boolean {\n return this.core.signedIn;\n }\n\n /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */\n openai(): SdkConfig {\n return { baseURL: `${this.core.baseUrl}/v1`, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };\n }\n\n /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */\n anthropic(): SdkConfig {\n return { baseURL: this.core.baseUrl, apiKey: PLACEHOLDER_KEY, fetch: this.fetch };\n }\n\n /** The user's credit balance. */\n async credits(): Promise<number> {\n const body = (await this.getJson(\"/v1/credits\")) as { balance_credits: number };\n return body.balance_credits;\n }\n\n /** The display name on the user's Chabi account, or null if they haven't set one. */\n async me(): Promise<{ name: string | null }> {\n const body = (await this.getJson(\"/v1/me\")) as { name?: string | null };\n return { name: body.name ?? null };\n }\n\n /** Signs the user out of this app on this device. */\n signOut(): Promise<void> {\n return this.core.end(\"signed_out\");\n }\n\n /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */\n onChange(listener: ChangeListener): () => void {\n return this.core.onChange(listener);\n }\n\n protected async getJson(path: string): Promise<unknown> {\n const res = await this.fetch(`${this.core.baseUrl}${path}`);\n if (!res.ok) throw new ChabiError(await describeResponse(res));\n return res.json();\n }\n\n private async authorizedFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n // The user's token only ever goes to Chabi, even if an app points an SDK somewhere else.\n if (!this.isChabi(input)) return this.core.fetchImpl(input, init);\n\n let token = await this.core.accessToken();\n // Answered like the gateway would, so the official SDKs raise their normal 401 error, without retrying.\n if (!token) return signedOutResponse();\n\n // A Request carries its body as a stream; clone it now so it can be sent again after a refresh.\n const spare = input instanceof Request ? input.clone() : null;\n const replayable = !(init?.body instanceof ReadableStream);\n\n let res = await this.send(input, init, token);\n if (res.status !== 401) return res;\n\n let code = await errorCode(res);\n if (code === \"invalid_token\") {\n const fresh = await this.core.refreshAfterReject(token);\n if (!fresh || !replayable) return res; // signed out by the refresh, or a stream body that's already spent\n token = fresh;\n res = await this.send(spare ?? input, init, token);\n if (res.status !== 401) return res;\n code = await errorCode(res);\n }\n if (code && SIGN_OUT_CODES.has(code)) await this.core.end(\"access_removed\");\n return res;\n }\n\n private isChabi(input: RequestInfo | URL): boolean {\n try {\n const url = new URL(input instanceof Request ? input.url : String(input));\n return url.origin === new URL(this.core.baseUrl).origin;\n } catch {\n return false;\n }\n }\n\n private send(input: RequestInfo | URL, init: RequestInit | undefined, token: string): Promise<Response> {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));\n headers.set(\"Authorization\", `Bearer ${token}`);\n headers.delete(\"x-api-key\"); // the Anthropic SDK's placeholder key\n return this.core.fetchImpl(input, { ...init, headers });\n }\n}\n\nconst signedOutResponse = () =>\n new Response(JSON.stringify({ error: { code: \"missing_token\", message: \"Sign in with Chabi to continue.\" } }), {\n status: 401,\n headers: { \"Content-Type\": \"application/json\", \"x-should-retry\": \"false\" },\n });\n\nasync function errorCode(res: Response): Promise<string | undefined> {\n const body = (await res.clone().json().catch(() => null)) as { error?: { code?: unknown } } | null;\n return typeof body?.error?.code === \"string\" ? body.error.code : undefined;\n}\n","// PKCE (RFC 7636) on Web Crypto, which browsers and Node 20+ both have as globalThis.crypto.\n\nconst base64url = (bytes: Uint8Array): string => {\n let s = \"\";\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n};\n\n/** A random base64url string: 32 bytes gives 43 characters, the verifier length RFC 7636 recommends. */\nexport function randomString(bytes = 32): string {\n return base64url(globalThis.crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/** The S256 code challenge for a verifier: base64url(SHA-256(verifier)). */\nexport async function challengeFor(verifier: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n","import { ChabiError } from \"./errors.js\";\nimport type { ChangeListener, ChangeReason, RefreshLock, TokenStorage, Tokens } from \"./types.js\";\n\n/** Refresh this long before the access token expires, so a request never goes out with one about to lapse. */\nexport const REFRESH_EARLY_MS = 60_000;\n\nexport type SessionOptions = {\n baseUrl: string;\n clientId: string;\n storage: TokenStorage;\n lock: RefreshLock;\n fetch?: typeof fetch;\n now?: () => number;\n};\n\ntype TokenResponse = { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown };\n\n/**\n * The signed-in user's tokens and everything that changes them. Each refresh token works once, and the gateway\n * ends the whole sign-in when one is sent twice, so every refresh runs inside `lock` and first rereads storage:\n * if another tab (or caller) already refreshed, its tokens are used instead.\n */\nexport class SessionCore {\n readonly baseUrl: string;\n readonly clientId: string;\n private readonly storage: TokenStorage;\n private readonly lock: RefreshLock;\n /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */\n readonly fetchImpl: typeof fetch;\n private readonly now: () => number;\n private tokens: Tokens | null = null;\n // Bumped by sign-in and sign-out, so a refresh that finishes afterwards can't bring an old session back.\n private generation = 0;\n private readonly listeners = new Set<ChangeListener>();\n\n constructor(opts: SessionOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/+$/, \"\");\n this.clientId = opts.clientId;\n this.storage = opts.storage;\n this.lock = opts.lock;\n this.fetchImpl = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));\n this.now = opts.now ?? Date.now;\n // Synchronous storage (the browser's) is read at once, so `signedIn` is right from the start.\n const loaded = this.storage.load();\n if (!isPromise(loaded)) this.tokens = loaded;\n else loaded.catch(() => {}); // asynchronous storage is read by load(); a failure here must not crash the app\n }\n\n get signedIn(): boolean {\n return this.tokens !== null;\n }\n\n /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */\n async load(): Promise<void> {\n this.tokens = await this.storage.load();\n }\n\n /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */\n async accessToken(): Promise<string | null> {\n const t = this.tokens;\n if (!t) return null;\n if (t.expiresAt - this.now() > REFRESH_EARLY_MS) return t.accessToken;\n return this.refreshLocked(t.refreshToken, null);\n }\n\n /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */\n async refreshAfterReject(rejected: string): Promise<string | null> {\n const t = this.tokens;\n if (!t) return null;\n if (t.accessToken !== rejected) return t.accessToken;\n return this.refreshLocked(t.refreshToken, rejected);\n }\n\n /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */\n async exchangeCode(p: { code: string; redirectUri: string; verifier: string }): Promise<void> {\n const res = await this.tokenRequest({\n grant_type: \"authorization_code\",\n code: p.code,\n redirect_uri: p.redirectUri,\n client_id: this.clientId,\n code_verifier: p.verifier,\n });\n const tokens = res.ok ? await this.parseTokens(res) : null;\n if (!tokens) {\n throw new ChabiError({ kind: \"signed_out\", status: res.status, code: \"sign_in_failed\", message: \"Sign-in didn't complete. Please try again.\" });\n }\n this.generation += 1;\n await this.storage.save(tokens);\n this.tokens = tokens;\n this.emit(true, \"signed_in\");\n }\n\n /** Forgets the tokens (memory and storage) and tells listeners why. */\n async end(reason: ChangeReason): Promise<void> {\n this.generation += 1;\n const was = this.tokens !== null;\n this.tokens = null;\n await this.storage.clear();\n if (was) this.emit(false, reason);\n }\n\n /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */\n adopt(tokens: Tokens | null): void {\n const was = this.tokens !== null;\n if (!tokens) this.generation += 1;\n this.tokens = tokens;\n if (was !== (tokens !== null)) this.emit(tokens !== null, tokens ? \"signed_in\" : \"signed_out\");\n }\n\n onChange(listener: ChangeListener): () => void {\n this.listeners.add(listener);\n return () => void this.listeners.delete(listener);\n }\n\n private emit(signedIn: boolean, reason: ChangeReason): void {\n for (const l of [...this.listeners]) {\n try {\n l(signedIn, reason);\n } catch {\n // A listener's own error must not break sign-in or a request.\n }\n }\n }\n\n private refreshLocked(startedWith: string, rejected: string | null): Promise<string | null> {\n return this.lock(async () => {\n const generation = this.generation;\n const stored = await this.storage.load();\n if (generation !== this.generation) return null;\n if (!stored) {\n this.adopt(null); // signed out elsewhere\n return null;\n }\n if (stored.refreshToken !== startedWith) {\n // Someone else refreshed while this caller waited for the lock: use theirs, never resend ours.\n this.tokens = stored;\n return stored.accessToken;\n }\n if (rejected === null && stored.expiresAt - this.now() > REFRESH_EARLY_MS) {\n this.tokens = stored;\n return stored.accessToken;\n }\n\n const res = await this.tokenRequest({ grant_type: \"refresh_token\", refresh_token: stored.refreshToken, client_id: this.clientId });\n if (generation !== this.generation) return null; // signed out while the request was out\n if (!res.ok) {\n if (res.status === 400 || res.status === 401) {\n await this.end(\"expired\");\n return null;\n }\n throw new ChabiError({ kind: \"provider_error\", status: res.status, message: \"Chabi is having trouble right now. Please try again.\" });\n }\n const fresh = await this.parseTokens(res);\n if (generation !== this.generation) return null; // signed out while the reply was read\n if (!fresh) throw new ChabiError({ kind: \"unknown\", status: res.status, message: \"Chabi sent an unexpected reply. Please try again.\" });\n await this.storage.save(fresh); // at once: the old refresh token is already spent\n if (generation !== this.generation) {\n // Signed out while saving: take back what this refresh wrote, but never a newer sign-in's tokens.\n if ((await this.storage.load())?.refreshToken === fresh.refreshToken) await this.storage.clear();\n return null;\n }\n this.tokens = fresh;\n return fresh.accessToken;\n });\n }\n\n private async tokenRequest(fields: Record<string, string>): Promise<Response> {\n try {\n return await this.fetchImpl(`${this.baseUrl}/oauth/token`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams(fields).toString(),\n });\n } catch {\n throw new ChabiError({ kind: \"network\", status: 0, message: \"Couldn't reach Chabi. Check your connection and try again.\" });\n }\n }\n\n private async parseTokens(res: Response): Promise<Tokens | null> {\n const b = (await res.json().catch(() => ({}))) as TokenResponse;\n if (typeof b.access_token !== \"string\" || typeof b.refresh_token !== \"string\" || typeof b.expires_in !== \"number\") return null;\n return { accessToken: b.access_token, refreshToken: b.refresh_token, expiresAt: this.now() + b.expires_in * 1000 };\n }\n}\n\nconst isPromise = <T>(v: T | Promise<T>): v is Promise<T> => typeof (v as { then?: unknown })?.then === \"function\";\n"],"mappings":";AAGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B;AAAA,EACT,YAAY,MAAsB;AAChC,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,WAAsC;AAAA,EAC1C,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,cAAc;AAAA,EACd,eAAe;A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AK,KAAK;AAC7B,UAAI,eAAe,KAAK,YAAY;AAElC,aAAK,MAAM,KAAK,QAAQ,KAAK,IAAI,iBAAiB,MAAM,aAAc,OAAM,KAAK,QAAQ,MAAM;AAC/F,eAAO;AAAA,MACT;AACA,WAAK,SAAS;AACd,aAAO,MAAM;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEA,MAAc,aAAa,QAAmD;AAC5E,QAAI;AACF,aAAO,MAAM,KAAK,UAAU,GAAG,KAAK,OAAO,gBAAgB;AAAA,QACzD,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,oCAAoC;AAAA,QAC/D,MAAM,IAAI,gBAAgB,MAAM,EAAE,SAAS;AAAA,MAC7C,CAAC;AAAA,IACH,QAAQ;AACN,YAAM,IAAI,WAAW,EAAE,MAAM,WAAW,QAAQ,GAAG,SAAS,6DAA6D,CAAC;AAAA,IAC5H;AAAA,EACF;AAAA,EAEA,MAAc,YAAY,KAAuC;AAC/D,UAAM,IAAK,MAAM,IAAI,KAAK,EAAE,MAAM,OAAO,CAAC,EAAE;AAC5C,QAAI,OAAO,EAAE,iBAAiB,YAAY,OAAO,EAAE,kBAAkB,YAAY,OAAO,EAAE,eAAe,SAAU,QAAO;AAC1H,WAAO,EAAE,aAAa,EAAE,cAAc,cAAc,EAAE,eAAe,WAAW,KAAK,IAAI,IAAI,EAAE,aAAa,IAAK;AAAA,EACnH;AACF;AAEA,IAAM,YAAY,CAAI,MAAuC,OAAQ,GAA0B,SAAS;","names":[]}
@@ -0,0 +1,119 @@
1
+ /** A signed-in user's tokens. `expiresAt` is when the access token expires, in ms since the epoch. */
2
+ type Tokens = {
3
+ accessToken: string;
4
+ refreshToken: string;
5
+ expiresAt: number;
6
+ };
7
+ /** Where the SDK keeps a user's tokens: localStorage in the browser, the app's choice in Node and Electron. */
8
+ interface TokenStorage {
9
+ load(): Tokens | null | Promise<Tokens | null>;
10
+ save(tokens: Tokens): void | Promise<void>;
11
+ clear(): void | Promise<void>;
12
+ }
13
+ /**
14
+ * Runs one token refresh at a time. Each refresh token works once, and sending one twice ends the sign-in,
15
+ * so every refresh for a user must go through the same lock (across tabs in a browser).
16
+ */
17
+ type RefreshLock = <T>(run: () => Promise<T>) => Promise<T>;
18
+ /** Why the user is now signed in or out. */
19
+ type ChangeReason = "signed_in" | "signed_out" | "access_removed" | "expired";
20
+ type ChangeListener = (signedIn: boolean, reason: ChangeReason) => void;
21
+ type ErrorKind = "out_of_credits" | "app_limit" | "signed_out" | "access_denied" | "rate_limited" | "app_suspended" | "bad_request" | "provider_error" | "network" | "unknown";
22
+ /** Any error from Chabi, the OpenAI SDK or the Anthropic SDK, in one shape. */
23
+ type ChabiErrorInfo = {
24
+ kind: ErrorKind;
25
+ /** A plain English default. Apps may show their own words instead. */
26
+ message: string;
27
+ status: number;
28
+ code?: string;
29
+ /** Where the user buys more credits (out_of_credits). */
30
+ upgradeUrl?: string;
31
+ /** Where the user raises this app's monthly limit (app_limit). */
32
+ manageUrl?: string;
33
+ /** Seconds to wait (rate_limited). */
34
+ retryAfter?: number;
35
+ };
36
+
37
+ type SessionOptions = {
38
+ baseUrl: string;
39
+ clientId: string;
40
+ storage: TokenStorage;
41
+ lock: RefreshLock;
42
+ fetch?: typeof fetch;
43
+ now?: () => number;
44
+ };
45
+ /**
46
+ * The signed-in user's tokens and everything that changes them. Each refresh token works once, and the gateway
47
+ * ends the whole sign-in when one is sent twice, so every refresh runs inside `lock` and first rereads storage:
48
+ * if another tab (or caller) already refreshed, its tokens are used instead.
49
+ */
50
+ declare class SessionCore {
51
+ readonly baseUrl: string;
52
+ readonly clientId: string;
53
+ private readonly storage;
54
+ private readonly lock;
55
+ /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */
56
+ readonly fetchImpl: typeof fetch;
57
+ private readonly now;
58
+ private tokens;
59
+ private generation;
60
+ private readonly listeners;
61
+ constructor(opts: SessionOptions);
62
+ get signedIn(): boolean;
63
+ /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */
64
+ load(): Promise<void>;
65
+ /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */
66
+ accessToken(): Promise<string | null>;
67
+ /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */
68
+ refreshAfterReject(rejected: string): Promise<string | null>;
69
+ /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */
70
+ exchangeCode(p: {
71
+ code: string;
72
+ redirectUri: string;
73
+ verifier: string;
74
+ }): Promise<void>;
75
+ /** Forgets the tokens (memory and storage) and tells listeners why. */
76
+ end(reason: ChangeReason): Promise<void>;
77
+ /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */
78
+ adopt(tokens: Tokens | null): void;
79
+ onChange(listener: ChangeListener): () => void;
80
+ private emit;
81
+ private refreshLocked;
82
+ private tokenRequest;
83
+ private parseTokens;
84
+ }
85
+
86
+ type SdkConfig = {
87
+ baseURL: string;
88
+ apiKey: string;
89
+ fetch: typeof fetch;
90
+ };
91
+ /** What the browser and Node clients share: requests with the user's token, account calls and sign-out. */
92
+ declare class ChabiBase {
93
+ protected readonly core: SessionCore;
94
+ /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */
95
+ readonly fetch: typeof fetch;
96
+ constructor(core: SessionCore);
97
+ get signedIn(): boolean;
98
+ /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
99
+ openai(): SdkConfig;
100
+ /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
101
+ anthropic(): SdkConfig;
102
+ /** The user's credit balance. */
103
+ credits(): Promise<number>;
104
+ /** The display name on the user's Chabi account, or null if they haven't set one. */
105
+ me(): Promise<{
106
+ name: string | null;
107
+ }>;
108
+ /** Signs the user out of this app on this device. */
109
+ signOut(): Promise<void>;
110
+ /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */
111
+ onChange(listener: ChangeListener): () => void;
112
+ protected getJson(path: string): Promise<unknown>;
113
+ private authorizedFetch;
114
+ private isChabi;
115
+ private send;
116
+ }
117
+
118
+ export { ChabiBase as C };
119
+ export type { ErrorKind as E, RefreshLock as R, TokenStorage as T, ChabiErrorInfo as a, ChangeListener as b, ChangeReason as c, Tokens as d };
@@ -0,0 +1,119 @@
1
+ /** A signed-in user's tokens. `expiresAt` is when the access token expires, in ms since the epoch. */
2
+ type Tokens = {
3
+ accessToken: string;
4
+ refreshToken: string;
5
+ expiresAt: number;
6
+ };
7
+ /** Where the SDK keeps a user's tokens: localStorage in the browser, the app's choice in Node and Electron. */
8
+ interface TokenStorage {
9
+ load(): Tokens | null | Promise<Tokens | null>;
10
+ save(tokens: Tokens): void | Promise<void>;
11
+ clear(): void | Promise<void>;
12
+ }
13
+ /**
14
+ * Runs one token refresh at a time. Each refresh token works once, and sending one twice ends the sign-in,
15
+ * so every refresh for a user must go through the same lock (across tabs in a browser).
16
+ */
17
+ type RefreshLock = <T>(run: () => Promise<T>) => Promise<T>;
18
+ /** Why the user is now signed in or out. */
19
+ type ChangeReason = "signed_in" | "signed_out" | "access_removed" | "expired";
20
+ type ChangeListener = (signedIn: boolean, reason: ChangeReason) => void;
21
+ type ErrorKind = "out_of_credits" | "app_limit" | "signed_out" | "access_denied" | "rate_limited" | "app_suspended" | "bad_request" | "provider_error" | "network" | "unknown";
22
+ /** Any error from Chabi, the OpenAI SDK or the Anthropic SDK, in one shape. */
23
+ type ChabiErrorInfo = {
24
+ kind: ErrorKind;
25
+ /** A plain English default. Apps may show their own words instead. */
26
+ message: string;
27
+ status: number;
28
+ code?: string;
29
+ /** Where the user buys more credits (out_of_credits). */
30
+ upgradeUrl?: string;
31
+ /** Where the user raises this app's monthly limit (app_limit). */
32
+ manageUrl?: string;
33
+ /** Seconds to wait (rate_limited). */
34
+ retryAfter?: number;
35
+ };
36
+
37
+ type SessionOptions = {
38
+ baseUrl: string;
39
+ clientId: string;
40
+ storage: TokenStorage;
41
+ lock: RefreshLock;
42
+ fetch?: typeof fetch;
43
+ now?: () => number;
44
+ };
45
+ /**
46
+ * The signed-in user's tokens and everything that changes them. Each refresh token works once, and the gateway
47
+ * ends the whole sign-in when one is sent twice, so every refresh runs inside `lock` and first rereads storage:
48
+ * if another tab (or caller) already refreshed, its tokens are used instead.
49
+ */
50
+ declare class SessionCore {
51
+ readonly baseUrl: string;
52
+ readonly clientId: string;
53
+ private readonly storage;
54
+ private readonly lock;
55
+ /** The underlying fetch, for requests that carry the user's token (see ChabiBase.fetch). */
56
+ readonly fetchImpl: typeof fetch;
57
+ private readonly now;
58
+ private tokens;
59
+ private generation;
60
+ private readonly listeners;
61
+ constructor(opts: SessionOptions);
62
+ get signedIn(): boolean;
63
+ /** Reads storage into memory. Needed once at start for asynchronous storage (Node, Electron). */
64
+ load(): Promise<void>;
65
+ /** The access token to send, refreshed first when it's within a minute of expiring. Null when signed out. */
66
+ accessToken(): Promise<string | null>;
67
+ /** The gateway said `rejected` is no longer valid: refresh, unless that already happened since it was sent. */
68
+ refreshAfterReject(rejected: string): Promise<string | null>;
69
+ /** Swaps the code from the sign-in redirect for tokens, saves them and tells listeners. */
70
+ exchangeCode(p: {
71
+ code: string;
72
+ redirectUri: string;
73
+ verifier: string;
74
+ }): Promise<void>;
75
+ /** Forgets the tokens (memory and storage) and tells listeners why. */
76
+ end(reason: ChangeReason): Promise<void>;
77
+ /** Another tab changed the stored tokens: take its copy, and tell listeners if that signed the user in or out. */
78
+ adopt(tokens: Tokens | null): void;
79
+ onChange(listener: ChangeListener): () => void;
80
+ private emit;
81
+ private refreshLocked;
82
+ private tokenRequest;
83
+ private parseTokens;
84
+ }
85
+
86
+ type SdkConfig = {
87
+ baseURL: string;
88
+ apiKey: string;
89
+ fetch: typeof fetch;
90
+ };
91
+ /** What the browser and Node clients share: requests with the user's token, account calls and sign-out. */
92
+ declare class ChabiBase {
93
+ protected readonly core: SessionCore;
94
+ /** A fetch for the official SDKs. It only sets Authorization: bodies, models and other headers pass through. */
95
+ readonly fetch: typeof fetch;
96
+ constructor(core: SessionCore);
97
+ get signedIn(): boolean;
98
+ /** Options for `new OpenAI(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
99
+ openai(): SdkConfig;
100
+ /** Options for `new Anthropic(...)`. In a browser, add `dangerouslyAllowBrowser: true`. */
101
+ anthropic(): SdkConfig;
102
+ /** The user's credit balance. */
103
+ credits(): Promise<number>;
104
+ /** The display name on the user's Chabi account, or null if they haven't set one. */
105
+ me(): Promise<{
106
+ name: string | null;
107
+ }>;
108
+ /** Signs the user out of this app on this device. */
109
+ signOut(): Promise<void>;
110
+ /** Called when the user is signed in or out, here or in another tab. Returns a function that unsubscribes. */
111
+ onChange(listener: ChangeListener): () => void;
112
+ protected getJson(path: string): Promise<unknown>;
113
+ private authorizedFetch;
114
+ private isChabi;
115
+ private send;
116
+ }
117
+
118
+ export { ChabiBase as C };
119
+ export type { ErrorKind as E, RefreshLock as R, TokenStorage as T, ChabiErrorInfo as a, ChangeListener as b, ChangeReason as c, Tokens as d };
@@ -0,0 +1,16 @@
1
+ import { a as ChabiErrorInfo } from './client-X74kWdDv.js';
2
+
3
+ /** An error the SDK raises itself. `info` is what `describeError` returns for it. */
4
+ declare class ChabiError extends Error {
5
+ readonly info: ChabiErrorInfo;
6
+ constructor(info: ChabiErrorInfo);
7
+ }
8
+ /**
9
+ * Any error from a Chabi request in one shape: an OpenAI or Anthropic SDK error, a ChabiError, a failed fetch.
10
+ * For a `Response` you got from `chabi.fetch` yourself, use `describeResponse`.
11
+ */
12
+ declare function describeError(e: unknown): ChabiErrorInfo;
13
+ /** `describeError` for a `Response`, such as one from `chabi.fetch` that wasn't ok. */
14
+ declare function describeResponse(res: Response): Promise<ChabiErrorInfo>;
15
+
16
+ export { ChabiError as C, describeResponse as a, describeError as d };
@@ -0,0 +1,16 @@
1
+ import { a as ChabiErrorInfo } from './client-X74kWdDv.cjs';
2
+
3
+ /** An error the SDK raises itself. `info` is what `describeError` returns for it. */
4
+ declare class ChabiError extends Error {
5
+ readonly info: ChabiErrorInfo;
6
+ constructor(info: ChabiErrorInfo);
7
+ }
8
+ /**
9
+ * Any error from a Chabi request in one shape: an OpenAI or Anthropic SDK error, a ChabiError, a failed fetch.
10
+ * For a `Response` you got from `chabi.fetch` yourself, use `describeResponse`.
11
+ */
12
+ declare function describeError(e: unknown): ChabiErrorInfo;
13
+ /** `describeError` for a `Response`, such as one from `chabi.fetch` that wasn't ok. */
14
+ declare function describeResponse(res: Response): Promise<ChabiErrorInfo>;
15
+
16
+ export { ChabiError as C, describeResponse as a, describeError as d };