@kaperkunde/tokens 0.0.0-stage → 0.1.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.
Files changed (50) hide show
  1. package/README.md +415 -2
  2. package/dist/browser-api.d.mts +56 -0
  3. package/dist/browser-api.mjs +75 -0
  4. package/dist/errors.d.mts +41 -0
  5. package/dist/errors.mjs +97 -0
  6. package/dist/index.d.mts +5 -0
  7. package/dist/index.mjs +5 -0
  8. package/dist/react/autorefill.d.mts +21 -0
  9. package/dist/react/autorefill.mjs +269 -0
  10. package/dist/react/balance.d.mts +23 -0
  11. package/dist/react/balance.mjs +116 -0
  12. package/dist/react/buy.d.mts +27 -0
  13. package/dist/react/buy.mjs +175 -0
  14. package/dist/react/history.d.mts +23 -0
  15. package/dist/react/history.mjs +102 -0
  16. package/dist/react/hooks.d.mts +52 -0
  17. package/dist/react/hooks.mjs +150 -0
  18. package/dist/react/index.d.mts +11 -0
  19. package/dist/react/index.mjs +10 -0
  20. package/dist/react/labels.d.mts +114 -0
  21. package/dist/react/labels.mjs +125 -0
  22. package/dist/react/own-model.d.mts +31 -0
  23. package/dist/react/own-model.mjs +358 -0
  24. package/dist/react/ui.d.mts +61 -0
  25. package/dist/react/ui.mjs +128 -0
  26. package/dist/react/usage.d.mts +21 -0
  27. package/dist/react/usage.mjs +137 -0
  28. package/dist/server/client.d.mts +76 -0
  29. package/dist/server/client.mjs +137 -0
  30. package/dist/server/error-of.d.mts +12 -0
  31. package/dist/server/error-of.mjs +63 -0
  32. package/dist/server/gateway.d.mts +62 -0
  33. package/dist/server/gateway.mjs +110 -0
  34. package/dist/server/index.d.mts +7 -0
  35. package/dist/server/index.mjs +7 -0
  36. package/dist/server/node.d.mts +23 -0
  37. package/dist/server/node.mjs +81 -0
  38. package/dist/server/routes.d.mts +56 -0
  39. package/dist/server/routes.mjs +257 -0
  40. package/dist/server/webhook.d.mts +47 -0
  41. package/dist/server/webhook.mjs +99 -0
  42. package/dist/styles.css +380 -0
  43. package/dist/types.d.mts +635 -0
  44. package/dist/types.mjs +142 -0
  45. package/dist/units.d.mts +37 -0
  46. package/dist/units.mjs +76 -0
  47. package/package.json +73 -4
  48. package/stub/cli.mjs +8 -0
  49. package/stub/server.d.mts +36 -0
  50. package/stub/server.mjs +1385 -0
