@kaperkunde/tokens 0.0.0-stage → 0.1.1

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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +425 -2
  3. package/dist/browser-api.d.mts +56 -0
  4. package/dist/browser-api.mjs +75 -0
  5. package/dist/errors.d.mts +47 -0
  6. package/dist/errors.mjs +105 -0
  7. package/dist/index.d.mts +5 -0
  8. package/dist/index.mjs +5 -0
  9. package/dist/react/autorefill.d.mts +21 -0
  10. package/dist/react/autorefill.mjs +269 -0
  11. package/dist/react/balance.d.mts +23 -0
  12. package/dist/react/balance.mjs +116 -0
  13. package/dist/react/buy.d.mts +27 -0
  14. package/dist/react/buy.mjs +175 -0
  15. package/dist/react/history.d.mts +23 -0
  16. package/dist/react/history.mjs +102 -0
  17. package/dist/react/hooks.d.mts +52 -0
  18. package/dist/react/hooks.mjs +150 -0
  19. package/dist/react/index.d.mts +11 -0
  20. package/dist/react/index.mjs +10 -0
  21. package/dist/react/labels.d.mts +114 -0
  22. package/dist/react/labels.mjs +125 -0
  23. package/dist/react/own-model.d.mts +31 -0
  24. package/dist/react/own-model.mjs +358 -0
  25. package/dist/react/ui.d.mts +61 -0
  26. package/dist/react/ui.mjs +128 -0
  27. package/dist/react/usage.d.mts +21 -0
  28. package/dist/react/usage.mjs +137 -0
  29. package/dist/server/client.d.mts +78 -0
  30. package/dist/server/client.mjs +138 -0
  31. package/dist/server/error-of.d.mts +12 -0
  32. package/dist/server/error-of.mjs +63 -0
  33. package/dist/server/gateway.d.mts +64 -0
  34. package/dist/server/gateway.mjs +114 -0
  35. package/dist/server/index.d.mts +7 -0
  36. package/dist/server/index.mjs +7 -0
  37. package/dist/server/node.d.mts +23 -0
  38. package/dist/server/node.mjs +81 -0
  39. package/dist/server/routes.d.mts +56 -0
  40. package/dist/server/routes.mjs +257 -0
  41. package/dist/server/webhook.d.mts +47 -0
  42. package/dist/server/webhook.mjs +99 -0
  43. package/dist/styles.css +380 -0
  44. package/dist/types.d.mts +645 -0
  45. package/dist/types.mjs +162 -0
  46. package/dist/units.d.mts +37 -0
  47. package/dist/units.mjs +76 -0
  48. package/package.json +72 -3
  49. package/stub/cli.mjs +8 -0
  50. package/stub/server.d.mts +38 -0
  51. package/stub/server.mjs +1465 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaperkunde
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,426 @@
1
- # Temporary Holding Version
1
+ # @kaperkunde/tokens
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The client for the Token Center: the service that sits between an app and its
4
+ AI providers, meters every call and keeps the user's token balance. An app
5
+ points its model calls at the center, mounts a few routes, verifies a webhook,
6
+ and draws the wallet with the components here.
7
+
8
+ One package, four entry points:
9
+
10
+ | Entry | Runs | What |
11
+ | ------------------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
12
+ | `@kaperkunde/tokens` | anywhere | The contract types, error codes and header names; unit formatting; `TokenCenterError`; `createTokenApi`, the browser's client |
13
+ | `@kaperkunde/tokens/server` | Node ≥ 22 | `createTokenCenter` (app API client), `gatewayConfig`, `chargeFromHeaders`, `tokenErrorOf`, `verifyWebhook`, `tokenRoutes`, `nodeHandler` |
14
+ | `@kaperkunde/tokens/react` | browser | `TokenBalance`, `BuyTokens`, `AutoRefill`, `UsageList`, `PurchaseHistory`, `OwnModelForm`, `BackendOrderSwitch` and the hooks |
15
+ | `@kaperkunde/tokens/styles.css` | opt-in | A neutral default theme on `--tk-*` variables |
16
+ | `@kaperkunde/tokens/stub` | tests | A stand-in center, `startStub()` and the `tokens-stub` command |
17
+
18
+ React ≥ 19 is an optional peer (only `/react` needs it). Nothing here names a
19
+ center: its address is configuration.
20
+
21
+ ```sh
22
+ pnpm add @kaperkunde/tokens
23
+ ```
24
+
25
+ Money is integer **micro-dollars** (`Micros`, 1 USD = 1,000,000) and fiat is
26
+ integer **cents**. An app shows balances in its own unit (`Balance.unit`, e.g.
27
+ "credits" at 1,000,000 per dollar, so one token is one micro-dollar).
28
+
29
+ ## Server setup
30
+
31
+ One client per process, made from configuration:
32
+
33
+ ```ts
34
+ // lib/tokens.ts
35
+ import { createTokenCenter } from "@kaperkunde/tokens/server"
36
+
37
+ export const center = createTokenCenter({
38
+ baseUrl: process.env.TOKENS_URL!, // the center, e.g. https://tokens.example.com
39
+ apiKey: process.env.TOKENS_APP_KEY!, // tk_live_… — server side only
40
+ })
41
+ ```
42
+
43
+ Every method is typed and throws a `TokenCenterError` with the contract's
44
+ `code`, the HTTP `status` and the whole `detail`. **A center that cannot be
45
+ reached, times out or answers a 5xx with no contract body is
46
+ `center_unavailable`: fail closed**, never fall back to calling a provider
47
+ directly.
48
+
49
+ ```ts
50
+ import { isTokenError } from "@kaperkunde/tokens"
51
+
52
+ try {
53
+ const balance = await center.balance(user.id)
54
+ } catch (error) {
55
+ if (isTokenError(error, "center_unavailable")) {
56
+ /* pause the job, show the message */
57
+ }
58
+ if (isTokenError(error, "insufficient_balance")) {
59
+ /* offer <BuyTokens>; error.action === "buy_tokens" */
60
+ }
61
+ }
62
+ ```
63
+
64
+ A `TokenCenterError` also exposes `path` (an `invalid_request` refusal names the
65
+ offending field, e.g. `tools[0].type` for an unpriced server tool, `amountCents`,
66
+ `body`) and `callId` (the `x-token-call-id` of a failed or refused call, so you
67
+ can find it in the ledger). A charge on an estimate (`CallCharge.estimated`) is
68
+ a call that was cut short; `provider_error` (502) covers a provider failure and
69
+ a problem with the center's own provider key, never with the provider's text,
70
+ and `forbidden` (403) a test key used where no test provider is set.
71
+
72
+ Provider refusals: `provider_out_of_credit` (503, `error.provider`, `error.model`) means the
73
+ center's own account with that AI provider is out of credit; nothing is charged and asking
74
+ again is pointless until an admin tops up, so an app should pause that feature for a while
75
+ rather than retry. `provider_rate_limited` (429) and `provider_overloaded` (503) are upstream
76
+ conditions worth one retry; `error.retryable` (`RETRYABLE_ERROR_CODES`) says which codes can work again, and
77
+ `error.detail.retryAfterSeconds` carries `Retry-After`. A speech answer names the voice it
78
+ used in place of the one asked for in `x-token-voice-fallback` (`SpeechResult.voiceFallback`,
79
+ `voiceFallbackFromHeaders`).
80
+
81
+ ### Model calls: the gateway
82
+
83
+ Point an AI SDK provider at the center, with the payer in `x-token-user`:
84
+
85
+ ```ts
86
+ import { createAnthropic } from "@ai-sdk/anthropic"
87
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
88
+ import { gatewayConfig, gatewayHeaders } from "@kaperkunde/tokens/server"
89
+
90
+ const config = gatewayConfig({
91
+ baseUrl: process.env.TOKENS_URL!,
92
+ apiKey: process.env.TOKENS_APP_KEY!,
93
+ user: owner.id, // who pays: your own user id
94
+ email: owner.verifiedEmail, // optional, stored on the center's user row
95
+ })
96
+
97
+ const anthropic = createAnthropic(config) // /messages, prompt caching untouched
98
+ const compatible = createOpenAICompatible({ name: "tokens", ...config })
99
+
100
+ // Attribution per call, for the ledger and your own correlation:
101
+ await generateText({
102
+ model: anthropic("claude-sonnet-5-5"),
103
+ headers: gatewayHeaders({
104
+ user: owner.id,
105
+ attribution: {
106
+ purpose: "storyteller",
107
+ activity: "Telling the next scene",
108
+ scope: world.id,
109
+ job: job.id,
110
+ correlation: usageRow.id, // your own ledger row
111
+ },
112
+ }),
113
+ prompt,
114
+ })
115
+ ```
116
+
117
+ Attribution values are `encodeURIComponent`-encoded and cut to 200 characters,
118
+ as the center expects. `backend: "own"` sends a chat-completions call to the
119
+ user's own endpoint; ask `center.route({ userId, model, needs })` which
120
+ backend to use and with which model.
121
+
122
+ What a call cost, from the response headers or the ledger:
123
+
124
+ ```ts
125
+ import { chargeFromHeaders, parseTrailer } from "@kaperkunde/tokens/server"
126
+
127
+ const charge = chargeFromHeaders(result.response.headers) // non-streamed
128
+ // { callId, source, model, costMicros, feeMicros, chargedMicros, balanceAfterMicros } (HeaderCharge)
129
+ // null for a stream (no cost yet): callIdFromHeaders(headers) gives its id, then wait for the charge.
130
+ const call = await center.call(charge.callId, { wait: 10 }) // long-polls ≤ 30 s
131
+ // or: gatewayConfig({ …, trailer: true }) and parseTrailer(sseText)
132
+ // or, for a multi-step call keyed by your own row:
133
+ const { calls, totals } = await center.calls(user.id, {
134
+ correlation: usageRow.id,
135
+ })
136
+ ```
137
+
138
+ A thrown gateway error is mapped back to the contract's code, whatever the SDK
139
+ made of it:
140
+
141
+ ```ts
142
+ import { tokenErrorOf } from "@kaperkunde/tokens/server"
143
+
144
+ try {
145
+ await generateText({ … })
146
+ } catch (error) {
147
+ const failure = tokenErrorOf(error) // TokenCenterError | null
148
+ if (failure?.code === "insufficient_balance") pauseJob("cap:tokens")
149
+ else if (failure?.code === "center_unavailable") pauseJob("center")
150
+ else throw error
151
+ }
152
+ ```
153
+
154
+ Speech is the one gateway call that is not a provider SDK's:
155
+ `const { audio, chars, charge } = await center.speech({ user: owner.id }, { input, voice })`.
156
+
157
+ ### Browser routes: `tokenRoutes`
158
+
159
+ The browser never holds the app key. It calls routes **your app** mounts; they
160
+ read your own session, put that user in and call the center. The browser cannot
161
+ name another user.
162
+
163
+ ```ts
164
+ import { tokenRoutes } from "@kaperkunde/tokens/server"
165
+
166
+ export const handler = tokenRoutes(center, {
167
+ basePath: "/api/tokens", // where it is mounted (default)
168
+ origin: process.env.APP_ORIGIN, // the origin Stripe returns the browser to
169
+ userOf: async (request) => {
170
+ const session = await auth.api.getSession({ headers: request.headers })
171
+ return session
172
+ ? {
173
+ id: session.user.id,
174
+ email: session.user.emailVerified ? session.user.email : null,
175
+ }
176
+ : null // 401
177
+ },
178
+ })
179
+ ```
180
+
181
+ It serves `GET app | models | balance | calls | history | sale-prices |
182
+ autorefill | own-endpoint | purchase/:id`, `POST checkout | card |
183
+ own-endpoint/test`, `PUT autorefill | own-endpoint | backend-order` and
184
+ `DELETE card | own-endpoint`. The return URLs for Stripe are built from
185
+ `origin` and the browser's `returnPath` (only a path on your own origin is
186
+ honoured); they must be under the app's registered return origins on the
187
+ center. Replace them with `returnUrls`.
188
+
189
+ **App router** (`app/api/tokens/[...op]/route.ts`):
190
+
191
+ ```ts
192
+ import { handler } from "@/lib/tokens-routes"
193
+ export { handler as GET, handler as POST, handler as PUT, handler as DELETE }
194
+ ```
195
+
196
+ **Pages router** (`pages/api/tokens/[...op].ts`), through the small Node adapter:
197
+
198
+ ```ts
199
+ import { nodeHandler } from "@kaperkunde/tokens/server"
200
+ import { handler } from "@/utils/tokensRoutes"
201
+
202
+ export const config = { api: { bodyParser: false } }
203
+ export default nodeHandler(handler)
204
+ ```
205
+
206
+ `nodeHandler` also takes a body Next already parsed. It trusts
207
+ `x-forwarded-proto` and `x-forwarded-host` for the URL it builds; pass
208
+ `{ trustForwarded: false }` if no proxy of yours sits in front.
209
+
210
+ ### Webhooks
211
+
212
+ The center posts signed events (`grant.received`, `purchase.completed`,
213
+ `balance.low`, `balance.empty`, `autorefill.failed`, `grant.expired`). Verify
214
+ the **raw body**, then handle idempotently on `event.id`: deliveries repeat
215
+ and arrive out of order.
216
+
217
+ ```ts
218
+ import { webhookRoute } from "@kaperkunde/tokens/server"
219
+
220
+ export const POST = webhookRoute({
221
+ secret: () => process.env.TOKENS_WEBHOOK_SECRET!, // an array while you rotate
222
+ handlers: {
223
+ "purchase.completed": async (event) => {
224
+ if (await seen(event.id)) return
225
+ await notifyUser(event.data.userId, event.data.purchase)
226
+ },
227
+ "balance.empty": async (event) => pauseWorkFor(event.data.userId),
228
+ "grant.received": async (event) => resumeWorkFor(event.data.userId),
229
+ },
230
+ })
231
+ ```
232
+
233
+ A bad signature or body answers 400, a throwing handler 500 (the center
234
+ retries from one minute to 24 hours), anything else 200. To do it by hand:
235
+ `verifyWebhook(rawBody, request.headers.get("token-signature"), secret, {
236
+ toleranceSeconds })` returns the typed event or throws a
237
+ `WebhookVerificationError` (`reason`: `malformed`, `signature`, `stale`,
238
+ `body`); the compare is constant-time and the tolerance 300 s. In the pages
239
+ router use `nodeHandler(webhookRoute(…))` with `bodyParser: false`.
240
+
241
+ ## Components
242
+
243
+ Components read colours, radius, font and spacing only from CSS variables, and
244
+ carry stable `tk-*` class names. No Tailwind, no CSS modules. Each takes
245
+ `className` (root), `classNames` (per part, e.g. `{ button: "my-button" }`),
246
+ `labels` (English strings, all overridable) and `basePath` (default
247
+ `/api/tokens`); without data props it loads its own from your mounted routes.
248
+
249
+ ```tsx
250
+ import "@kaperkunde/tokens/styles.css" // optional
251
+ import {
252
+ TokensProvider,
253
+ TokenBalance,
254
+ BuyTokens,
255
+ AutoRefill,
256
+ UsageList,
257
+ PurchaseHistory,
258
+ OwnModelForm,
259
+ } from "@kaperkunde/tokens/react"
260
+
261
+ ;<TokensProvider basePath="/api/tokens" labels={{ buyTitle: "Buy credits" }}>
262
+ <TokenBalance href="/ai/tokens" /> {/* compact pill: "84k credits" */}
263
+ <TokenBalance variant="full" /> {/* breakdown, next expiry, shortfall */}
264
+ <BuyTokens returnPath="/ai/tokens" />{" "}
265
+ {/* the app's packs and bounds come from the center (purchaseOptions); packsOnly hides "Other amount" */}
266
+ <AutoRefill returnPath="/ai/tokens" />
267
+ <UsageList query={{ scope: world.id }} /> {/* cost, cache share, purpose */}
268
+ <PurchaseHistory />
269
+ <OwnModelForm />{" "}
270
+ {/* BYO (also exported as OwnEndpointForm): address, write-only key, models, tool choice, order, test */}
271
+ </TokensProvider>
272
+ ```
273
+
274
+ - **Forms say what is missing**: a button is never disabled for an empty
275
+ field; pressing it names what is still needed ("Still needed: Address,
276
+ Models.") and the center's own errors are shown in words. `disabled` is only
277
+ for a write in flight.
278
+ - **Accessible and narrow**: real labels (with "(needed)"), `aria-pressed`
279
+ segmented controls, `role="alert"` and `role="status"` messages, 44 px tall
280
+ targets, inputs at 16 px under 560 px so iOS does not zoom, and everything
281
+ wraps at 375 px.
282
+ - **Hooks**: `useBalance`, `useCalls`, `useHistory`, `useSalePrices`,
283
+ `useAutoRefill`, `useOwnEndpoint`, `useAppInfo` return
284
+ `{ data, error, loading, refresh }`, poll while the tab is visible and load
285
+ again on focus; `refreshTokens()` reloads all of them after you spend or buy
286
+ something yourself. `useTokenApi(basePath)` is the typed client of your
287
+ routes (`createTokenApi` outside React).
288
+ - **Data in, callbacks out** for testing or a custom screen: `TokenBalance
289
+ balance={…}`, `BuyTokens onCheckout={…} onRedirect={…}`, `AutoRefill
290
+ value={…} onSave={…}`, `UsageList page={…}`, `OwnModelForm endpoint={…}
291
+ onSave={…} onTest={…}`.
292
+
293
+ ## Theming: `--tk-*`
294
+
295
+ `styles.css` defines every variable for light and dark (`prefers-color-scheme`,
296
+ or `data-theme="light|dark"` on `<html>`) on `:where(:root)`, specificity zero,
297
+ so any rule of yours wins. Skip the file and style the `tk-*` classes yourself,
298
+ or set the variables where you want them:
299
+
300
+ | Variable | Used for |
301
+ | ---------------- | ---------------------------------------------- |
302
+ | `--tk-font` | font family |
303
+ | `--tk-fg` | text |
304
+ | `--tk-muted` | secondary text |
305
+ | `--tk-bg` | the page behind a panel (inputs, buttons) |
306
+ | `--tk-surface` | panels, the pill |
307
+ | `--tk-border` | lines around panels, inputs and buttons |
308
+ | `--tk-accent` | primary button, the pressed segment |
309
+ | `--tk-accent-fg` | text on `--tk-accent` |
310
+ | `--tk-danger` | errors, destructive buttons, an empty balance |
311
+ | `--tk-ok` | success notices |
312
+ | `--tk-focus` | the focus ring |
313
+ | `--tk-radius` | corner radius |
314
+ | `--tk-gap` | the spacing unit inside a panel |
315
+ | `--tk-tap` | the least height of anything pressable (44 px) |
316
+
317
+ ```css
318
+ /* Map onto your own design tokens */
319
+ :root {
320
+ --tk-font: var(--app-font);
321
+ --tk-fg: var(--app-text);
322
+ --tk-muted: var(--app-text-muted);
323
+ --tk-bg: var(--app-bg);
324
+ --tk-surface: var(--app-surface);
325
+ --tk-border: var(--app-border);
326
+ --tk-accent: var(--app-accent);
327
+ --tk-accent-fg: var(--app-accent-ink);
328
+ --tk-danger: var(--app-danger);
329
+ }
330
+ ```
331
+
332
+ The parts you can address with `classNames` / CSS: `panel`, `title`, `form`,
333
+ `field`, `label`, `hint`, `input`, `textarea`, `check`, `switch`, `button`
334
+ (`tk-button--primary|danger|quiet`), `actions`, `segmented`, `segment`,
335
+ `notice` (`tk-notice--error|ok|info`), `balance` (`tk-balance--pill|full|empty`),
336
+ `breakdown`, `list`, `row` (`tk-row__main|title|meta|amount`) and the helper
337
+ `tk-hide-narrow` (hides the pill's unit name under 430 px).
338
+
339
+ ## Units
340
+
341
+ ```ts
342
+ import {
343
+ formatUnits,
344
+ formatCompact,
345
+ formatMoney,
346
+ unitsOf,
347
+ creditFor,
348
+ } from "@kaperkunde/tokens"
349
+
350
+ formatUnits(8_000_000, unit) // "8,000,000 credits"
351
+ formatUnits(84_000, unit, { compact: true }) // "84k credits"
352
+ formatCompact(1_234_000) // "1.2M"
353
+ formatMoney(1000, "eur") // "€10.00"
354
+ creditFor(1000, { centsPerDollar: 100 }) // 10_000_000 micros
355
+ ```
356
+
357
+ ## Testing against the stub
358
+
359
+ `@kaperkunde/tokens/stub` is a dependency-free stand-in for the center, the
360
+ same one the contract ships: in-memory wallet, the canned or forwarded
361
+ provider answers, the app API, signed webhooks and a few test controls. Use it
362
+ in an app's end-to-end tests and CI so no network or private service is needed.
363
+
364
+ ```sh
365
+ TOKENS_STUB_PORT=4100 \
366
+ TOKENS_STUB_OPENAI_UPSTREAM=http://localhost:3009/v1 \
367
+ TOKENS_STUB_EXTRA_MODELS=fake-model \
368
+ TOKENS_STUB_WEBHOOK_URL=http://localhost:3001/api/tokens/webhook \
369
+ npx tokens-stub
370
+ ```
371
+
372
+ ```ts
373
+ import { startStub } from "@kaperkunde/tokens/stub"
374
+
375
+ const stub = await startStub({
376
+ port: 0, // any free port
377
+ key: "tk_test_e2e", // the only key accepted (any non-empty key when unset)
378
+ webhookUrl: "http://localhost:3001/api/tokens/webhook",
379
+ webhookSecret: "whsec_e2e",
380
+ upstream: { openai: "http://localhost:3009/v1" }, // forward to your fake LLM
381
+ extraModels: ["fake-model"],
382
+ unitOne: "credit",
383
+ unitMany: "credits",
384
+ })
385
+ // stub.url, stub.reset(), await stub.close()
386
+ ```
387
+
388
+ Options map onto `TOKENS_STUB_PORT`, `_KEY`, `_WEBHOOK_URL`, `_WEBHOOK_SECRET`,
389
+ `_ANTHROPIC_UPSTREAM`, `_OPENAI_UPSTREAM`, `_OWN_UPSTREAM`, `_EXTRA_MODELS`,
390
+ `_PACKS` / `_PACKS_ONLY` (the app's packs, default 500,1000,2500,5000), `_START_MICROS` (a new user starts with $5), `_FEE_BPS` (2000), `_UNIT_ONE`,
391
+ `_UNIT_MANY` and `_REPLY`; an option wins over its variable.
392
+
393
+ Fixed prices: every model $3 / $15 per million tokens in / out, so a canned
394
+ call costs 600 micros (720 charged from purchased, fee included); speech is $15
395
+ per million characters. A model id containing `unpriced` answers
396
+ `model_not_priced`.
397
+
398
+ Test controls (no auth; the real center has none of these):
399
+
400
+ | Call | Does |
401
+ | ------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
402
+ | `POST /stub/reset` | Forget everything |
403
+ | `POST /stub/mode {"down":true}` | Every call answers 503 `center_unavailable` (fail-closed tests) |
404
+ | `POST /stub/mode {"providerError":true}` | Gateway calls answer 502 `provider_error` |
405
+ | `POST /stub/mode {"fail":"out_of_credit"}` (or env `TOKENS_STUB_FAIL`, the `fail` option, or the request header `x-stub-fail`) | Gateway calls answer 503 `provider_out_of_credit` (provider, model, `x-should-retry: false`); `"rate_limited"` 429 `provider_rate_limited` + `Retry-After: 7`; `"overloaded"` 503 `provider_overloaded`; `null` clears it. Speech does not fail: `stub-voice` falls back to `stub-voice-eleven` and answers with `x-token-voice-fallback` |
406
+ | `POST /stub/balance {"userId","purchasedMicros"}` | Set purchased (0 → `insufficient_balance` on the next call) |
407
+ | `POST /stub/grant {"userId","micros","provider"?,"expiresAt"?}` | Add a lot and send `grant.received` |
408
+ | `POST /stub/expire {"lotId"}` | Expire a lot, send `grant.expired` |
409
+ | `POST /stub/autorefill-fail {"userId"}` | Turn auto-refill off, send `autorefill.failed` |
410
+ | `GET /stub/checkout/:purchaseId` | The "Stripe page": pays, credits, sends `purchase.completed`, 303 back |
411
+ | `GET /stub/card/:userId?to=` | Saves a Visa ending 4242 and redirects to `to` |
412
+ | `GET /stub/state` | Every balance and call, for assertions |
413
+
414
+ A Playwright test follows the checkout URL the app returns and lands on the
415
+ app's success URL with the wallet credited. The stub's webhooks are signed
416
+ exactly as the center signs them, so `webhookRoute` can be tested end to end.
417
+ Not simulated: the in-flight cap, rate limits, idempotency keys, Stripe, tax,
418
+ auto-refill charges and own-endpoint limits.
419
+
420
+ ## Contract
421
+
422
+ `CONTRACT_VERSION` (1) names the contract these types and the stub follow. A
423
+ change that breaks a client is a new major version of this package.
424
+
425
+ Speech from the stub is a short run of real, silent MP3 frames, so an audio
426
+ element plays it. EUR sells at 121 cents per dollar of credit, USD at 100.
@@ -0,0 +1,56 @@
1
+ import { AppInfo, AutoRefill, AutoRefillInput, BackendOrder, Balance, CallsPage, CallsQuery, CardSetupSession, Cents, CheckoutSession, Currency, HistoryPage, ModelInfo, OwnEndpoint, OwnEndpointInput, OwnEndpointResponse, OwnEndpointTest, Purchase, SalePrices } from "./types.mjs";
2
+ /** What the browser sends to `POST <base>/checkout`. The app adds the user and the return URLs. */
3
+ export type CheckoutInput = {
4
+ currency: Currency;
5
+ amountCents: Cents;
6
+ /** Save the card for auto-refill. */
7
+ saveCard?: boolean;
8
+ locale?: string;
9
+ /** A path on the app's own origin to come back to (default `/`). */
10
+ returnPath?: string;
11
+ };
12
+ /** What the browser sends to `POST <base>/card`. */
13
+ export type CardInput = {
14
+ currency?: Currency;
15
+ returnPath?: string;
16
+ };
17
+ /**
18
+ * The browser's client for the routes an app mounts with `tokenRoutes` from
19
+ * `@kaperkunde/tokens/server` (default base `/api/tokens`). It carries the
20
+ * session cookie only: the app key never reaches a browser. Every method
21
+ * throws a `TokenCenterError` (a network failure is `center_unavailable`).
22
+ */
23
+ export type TokenApi = {
24
+ app(): Promise<AppInfo>;
25
+ models(): Promise<ModelInfo[]>;
26
+ balance(): Promise<Balance>;
27
+ calls(query?: CallsQuery): Promise<CallsPage>;
28
+ history(query?: {
29
+ limit?: number;
30
+ cursor?: string;
31
+ }): Promise<HistoryPage>;
32
+ salePrices(): Promise<SalePrices>;
33
+ purchase(id: string): Promise<Purchase>;
34
+ /** Opens Stripe Checkout; send the browser to `url`. */
35
+ checkout(input: CheckoutInput, idempotencyKey?: string): Promise<CheckoutSession>;
36
+ autoRefill(): Promise<AutoRefill>;
37
+ setAutoRefill(input: AutoRefillInput): Promise<AutoRefill>;
38
+ /** Opens Stripe in setup mode to save a card; send the browser to `url`. */
39
+ setupCard(input?: CardInput, idempotencyKey?: string): Promise<CardSetupSession>;
40
+ removeCard(): Promise<void>;
41
+ /** `null` when the user has saved none. */
42
+ ownEndpoint(): Promise<OwnEndpointResponse>;
43
+ saveOwnEndpoint(input: OwnEndpointInput): Promise<OwnEndpoint>;
44
+ removeOwnEndpoint(): Promise<void>;
45
+ testOwnEndpoint(): Promise<OwnEndpointTest>;
46
+ setBackendOrder(order: BackendOrder): Promise<{
47
+ order: BackendOrder;
48
+ }>;
49
+ };
50
+ export type TokenApiOptions = {
51
+ basePath?: string;
52
+ fetch?: typeof fetch;
53
+ /** Extra headers on every request (a CSRF token, say). */
54
+ headers?: Record<string, string>;
55
+ };
56
+ export declare function createTokenApi(options?: TokenApiOptions): TokenApi;
@@ -0,0 +1,75 @@
1
+ import { centerUnavailable, errorFromResponse, isTokenError } from "./errors.mjs";
2
+ // src/browser-api.ts
3
+ function createTokenApi(options = {}) {
4
+ const base = (options.basePath ?? "/api/tokens").replace(/\/+$/, "");
5
+ async function send(method, path, init = {}) {
6
+ const search = new URLSearchParams();
7
+ for (const [k, v] of Object.entries(init.query ?? {})) if (v !== void 0 && v !== null && v !== "") search.set(k, String(v));
8
+ const url = `${base}/${path}${search.size ? `?${search}` : ""}`;
9
+ const headers = {
10
+ accept: "application/json",
11
+ ...options.headers
12
+ };
13
+ if (init.body !== void 0) headers["content-type"] = "application/json";
14
+ if (init.idempotencyKey) headers["idempotency-key"] = init.idempotencyKey;
15
+ let response;
16
+ try {
17
+ response = await (options.fetch ?? fetch)(url, {
18
+ method,
19
+ headers,
20
+ credentials: "same-origin",
21
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
22
+ });
23
+ } catch (cause) {
24
+ throw centerUnavailable(cause, "Could not reach the server.");
25
+ }
26
+ if (response.status === 204) return void 0;
27
+ let body = null;
28
+ let readable = true;
29
+ try {
30
+ body = await response.json();
31
+ } catch {
32
+ readable = false;
33
+ }
34
+ if (!response.ok) throw errorFromResponse(response.status, body, {
35
+ code: response.headers.get("x-token-error"),
36
+ retryAfter: response.headers.get("retry-after"),
37
+ callId: response.headers.get("x-token-call-id")
38
+ });
39
+ if (!readable) throw centerUnavailable(void 0, "The server answered nothing readable.");
40
+ return body;
41
+ }
42
+ return {
43
+ app: () => send("GET", "app"),
44
+ models: async () => (await send("GET", "models")).models,
45
+ balance: () => send("GET", "balance"),
46
+ calls: (query) => send("GET", "calls", { query }),
47
+ history: (query) => send("GET", "history", { query }),
48
+ salePrices: () => send("GET", "sale-prices"),
49
+ purchase: (id) => send("GET", `purchase/${encodeURIComponent(id)}`),
50
+ checkout: (input, idempotencyKey) => send("POST", "checkout", {
51
+ body: input,
52
+ idempotencyKey
53
+ }),
54
+ autoRefill: () => send("GET", "autorefill"),
55
+ setAutoRefill: (input) => send("PUT", "autorefill", { body: input }),
56
+ setupCard: (input, idempotencyKey) => send("POST", "card", {
57
+ body: input ?? {},
58
+ idempotencyKey
59
+ }),
60
+ removeCard: () => send("DELETE", "card"),
61
+ ownEndpoint: async () => {
62
+ try {
63
+ return await send("GET", "own-endpoint");
64
+ } catch (error) {
65
+ if (isTokenError(error, "not_found")) return null;
66
+ throw error;
67
+ }
68
+ },
69
+ saveOwnEndpoint: (input) => send("PUT", "own-endpoint", { body: input }),
70
+ removeOwnEndpoint: () => send("DELETE", "own-endpoint"),
71
+ testOwnEndpoint: () => send("POST", "own-endpoint/test"),
72
+ setBackendOrder: (order) => send("PUT", "backend-order", { body: { order } })
73
+ };
74
+ }
75
+ export { createTokenApi };
@@ -0,0 +1,47 @@
1
+ import { ErrorCode, TokenErrorDetail } from "./types.mjs";
2
+ /**
3
+ * An error the Token Center answered with (or that the client synthesised for
4
+ * it: `center_unavailable` when it cannot be reached). `code` is the contract's
5
+ * stable code, `status` the HTTP status, `detail` the whole body the center
6
+ * sent (`action`, `capability`, `minimumCents`, `retryAfterSeconds` …).
7
+ *
8
+ * `message` is an English sentence safe to show a user.
9
+ */
10
+ export declare class TokenCenterError extends Error {
11
+ readonly code: ErrorCode;
12
+ readonly status: number;
13
+ readonly detail: TokenErrorDetail;
14
+ constructor(detail: TokenErrorDetail, status?: number, options?: {
15
+ cause?: unknown;
16
+ });
17
+ /** The center's call this error belongs to (`x-token-call-id`), when it does: a failed or refused call. */
18
+ get callId(): string | undefined;
19
+ /** `invalid_request`: the JSON path of the offending field or header (`amountCents`, `tools[0].type`, `body`). */
20
+ get path(): string | undefined;
21
+ /**
22
+ * Whether asking again can work: `provider_rate_limited`, `provider_overloaded`,
23
+ * `provider_timeout`, `rate_limited` and `center_unavailable` can; `provider_out_of_credit`
24
+ * cannot until an admin tops the center's account up.
25
+ */
26
+ get retryable(): boolean;
27
+ /** What the app should offer the user: buy tokens, set up an own model, wait. */
28
+ get action(): TokenErrorDetail["action"];
29
+ }
30
+ export declare const isErrorCode: (value: unknown) => value is ErrorCode;
31
+ /** Whether `error` is a `TokenCenterError`, optionally of one of `codes`. */
32
+ export declare function isTokenError(error: unknown, ...codes: ErrorCode[]): error is TokenCenterError;
33
+ /** `center_unavailable`: nothing answered, or only a 5xx with no contract body. Apps fail closed. */
34
+ export declare function centerUnavailable(cause?: unknown, message?: string): TokenCenterError;
35
+ /** A `TokenErrorDetail` out of anything shaped like one, or null. */
36
+ export declare function detailOf(value: unknown): TokenErrorDetail | null;
37
+ /**
38
+ * The error for a non-2xx answer. Reads, in order: the app API body
39
+ * (`{ error: {code, …} }`), the gateway body (`{ …, token_center: {code, …} }`),
40
+ * the `x-token-error` header; with none of them a 5xx is `center_unavailable`
41
+ * (a proxy's error page, a crash) and anything else is mapped by status.
42
+ */
43
+ export declare function errorFromResponse(status: number, body: unknown, headers?: {
44
+ code?: string | null;
45
+ retryAfter?: string | null;
46
+ callId?: string | null;
47
+ }): TokenCenterError;