package/dist/types.mjs ADDED
@@ -0,0 +1,142 @@
1
+ // src/types.ts
2
+ /**
3
+ * Token Center contract types, contract version 1.
4
+ *
5
+ * The single source of truth shared by the center and `@kaperkunde/tokens` (each carries a copy). openapi.yaml says the same thing
6
+ * over HTTP; if the two ever disagree, this file wins and openapi.yaml is fixed.
7
+ *
8
+ * Conventions:
9
+ * - Money is integer **micro-dollars** (`Micros`, 1 USD = 1_000_000). JSON carries it as a
10
+ * number (safe up to 9e15, i.e. $9bn). Never floats for balances.
11
+ * - Fiat amounts for Stripe are integer **cents** in the named currency.
12
+ * - Times are ISO 8601 strings in UTC (`2026-12-01T00:00:00.000Z`).
13
+ * - `userId` is always the **app's own user id** (opaque string, 1..128 chars). The center never
14
+ * sees one app's users from another app (`appId` comes from the key, never from the body).
15
+ */
16
+ const CONTRACT_VERSION = 1;
17
+ /**
18
+ * Header names (lower case; HTTP is case-insensitive). Request values that carry user text --
19
+ * `x-token-user`, `x-token-email` and every attribution header -- are
20
+ * `encodeURIComponent`-encoded by the client (the package always encodes them) and decoded by
21
+ * the center (a value that is not valid percent-encoding is taken as it is). A decoded
22
+ * attribution value is at most 200 characters, longer is cut; a decoded user id is 1..128.
23
+ */
24
+ const TOKEN_HEADERS = {
25
+ /** The app's user id, URI-encoded. Required on every gateway request. */
26
+ user: "x-token-user",
27
+ /** The user's **verified** email, URI-encoded. Optional; stored/updated on the center's user row. */
28
+ email: "x-token-email",
29
+ /** What the call is for, a small closed set per app (e.g. storyteller, player, voice). */
30
+ purpose: "x-token-purpose",
31
+ /** A human line ("Telling Ash"). */
32
+ activity: "x-token-activity",
33
+ /** The app's grouping (e.g. a party or a world id). */
34
+ scope: "x-token-scope",
35
+ /** The app's job id (a job id in the app's own queue). */
36
+ job: "x-token-job",
37
+ /** What the call is about (e.g. a character or chapter id). */
38
+ subject: "x-token-subject",
39
+ /** Groups several gateway requests into one app-level call (the app's own ledger row id). */
40
+ correlation: "x-token-correlation",
41
+ /** `tokens` (default) or `own`. `own` sends a chat-completions request to the user's own endpoint. */
42
+ backend: "x-token-backend",
43
+ /** `event`: append a final `event: token_center` SSE event carrying the CallCharge. Off by default. */
44
+ trailer: "x-token-trailer",
45
+ /** Idempotency for app API POSTs that create something (checkout, card setup). */
46
+ idempotencyKey: "idempotency-key",
47
+ callId: "x-token-call-id",
48
+ /** `tokens` | `own` */
49
+ source: "x-token-source",
50
+ /** The model that actually ran (may differ from the requested one on `own`). */
51
+ model: "x-token-model",
52
+ /** Provider cost of the call at the price in force, micros. Absent on streams (use GET /api/v1/calls/:id or the trailer). */
53
+ costMicros: "x-token-cost-micros",
54
+ /** Fee charged on the purchased portion, micros. */
55
+ feeMicros: "x-token-fee-micros",
56
+ /** What the call came to, cost + fee, micros (the wallet lost this less any absorbed shortfall). */
57
+ chargedMicros: "x-token-charged-micros",
58
+ /** Total spendable after the charge (all lots, all providers), micros. */
59
+ balanceMicros: "x-token-balance-micros",
60
+ /** Characters metered on a speech call. */
61
+ chars: "x-token-chars",
62
+ /** On every error response: the stable ErrorCode. */
63
+ error: "x-token-error",
64
+ /** Rate limited / in-flight cap: seconds to wait (standard header). */
65
+ retryAfter: "retry-after",
66
+ /** `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>` */
67
+ signature: "token-signature",
68
+ eventId: "token-event-id"
69
+ };
70
+ /** The keys the gateway accepts for the app key: Anthropic SDKs send `x-api-key`, OpenAI SDKs `authorization: Bearer`. */
71
+ const APP_KEY_HEADERS = ["x-api-key", "authorization"];
72
+ /** App key format: `tk_<live|test>_<keyId 12 chars>_<secret 40 chars base62>`. Only sha256(secret) is stored. */
73
+ const APP_KEY_PATTERN = /^tk_(live|test)_[A-Za-z0-9]{12}_[A-Za-z0-9]{40}$/;
74
+ /** Webhook signature tolerance. */
75
+ const WEBHOOK_TOLERANCE_SECONDS = 300;
76
+ const ERROR_CODES = [
77
+ "unauthenticated",
78
+ "forbidden",
79
+ "invalid_request",
80
+ "unknown_user",
81
+ "not_found",
82
+ "unknown_model",
83
+ "model_not_priced",
84
+ "wrong_protocol",
85
+ "insufficient_balance",
86
+ "capability_unavailable",
87
+ "byo_not_configured",
88
+ "byo_failed",
89
+ "byo_limit_reached",
90
+ "provider_error",
91
+ "provider_timeout",
92
+ "rate_limited",
93
+ "payments_unavailable",
94
+ "purchase_too_small",
95
+ "no_card",
96
+ "conflict",
97
+ "center_unavailable",
98
+ "internal_error"
99
+ ];
100
+ const ERROR_STATUS = {
101
+ unauthenticated: 401,
102
+ forbidden: 403,
103
+ invalid_request: 400,
104
+ unknown_user: 404,
105
+ not_found: 404,
106
+ unknown_model: 404,
107
+ model_not_priced: 409,
108
+ wrong_protocol: 400,
109
+ insufficient_balance: 402,
110
+ capability_unavailable: 402,
111
+ byo_not_configured: 409,
112
+ byo_failed: 502,
113
+ byo_limit_reached: 402,
114
+ provider_error: 502,
115
+ provider_timeout: 504,
116
+ rate_limited: 429,
117
+ payments_unavailable: 503,
118
+ purchase_too_small: 400,
119
+ no_card: 409,
120
+ conflict: 409,
121
+ center_unavailable: 503,
122
+ internal_error: 500
123
+ };
124
+ const WEBHOOK_EVENT_TYPES = [
125
+ "grant.received",
126
+ "purchase.completed",
127
+ "balance.low",
128
+ "balance.empty",
129
+ "autorefill.failed",
130
+ "grant.expired"
131
+ ];
132
+ /** Retry schedule after a non-2xx or a timeout (10 s): then the delivery is dead (admin may replay). */
133
+ const WEBHOOK_RETRY_SECONDS = [
134
+ 60,
135
+ 300,
136
+ 1800,
137
+ 7200,
138
+ 21600,
139
+ 43200,
140
+ 86400
141
+ ];
142
+ export { APP_KEY_HEADERS, APP_KEY_PATTERN, CONTRACT_VERSION, ERROR_CODES, ERROR_STATUS, TOKEN_HEADERS, WEBHOOK_EVENT_TYPES, WEBHOOK_RETRY_SECONDS, WEBHOOK_TOLERANCE_SECONDS };
@@ -0,0 +1,37 @@
1
+ import { AppUnit, Cents, Currency, Micros, SalePrice } from "./types.mjs";
2
+ /** Micro-dollars per dollar: the contract's money unit. */
3
+ export declare const MICROS_PER_DOLLAR = 1000000;
4
+ /**
5
+ * How many of an app's display unit `micros` is. With `perDollar` 1,000,000
6
+ * (an app whose unit is 1,000,000 per dollar) one unit is one micro-dollar.
7
+ * Rounded toward zero so a balance is never overstated.
8
+ */
9
+ export declare function unitsOf(micros: Micros, unit: Pick<AppUnit, "perDollar"> | number): number;
10
+ /** The other way: how many micros `units` of the app's unit are. */
11
+ export declare function microsOf(units: number, unit: Pick<AppUnit, "perDollar"> | number): Micros;
12
+ /** Dollars as a float, for display only (never for balances). */
13
+ export declare const microsToUsd: (micros: Micros) => number;
14
+ /**
15
+ * "84k", "1.2M", "950": a short number for a pill. One decimal below 10 of a
16
+ * suffix ("1.2M"), none above ("12M"); always truncated, so "999,999" is "999k"
17
+ * and a balance is never shown larger than it is. Negative numbers keep their sign.
18
+ */
19
+ export declare function formatCompact(value: number): string;
20
+ export type FormatUnitsOptions = {
21
+ /** "84k credits" instead of "84,000 credits". */
22
+ compact?: boolean;
23
+ /** Leave the unit's name off: "84,000". */
24
+ bare?: boolean;
25
+ locale?: string;
26
+ };
27
+ /** "8,000,000 credits", "1 credit", "84k tokens": micros in the app's own unit. */
28
+ export declare function formatUnits(micros: Micros, unit: AppUnit, options?: FormatUnitsOptions): string;
29
+ /** "€10.00", "$4.50": integer cents in a currency. */
30
+ export declare function formatMoney(cents: Cents, currency: Currency | string, locale?: string): string;
31
+ /**
32
+ * What a purchase of `amountCents` credits, in micros, at a sale price:
33
+ * `floor(cents × 1e6 / centsPerDollar)`, the center's own rule. The center
34
+ * fixes it when the purchase is opened and answers it as `creditMicros`; this
35
+ * is for showing "€10 buys 10,000,000 tokens" before asking.
36
+ */
37
+ export declare function creditFor(amountCents: Cents, price: Pick<SalePrice, "centsPerDollar">): Micros;
package/dist/units.mjs ADDED
@@ -0,0 +1,76 @@
1
+ // src/units.ts
2
+ /** Micro-dollars per dollar: the contract's money unit. */
3
+ const MICROS_PER_DOLLAR = 1e6;
4
+ /**
5
+ * How many of an app's display unit `micros` is. With `perDollar` 1,000,000
6
+ * (an app whose unit is 1,000,000 per dollar) one unit is one micro-dollar.
7
+ * Rounded toward zero so a balance is never overstated.
8
+ */
9
+ function unitsOf(micros, unit) {
10
+ const perDollar = typeof unit === "number" ? unit : unit.perDollar;
11
+ return Math.trunc(micros * perDollar / MICROS_PER_DOLLAR);
12
+ }
13
+ /** The other way: how many micros `units` of the app's unit are. */
14
+ function microsOf(units, unit) {
15
+ const perDollar = typeof unit === "number" ? unit : unit.perDollar;
16
+ return Math.round(units * MICROS_PER_DOLLAR / perDollar);
17
+ }
18
+ /** Dollars as a float, for display only (never for balances). */
19
+ const microsToUsd = (micros) => micros / MICROS_PER_DOLLAR;
20
+ const SUFFIXES = [
21
+ {
22
+ at: 0xe8d4a51000,
23
+ suffix: "T"
24
+ },
25
+ {
26
+ at: 1e9,
27
+ suffix: "B"
28
+ },
29
+ {
30
+ at: 1e6,
31
+ suffix: "M"
32
+ },
33
+ {
34
+ at: 1e3,
35
+ suffix: "k"
36
+ }
37
+ ];
38
+ /**
39
+ * "84k", "1.2M", "950": a short number for a pill. One decimal below 10 of a
40
+ * suffix ("1.2M"), none above ("12M"); always truncated, so "999,999" is "999k"
41
+ * and a balance is never shown larger than it is. Negative numbers keep their sign.
42
+ */
43
+ function formatCompact(value) {
44
+ if (!Number.isFinite(value)) return "0";
45
+ const sign = value < 0 ? "-" : "";
46
+ const abs = Math.abs(Math.trunc(value));
47
+ const step = SUFFIXES.find(({ at }) => abs >= at);
48
+ if (!step) return `${sign}${abs}`;
49
+ const scaled = abs / step.at;
50
+ const rounded = scaled < 10 ? Math.floor(scaled * 10) / 10 : Math.floor(scaled);
51
+ return `${sign}${Number.isInteger(rounded) ? rounded : rounded.toFixed(1)}${step.suffix}`;
52
+ }
53
+ /** "8,000,000 credits", "1 credit", "84k tokens": micros in the app's own unit. */
54
+ function formatUnits(micros, unit, options = {}) {
55
+ const n = unitsOf(micros, unit);
56
+ const number = options.compact ? formatCompact(n) : new Intl.NumberFormat(options.locale ?? "en").format(n);
57
+ if (options.bare) return number;
58
+ return `${number} ${Math.abs(n) === 1 ? unit.one : unit.many}`;
59
+ }
60
+ /** "€10.00", "$4.50": integer cents in a currency. */
61
+ function formatMoney(cents, currency, locale = "en") {
62
+ return new Intl.NumberFormat(locale, {
63
+ style: "currency",
64
+ currency: currency.toUpperCase()
65
+ }).format(cents / 100);
66
+ }
67
+ /**
68
+ * What a purchase of `amountCents` credits, in micros, at a sale price:
69
+ * `floor(cents × 1e6 / centsPerDollar)`, the center's own rule. The center
70
+ * fixes it when the purchase is opened and answers it as `creditMicros`; this
71
+ * is for showing "€10 buys 10,000,000 tokens" before asking.
72
+ */
73
+ function creditFor(amountCents, price) {
74
+ return Math.floor(amountCents * MICROS_PER_DOLLAR / price.centsPerDollar);
75
+ }
76
+ export { MICROS_PER_DOLLAR, creditFor, formatCompact, formatMoney, formatUnits, microsOf, microsToUsd, unitsOf };
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@kaperkunde/tokens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The client for the Token Center: the contract types, a typed server client and gateway config for AI SDK providers, webhook verification, browser-facing route handlers, React components for balance, buying, auto-refill, usage and own models, and a stand-in center for tests.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/kaperkunde/common-public.git",
10
+ "directory": "packages/tokens"
11
+ },
12
+ "engines": {
13
+ "node": ">=22"
14
+ },
15
+ "sideEffects": [
16
+ "*.css"
17
+ ],
18
+ "files": [
19
+ "dist",
20
+ "stub"
21
+ ],
22
+ "bin": {
23
+ "tokens-stub": "./stub/cli.mjs"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.mts",
28
+ "import": "./dist/index.mjs",
29
+ "default": "./dist/index.mjs"
30
+ },
31
+ "./server": {
32
+ "types": "./dist/server/index.d.mts",
33
+ "import": "./dist/server/index.mjs",
34
+ "default": "./dist/server/index.mjs"
35
+ },
36
+ "./react": {
37
+ "types": "./dist/react/index.d.mts",
38
+ "import": "./dist/react/index.mjs",
39
+ "default": "./dist/react/index.mjs"
40
+ },
41
+ "./stub": {
42
+ "types": "./stub/server.d.mts",
43
+ "import": "./stub/server.mjs",
44
+ "default": "./stub/server.mjs"
45
+ },
46
+ "./styles.css": "./dist/styles.css"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "typecheck": "tsc --noEmit -p tsconfig.json"
51
+ },
52
+ "peerDependencies": {
53
+ "react": "^19.0.0",
54
+ "react-dom": "^19.0.0"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "react": {
58
+ "optional": true
59
+ },
60
+ "react-dom": {
61
+ "optional": true
62
+ }
63
+ },
64
+ "devDependencies": {
65
+ "@types/react": "19.2.18",
66
+ "@types/react-dom": "19.2.7",
67
+ "happy-dom": "21.0.4",
68
+ "react": "19.2.8",
69
+ "react-dom": "19.2.8"
70
+ },
71
+ "publishConfig": {
72
+ "access": "public",
73
+ "provenance": true
74
+ }
75
+ }
package/stub/cli.mjs ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // `tokens-stub`: run the stand-in Token Center. Configure with TOKENS_STUB_* (see the README).
3
+ import { startStub } from "./server.mjs"
4
+
5
+ const stub = await startStub()
6
+ console.log(`[stub] token center contract stub on ${stub.url}`)
7
+ for (const signal of ["SIGINT", "SIGTERM"])
8
+ process.on(signal, () => stub.close().then(() => process.exit(0)))
@@ -0,0 +1,36 @@
1
+ export type StubOptions = {
2
+ /** 0 = any free port. Default `TOKENS_STUB_PORT` or 4100. */
3
+ port?: number
4
+ /** If set, the only app key accepted; otherwise any non-empty key is. */
5
+ key?: string
6
+ /** Where signed webhooks are POSTed; none when unset. */
7
+ webhookUrl?: string
8
+ /** HMAC secret for `token-signature`. Default `whsec_stub`. */
9
+ webhookSecret?: string
10
+ /** Base URLs (`…/v1`) provider calls are forwarded to; canned answers when unset. */
11
+ upstream?: { anthropic?: string; openai?: string; own?: string }
12
+ /** Extra model ids offered on the chat-completions protocol. */
13
+ extraModels?: string[] | string
14
+ /** Purchased balance a new user starts with, micros. Default 5,000,000. */
15
+ startMicros?: number
16
+ /** Fee on the purchased portion, basis points. Default 2000. */
17
+ feeBps?: number
18
+ unitOne?: string
19
+ unitMany?: string
20
+ /** The canned assistant text. */
21
+ reply?: string
22
+ /** Cents of the app's packs (default 500,1000,2500,5000). */
23
+ packsCents?: number[] | string
24
+ /** Allow only the packs. */
25
+ packsOnly?: boolean
26
+ }
27
+
28
+ export type Stub = {
29
+ url: string
30
+ port: number
31
+ /** Forget every user, call and purchase. */
32
+ reset(): void
33
+ close(): Promise<void>
34
+ }
35
+
36
+ export function startStub(options?: StubOptions): Promise<Stub>