@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
@@ -0,0 +1,175 @@
1
+ "use client";
2
+ import { creditFor, formatMoney, formatUnits } from "../units.mjs";
3
+ import { refreshTokens, useAppInfo, useLabels, useLocale, useSalePrices, useTokenApi } from "./hooks.mjs";
4
+ import { fill } from "./labels.mjs";
5
+ import { Field, Notice, Panel, Segmented, part, stillNeeded, useAction } from "./ui.mjs";
6
+ import { useState } from "react";
7
+ import { jsx, jsxs } from "react/jsx-runtime";
8
+ // src/react/buy.tsx
9
+ const DEFAULT_AMOUNTS = [
10
+ 500,
11
+ 1e3,
12
+ 2500,
13
+ 5e3
14
+ ];
15
+ /** Choose an amount and a currency, start Stripe Checkout through the app's route, and go there. */
16
+ function BuyTokens(props) {
17
+ const labels = useLabels(props.labels);
18
+ const locale = useLocale();
19
+ const api = useTokenApi(props.basePath);
20
+ const styling = props;
21
+ const prices = useSalePrices({ basePath: props.basePath });
22
+ const app = useAppInfo({
23
+ basePath: props.basePath,
24
+ skip: props.unit !== void 0
25
+ });
26
+ const unit = props.unit ?? app.data?.unit;
27
+ const available = (prices.data?.prices ?? []).filter((p) => !props.currencies || props.currencies.includes(p.currency));
28
+ const [currencyChoice, setCurrency] = useState(props.defaultCurrency ?? null);
29
+ const currency = available.find((p) => p.currency === currencyChoice) ? currencyChoice : available[0]?.currency ?? null;
30
+ const price = available.find((p) => p.currency === currency);
31
+ const options = prices.data?.options;
32
+ const packsOnly = options?.packsOnly === true;
33
+ const offered = props.amounts ?? (options?.packsCents.length ? options.packsCents : DEFAULT_AMOUNTS);
34
+ const amounts = packsOnly ? offered.filter((a) => options.packsCents.includes(a)) : offered;
35
+ const allowOther = props.allowOther !== false && !packsOnly;
36
+ const [chosen, setChosen] = useState(amounts[1] ?? amounts[0] ?? null);
37
+ const [other, setOther] = useState("");
38
+ const [saveCard, setSaveCard] = useState(false);
39
+ const action = useAction(labels);
40
+ const [problem, setProblem] = useState(null);
41
+ const otherCents = Math.round(Number(other.replace(",", ".")) * 100);
42
+ const cents = chosen === "other" ? Number.isFinite(otherCents) ? otherCents : 0 : chosen;
43
+ const needed = stillNeeded(labels, [{
44
+ label: labels.amount,
45
+ filled: cents !== null && cents > 0
46
+ }]);
47
+ const minimum = Math.max(price?.minimumCents ?? 0, options?.minimumCents ?? 0);
48
+ const maximum = options?.maximumCents ?? Infinity;
49
+ const paymentsOff = Boolean(prices.data && !prices.data.paymentsAvailable);
50
+ async function submit(event) {
51
+ event.preventDefault();
52
+ if (paymentsOff) return;
53
+ setProblem(null);
54
+ if (needed) return setProblem(needed);
55
+ if (!currency || !price) return setProblem(labels.paymentsUnavailable);
56
+ if (cents > maximum) return setProblem(fill(labels.maximum, { money: formatMoney(maximum, currency, locale) }));
57
+ if (cents < minimum) return setProblem(fill(labels.minimum, { money: formatMoney(minimum, currency, locale) }));
58
+ const input = {
59
+ currency,
60
+ amountCents: cents,
61
+ ...saveCard ? { saveCard: true } : {},
62
+ ...props.returnPath ? { returnPath: props.returnPath } : {},
63
+ ...locale ? { locale } : {}
64
+ };
65
+ const session = await action.run(() => props.onCheckout ? props.onCheckout(input) : api.checkout(input, crypto.randomUUID()));
66
+ if (session) {
67
+ refreshTokens();
68
+ if (props.onRedirect) props.onRedirect(session.url);
69
+ else window.location.assign(session.url);
70
+ }
71
+ }
72
+ return /* @__PURE__ */ jsxs(Panel, {
73
+ title: labels.buyTitle,
74
+ styling,
75
+ children: [
76
+ paymentsOff ? /* @__PURE__ */ jsx(Notice, {
77
+ kind: "info",
78
+ styling,
79
+ children: labels.paymentsUnavailable
80
+ }) : null,
81
+ prices.error ? /* @__PURE__ */ jsx(Notice, {
82
+ styling,
83
+ children: labels.unavailable
84
+ }) : null,
85
+ /* @__PURE__ */ jsxs("form", {
86
+ className: part(styling, "form"),
87
+ onSubmit: submit,
88
+ noValidate: true,
89
+ children: [
90
+ available.length > 1 && currency ? /* @__PURE__ */ jsx(Segmented, {
91
+ label: labels.currency,
92
+ value: currency,
93
+ options: available.map((p) => ({
94
+ value: p.currency,
95
+ label: p.currency.toUpperCase()
96
+ })),
97
+ onChange: setCurrency,
98
+ styling
99
+ }) : null,
100
+ /* @__PURE__ */ jsx(Segmented, {
101
+ label: labels.amount,
102
+ value: chosen,
103
+ options: [...amounts.map((a) => ({
104
+ value: a,
105
+ label: formatMoney(a, currency ?? "eur", locale)
106
+ })), ...!allowOther ? [] : [{
107
+ value: "other",
108
+ label: labels.otherAmount
109
+ }]],
110
+ onChange: setChosen,
111
+ styling
112
+ }),
113
+ chosen === "other" ? /* @__PURE__ */ jsx(Field, {
114
+ label: labels.otherAmount,
115
+ required: true,
116
+ styling,
117
+ children: (p) => /* @__PURE__ */ jsx("input", {
118
+ ...p,
119
+ className: part(styling, "input"),
120
+ type: "text",
121
+ inputMode: "decimal",
122
+ autoComplete: "off",
123
+ value: other,
124
+ onChange: (e) => setOther(e.target.value)
125
+ })
126
+ }) : null,
127
+ price && cents && cents > 0 && unit ? /* @__PURE__ */ jsxs("p", {
128
+ className: "tk-muted",
129
+ "aria-live": "polite",
130
+ children: [
131
+ fill(labels.buys, {
132
+ money: formatMoney(cents, price.currency, locale),
133
+ tokens: formatUnits(Math.max(0, creditFor(cents, price)), unit, { locale })
134
+ }),
135
+ " ",
136
+ labels.tax[price.taxBehavior]
137
+ ]
138
+ }) : null,
139
+ props.offerSaveCard === false ? null : /* @__PURE__ */ jsxs("label", {
140
+ className: part(styling, "check"),
141
+ children: [
142
+ /* @__PURE__ */ jsx("input", {
143
+ type: "checkbox",
144
+ checked: saveCard,
145
+ onChange: (e) => setSaveCard(e.target.checked)
146
+ }),
147
+ " ",
148
+ labels.saveCard
149
+ ]
150
+ }),
151
+ problem ? /* @__PURE__ */ jsx(Notice, {
152
+ styling,
153
+ children: problem
154
+ }) : null,
155
+ action.error ? /* @__PURE__ */ jsx(Notice, {
156
+ styling,
157
+ children: action.error
158
+ }) : null,
159
+ /* @__PURE__ */ jsx("div", {
160
+ className: part(styling, "actions"),
161
+ children: /* @__PURE__ */ jsx("button", {
162
+ type: "submit",
163
+ className: part(styling, "button", "tk-button--primary"),
164
+ "aria-busy": action.pending,
165
+ disabled: action.pending || paymentsOff,
166
+ title: paymentsOff ? labels.paymentsUnavailable : void 0,
167
+ children: action.pending ? labels.buying : cents && cents > 0 && currency ? fill(labels.buyButton, { amount: formatMoney(cents, currency, locale) }) : labels.buyButtonBare
168
+ })
169
+ })
170
+ ]
171
+ })
172
+ ]
173
+ });
174
+ }
175
+ export { BuyTokens };
@@ -0,0 +1,23 @@
1
+ import { AppUnit, HistoryEntry, HistoryPage } from "../types.mjs";
2
+ import { LabelOverrides, Labels } from "./labels.mjs";
3
+ import { Styling } from "./ui.mjs";
4
+ export type PurchaseHistoryProps = Styling & {
5
+ page?: HistoryPage;
6
+ limit?: number;
7
+ unit?: AppUnit;
8
+ labels?: LabelOverrides;
9
+ basePath?: string;
10
+ };
11
+ type Line = {
12
+ key: string;
13
+ title: string;
14
+ meta: string;
15
+ amount: string;
16
+ };
17
+ /** One history entry as the lines a row shows. Exported for tests and custom lists. */
18
+ export declare function historyLine(entry: HistoryEntry, unit: AppUnit, labels: Labels, locale?: string): Line;
19
+ /** Purchases, drops and grants, expiries and adjustments, newest first. */
20
+ export declare function PurchaseHistory(props: PurchaseHistoryProps): import("react").JSX.Element;
21
+ /** The same list under the name the center's docs use. */
22
+ export declare const HistoryList: typeof PurchaseHistory;
23
+ export {};
@@ -0,0 +1,102 @@
1
+ "use client";
2
+ import { formatMoney, formatUnits } from "../units.mjs";
3
+ import { useAppInfo, useHistory, useLabels, useLocale } from "./hooks.mjs";
4
+ import { Notice, Panel, dateText, part } from "./ui.mjs";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ // src/react/history.tsx
7
+ /** One history entry as the lines a row shows. Exported for tests and custom lists. */
8
+ function historyLine(entry, unit, labels, locale) {
9
+ const when = dateText(entry.at, locale);
10
+ const units = (n) => formatUnits(n, unit, {
11
+ locale,
12
+ bare: true
13
+ });
14
+ switch (entry.type) {
15
+ case "purchase": {
16
+ const p = entry.purchase;
17
+ const status = p.status === "paid" ? "" : ` · ${p.status === "open" ? labels.statusOpen : p.status === "failed" ? labels.statusFailed : labels.statusExpired}`;
18
+ return {
19
+ key: `purchase:${p.id}`,
20
+ title: p.kind === "refill" ? labels.refill : labels.purchase,
21
+ meta: `${when} · ${formatMoney(p.amountCents, p.currency, locale)}${status}`,
22
+ amount: p.status === "paid" ? `+${units(p.creditMicros)}` : "—"
23
+ };
24
+ }
25
+ case "grant": return {
26
+ key: `grant:${entry.lot.id}`,
27
+ title: entry.lot.kind === "airdrop" ? labels.airdrop : labels.grant,
28
+ meta: when,
29
+ amount: `+${units(entry.lot.grantedMicros)}`
30
+ };
31
+ case "expiry": return {
32
+ key: `expiry:${entry.lotId}:${entry.at}`,
33
+ title: labels.expiredLot,
34
+ meta: when,
35
+ amount: `−${units(entry.expiredMicros)}`
36
+ };
37
+ case "adjustment": return {
38
+ key: `adjustment:${entry.at}:${entry.reason}`,
39
+ title: labels.adjustment,
40
+ meta: `${when} · ${entry.reason}`,
41
+ amount: `${entry.micros >= 0 ? "+" : "−"}${units(Math.abs(entry.micros))}`
42
+ };
43
+ }
44
+ }
45
+ /** Purchases, drops and grants, expiries and adjustments, newest first. */
46
+ function PurchaseHistory(props) {
47
+ const labels = useLabels(props.labels);
48
+ const locale = useLocale();
49
+ const styling = props;
50
+ const loaded = useHistory({ limit: props.limit ?? 50 }, {
51
+ basePath: props.basePath,
52
+ skip: props.page !== void 0
53
+ });
54
+ const app = useAppInfo({
55
+ basePath: props.basePath,
56
+ skip: props.unit !== void 0
57
+ });
58
+ const unit = props.unit ?? app.data?.unit ?? {
59
+ one: "token",
60
+ many: "tokens",
61
+ perDollar: 1e6
62
+ };
63
+ const page = props.page ?? loaded.data;
64
+ return /* @__PURE__ */ jsx(Panel, {
65
+ title: labels.historyTitle,
66
+ styling,
67
+ children: !page ? loaded.error ? /* @__PURE__ */ jsx(Notice, {
68
+ styling,
69
+ children: labels.unavailable
70
+ }) : /* @__PURE__ */ jsx("p", {
71
+ className: "tk-muted",
72
+ children: labels.loading
73
+ }) : page.entries.length === 0 ? /* @__PURE__ */ jsx("p", {
74
+ className: "tk-muted",
75
+ children: labels.historyEmpty
76
+ }) : /* @__PURE__ */ jsx("ul", {
77
+ className: part(styling, "list"),
78
+ children: page.entries.map((entry) => {
79
+ const line = historyLine(entry, unit, labels, locale);
80
+ return /* @__PURE__ */ jsxs("li", {
81
+ className: part(styling, "row"),
82
+ children: [/* @__PURE__ */ jsxs("span", {
83
+ className: "tk-row__main",
84
+ children: [/* @__PURE__ */ jsx("span", {
85
+ className: "tk-row__title",
86
+ children: line.title
87
+ }), /* @__PURE__ */ jsx("span", {
88
+ className: "tk-row__meta",
89
+ children: line.meta
90
+ })]
91
+ }), /* @__PURE__ */ jsx("span", {
92
+ className: "tk-row__amount",
93
+ children: line.amount
94
+ })]
95
+ }, line.key);
96
+ })
97
+ })
98
+ });
99
+ }
100
+ /** The same list under the name the center's docs use. */
101
+ const HistoryList = PurchaseHistory;
102
+ export { HistoryList, PurchaseHistory, historyLine };
@@ -0,0 +1,52 @@
1
+ import { TokenApi } from "../browser-api.mjs";
2
+ import { TokenCenterError } from "../errors.mjs";
3
+ import { AppInfo, AutoRefill, Balance, CallsPage, CallsQuery, HistoryPage, OwnEndpoint, SalePrices } from "../types.mjs";
4
+ import { LabelOverrides, Labels } from "./labels.mjs";
5
+ import { ReactNode } from "react";
6
+ export type TokensProviderProps = {
7
+ /** Where the app mounted `tokenRoutes`. Default `/api/tokens`. */
8
+ basePath?: string;
9
+ /** Bring your own client (tests, a custom fetch). */
10
+ api?: TokenApi;
11
+ labels?: LabelOverrides;
12
+ /** For dates and numbers (default: the browser's). */
13
+ locale?: string;
14
+ children: ReactNode;
15
+ };
16
+ /** Gives every component below it the app's client, labels and locale. Optional: each component also works alone with `/api/tokens`. */
17
+ export declare function TokensProvider({ basePath, api, labels, locale, children }: TokensProviderProps): import("react").JSX.Element;
18
+ /** The client: from `basePath` if given, else the provider's, else `/api/tokens`. */
19
+ export declare function useTokenApi(basePath?: string): TokenApi;
20
+ export declare function useLabels(overrides?: LabelOverrides): Labels;
21
+ export declare const useLocale: () => string | undefined;
22
+ /** Ask every mounted `useBalance`/`useCalls`/… to load again (after a purchase, a spend you made yourself). */
23
+ export declare function refreshTokens(): void;
24
+ export type Resource<T> = {
25
+ data: T | undefined;
26
+ error: TokenCenterError | undefined;
27
+ loading: boolean;
28
+ refresh: () => Promise<void>;
29
+ };
30
+ export type ResourceOptions = {
31
+ /** Poll while the tab is visible, in ms. 0 or unset: no polling. */
32
+ refreshMs?: number;
33
+ /** Skip loading (a value the caller already has). */
34
+ skip?: boolean;
35
+ };
36
+ /** Load something now, on `key` changes, every `refreshMs` while visible, on focus, and on `refreshTokens()`. */
37
+ export declare function useResource<T>(load: () => Promise<T>, key: string, options?: ResourceOptions): Resource<T>;
38
+ type Opts = ResourceOptions & {
39
+ basePath?: string;
40
+ };
41
+ /** The signed-in user's balance, refreshed every 30 s while the tab is showing. */
42
+ export declare function useBalance(options?: Opts): Resource<Balance>;
43
+ export declare function useAppInfo(options?: Opts): Resource<AppInfo>;
44
+ export declare function useSalePrices(options?: Opts): Resource<SalePrices>;
45
+ export declare function useAutoRefill(options?: Opts): Resource<AutoRefill>;
46
+ /** `data` is `null` when the user has saved none. */
47
+ export declare function useOwnEndpoint(options?: Opts): Resource<OwnEndpoint | null>;
48
+ export declare function useCalls(query?: CallsQuery, options?: Opts): Resource<CallsPage>;
49
+ export declare function useHistory(query?: {
50
+ limit?: number;
51
+ }, options?: Opts): Resource<HistoryPage>;
52
+ export {};
@@ -0,0 +1,150 @@
1
+ "use client";
2
+ import { createTokenApi } from "../browser-api.mjs";
3
+ import { TokenCenterError, centerUnavailable } from "../errors.mjs";
4
+ import { mergeLabels } from "./labels.mjs";
5
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
6
+ import { jsx } from "react/jsx-runtime";
7
+ // src/react/hooks.tsx
8
+ const Context = createContext(null);
9
+ /** Gives every component below it the app's client, labels and locale. Optional: each component also works alone with `/api/tokens`. */
10
+ function TokensProvider({ basePath, api, labels, locale, children }) {
11
+ const value = useMemo(() => ({
12
+ api: api ?? createTokenApi({ basePath }),
13
+ labels,
14
+ locale
15
+ }), [
16
+ api,
17
+ basePath,
18
+ labels,
19
+ locale
20
+ ]);
21
+ return /* @__PURE__ */ jsx(Context.Provider, {
22
+ value,
23
+ children
24
+ });
25
+ }
26
+ const fallback = {
27
+ api: createTokenApi(),
28
+ labels: void 0,
29
+ locale: void 0
30
+ };
31
+ /** The client: from `basePath` if given, else the provider's, else `/api/tokens`. */
32
+ function useTokenApi(basePath) {
33
+ const context = useContext(Context);
34
+ return useMemo(() => basePath ? createTokenApi({ basePath }) : context?.api ?? fallback.api, [basePath, context]);
35
+ }
36
+ function useLabels(overrides) {
37
+ const context = useContext(Context);
38
+ return useMemo(() => mergeLabels(context?.labels, overrides), [context, overrides]);
39
+ }
40
+ const useLocale = () => useContext(Context)?.locale;
41
+ const REFRESH_EVENT = "tokens:refresh";
42
+ /** Ask every mounted `useBalance`/`useCalls`/… to load again (after a purchase, a spend you made yourself). */
43
+ function refreshTokens() {
44
+ if (typeof window !== "undefined") window.dispatchEvent(new Event(REFRESH_EVENT));
45
+ }
46
+ /** Load something now, on `key` changes, every `refreshMs` while visible, on focus, and on `refreshTokens()`. */
47
+ function useResource(load, key, options = {}) {
48
+ const [state, setState] = useState({
49
+ data: void 0,
50
+ error: void 0,
51
+ loading: !options.skip
52
+ });
53
+ const loader = useRef(load);
54
+ loader.current = load;
55
+ const serial = useRef(0);
56
+ const alive = useRef(true);
57
+ const skipped = useRef(options.skip);
58
+ skipped.current = options.skip;
59
+ const refresh = useCallback(async () => {
60
+ if (skipped.current) return;
61
+ const mine = ++serial.current;
62
+ try {
63
+ const data = await loader.current();
64
+ if (alive.current && mine === serial.current) setState({
65
+ data,
66
+ error: void 0,
67
+ loading: false
68
+ });
69
+ } catch (error) {
70
+ if (alive.current && mine === serial.current) setState((s) => ({
71
+ data: s.data,
72
+ error: error instanceof TokenCenterError ? error : centerUnavailable(error),
73
+ loading: false
74
+ }));
75
+ }
76
+ }, []);
77
+ const { refreshMs, skip } = options;
78
+ useEffect(() => {
79
+ alive.current = true;
80
+ if (skip) {
81
+ setState((s) => s.loading ? {
82
+ ...s,
83
+ loading: false
84
+ } : s);
85
+ return;
86
+ }
87
+ setState((s) => s.loading ? s : {
88
+ ...s,
89
+ loading: s.data === void 0
90
+ });
91
+ refresh();
92
+ const again = () => {
93
+ if (document.visibilityState !== "hidden") refresh();
94
+ };
95
+ const timer = refreshMs ? setInterval(again, refreshMs) : void 0;
96
+ window.addEventListener("focus", again);
97
+ document.addEventListener("visibilitychange", again);
98
+ window.addEventListener(REFRESH_EVENT, again);
99
+ return () => {
100
+ alive.current = false;
101
+ if (timer) clearInterval(timer);
102
+ window.removeEventListener("focus", again);
103
+ document.removeEventListener("visibilitychange", again);
104
+ window.removeEventListener(REFRESH_EVENT, again);
105
+ };
106
+ }, [
107
+ key,
108
+ refreshMs,
109
+ skip,
110
+ refresh
111
+ ]);
112
+ return {
113
+ ...state,
114
+ refresh
115
+ };
116
+ }
117
+ /** The signed-in user's balance, refreshed every 30 s while the tab is showing. */
118
+ function useBalance(options = {}) {
119
+ const api = useTokenApi(options.basePath);
120
+ return useResource(() => api.balance(), "balance", {
121
+ refreshMs: 3e4,
122
+ ...options
123
+ });
124
+ }
125
+ function useAppInfo(options = {}) {
126
+ const api = useTokenApi(options.basePath);
127
+ return useResource(() => api.app(), "app", options);
128
+ }
129
+ function useSalePrices(options = {}) {
130
+ const api = useTokenApi(options.basePath);
131
+ return useResource(() => api.salePrices(), "sale-prices", options);
132
+ }
133
+ function useAutoRefill(options = {}) {
134
+ const api = useTokenApi(options.basePath);
135
+ return useResource(() => api.autoRefill(), "autorefill", options);
136
+ }
137
+ /** `data` is `null` when the user has saved none. */
138
+ function useOwnEndpoint(options = {}) {
139
+ const api = useTokenApi(options.basePath);
140
+ return useResource(() => api.ownEndpoint(), "own-endpoint", options);
141
+ }
142
+ function useCalls(query = {}, options = {}) {
143
+ const api = useTokenApi(options.basePath);
144
+ return useResource(() => api.calls(query), `calls:${JSON.stringify(query)}`, options);
145
+ }
146
+ function useHistory(query = {}, options = {}) {
147
+ const api = useTokenApi(options.basePath);
148
+ return useResource(() => api.history(query), `history:${JSON.stringify(query)}`, options);
149
+ }
150
+ export { TokensProvider, refreshTokens, useAppInfo, useAutoRefill, useBalance, useCalls, useHistory, useLabels, useLocale, useOwnEndpoint, useResource, useSalePrices, useTokenApi };
@@ -0,0 +1,11 @@
1
+ import { TokenBalance, TokenBalanceProps } from "./balance.mjs";
2
+ import { BuyTokens, BuyTokensProps } from "./buy.mjs";
3
+ import { AutoRefill, AutoRefillProps } from "./autorefill.mjs";
4
+ import { UsageList, UsageListProps, cacheShare, callTitle } from "./usage.mjs";
5
+ import { HistoryList, PurchaseHistory, PurchaseHistoryProps, historyLine } from "./history.mjs";
6
+ import { BackendOrderSwitch, BackendOrderSwitchProps, OwnEndpointForm, OwnModelForm, OwnModelFormProps } from "./own-model.mjs";
7
+ import { Resource, ResourceOptions, TokensProvider, TokensProviderProps, refreshTokens, useAppInfo, useAutoRefill, useBalance, useCalls, useHistory, useLabels, useOwnEndpoint, useResource, useSalePrices, useTokenApi } from "./hooks.mjs";
8
+ import { DEFAULT_LABELS, LabelOverrides, Labels, fill, mergeLabels } from "./labels.mjs";
9
+ import { Styling } from "./ui.mjs";
10
+ import { CardInput, CheckoutInput, TokenApi } from "../browser-api.mjs";
11
+ export { AutoRefill, type AutoRefillProps, BackendOrderSwitch, type BackendOrderSwitchProps, BuyTokens, type BuyTokensProps, type CardInput, type CheckoutInput, DEFAULT_LABELS, HistoryList, type LabelOverrides, type Labels, OwnEndpointForm, OwnModelForm, type OwnModelFormProps, PurchaseHistory, type PurchaseHistoryProps, type Resource, type ResourceOptions, type Styling, type TokenApi, TokenBalance, type TokenBalanceProps, TokensProvider, type TokensProviderProps, UsageList, type UsageListProps, cacheShare, callTitle, fill, historyLine, mergeLabels, refreshTokens, useAppInfo, useAutoRefill, useBalance, useCalls, useHistory, useLabels, useOwnEndpoint, useResource, useSalePrices, useTokenApi };
@@ -0,0 +1,10 @@
1
+ "use client";
2
+ import { TokenBalance } from "./balance.mjs";
3
+ import { BuyTokens } from "./buy.mjs";
4
+ import { AutoRefill } from "./autorefill.mjs";
5
+ import { UsageList, cacheShare, callTitle } from "./usage.mjs";
6
+ import { HistoryList, PurchaseHistory, historyLine } from "./history.mjs";
7
+ import { BackendOrderSwitch, OwnEndpointForm, OwnModelForm } from "./own-model.mjs";
8
+ import { TokensProvider, refreshTokens, useAppInfo, useAutoRefill, useBalance, useCalls, useHistory, useLabels, useOwnEndpoint, useResource, useSalePrices, useTokenApi } from "./hooks.mjs";
9
+ import { DEFAULT_LABELS, fill, mergeLabels } from "./labels.mjs";
10
+ export { AutoRefill, BackendOrderSwitch, BuyTokens, DEFAULT_LABELS, HistoryList, OwnEndpointForm, OwnModelForm, PurchaseHistory, TokenBalance, TokensProvider, UsageList, cacheShare, callTitle, fill, historyLine, mergeLabels, refreshTokens, useAppInfo, useAutoRefill, useBalance, useCalls, useHistory, useLabels, useOwnEndpoint, useResource, useSalePrices, useTokenApi };
@@ -0,0 +1,114 @@
1
+ /** Every English string the components draw. Override any through `labels` on a component or the provider. */
2
+ export declare const DEFAULT_LABELS: {
3
+ readonly loading: "Loading…";
4
+ readonly retry: "Try again";
5
+ readonly unavailable: "Tokens are unavailable right now. Try again in a moment.";
6
+ readonly somethingWrong: "Something went wrong.";
7
+ readonly stillNeeded: "Still needed: {fields}.";
8
+ readonly balance: "Balance";
9
+ readonly balanceUnknown: "Balance unavailable";
10
+ readonly purchased: "Bought";
11
+ readonly fromGrants: "From drops and grants";
12
+ readonly expiring: "{amount} expire {date}";
13
+ readonly shortfall: "You owe {amount} from your last calls; it comes out of your next purchase.";
14
+ readonly feeNote: "A token buys a little less than a dollar of model use.";
15
+ readonly empty: "Out of tokens";
16
+ readonly buyMore: "Buy tokens";
17
+ readonly buyTitle: "Buy tokens";
18
+ readonly amount: "Amount";
19
+ readonly otherAmount: "Other amount";
20
+ readonly currency: "Currency";
21
+ readonly saveCard: "Save my card for auto-refill";
22
+ readonly buyButton: "Buy {amount}";
23
+ readonly buyButtonBare: "Buy";
24
+ readonly buying: "Opening checkout…";
25
+ readonly buys: "{money} buys {tokens}.";
26
+ readonly tax: {
27
+ readonly inclusive: "Price includes VAT.";
28
+ readonly exclusive: "Before sales tax; tax is added at checkout.";
29
+ };
30
+ readonly minimum: "The smallest purchase is {money}.";
31
+ readonly maximum: "The largest purchase is {money}.";
32
+ readonly paymentsUnavailable: "Buying is not available right now.";
33
+ readonly autoRefillTitle: "Auto-refill";
34
+ readonly autoRefillOn: "Refill automatically";
35
+ readonly autoRefillHelp: "When your bought tokens fall below the threshold, your card is charged for the amount below, up to the monthly maximum.";
36
+ readonly threshold: "When bought tokens fall below";
37
+ readonly refillAmount: "Refill amount";
38
+ readonly monthlyMax: "Most per month";
39
+ readonly card: "Card";
40
+ readonly noCard: "No card saved";
41
+ readonly addCard: "Add a card";
42
+ readonly replaceCard: "Replace card";
43
+ readonly removeCard: "Remove card";
44
+ readonly needCardFirst: "Save a card first, then turn auto-refill on.";
45
+ readonly autoRefillFailed: "Your last refill could not be charged, so auto-refill was turned off. Check your card and turn it back on.";
46
+ readonly save: "Save";
47
+ readonly saving: "Saving…";
48
+ readonly saved: "Saved.";
49
+ readonly usageTitle: "Recent usage";
50
+ readonly usageEmpty: "Nothing used yet.";
51
+ readonly cached: "{percent}% cached";
52
+ readonly tokensInOut: "{input} in · {output} out";
53
+ readonly yourOwn: "your own model";
54
+ readonly loadMore: "Show more";
55
+ readonly totals: "{count} calls · {amount} used";
56
+ readonly failedCall: "failed";
57
+ readonly historyTitle: "Purchases and grants";
58
+ readonly historyEmpty: "Nothing yet.";
59
+ readonly purchase: "Purchase";
60
+ readonly refill: "Auto-refill";
61
+ readonly grant: "Grant";
62
+ readonly airdrop: "Drop";
63
+ readonly expiredLot: "Expired";
64
+ readonly adjustment: "Adjustment";
65
+ readonly statusOpen: "waiting for payment";
66
+ readonly statusFailed: "failed";
67
+ readonly statusExpired: "expired";
68
+ readonly ownTitle: "Your own model";
69
+ readonly baseUrl: "Address";
70
+ readonly baseUrlHelp: "An OpenAI-compatible address that does not include /chat/completions.";
71
+ readonly apiKey: "Key";
72
+ readonly apiKeyHelp: "Stored sealed and never shown again.";
73
+ readonly apiKeySaved: "Saved ({hint}). Leave empty to keep it.";
74
+ readonly removeKey: "Remove the saved key";
75
+ readonly models: "Models";
76
+ readonly modelsHelp: "One per line.";
77
+ readonly defaultModel: "Model to use when the one asked for is not listed";
78
+ readonly capabilities: "What it can do";
79
+ readonly limit: "Most tokens a month";
80
+ readonly limitHelp: "Leave empty for no limit.";
81
+ readonly order: "Which first";
82
+ readonly orders: {
83
+ readonly tokens_then_own: "Tokens first, then my own";
84
+ readonly own_then_tokens: "My own first, then tokens";
85
+ readonly tokens_only: "Tokens only";
86
+ readonly own_only: "My own only";
87
+ };
88
+ readonly toolChoice: "When it is given tools";
89
+ readonly toolChoices: {
90
+ readonly auto: "Let the model decide";
91
+ readonly required: "Require it to call one";
92
+ };
93
+ readonly toolChoiceHelp: "Some models only call a tool when told to; choose Require if yours answers in prose instead.";
94
+ readonly orderNeedsOwn: "Save your own model first to use it.";
95
+ readonly test: "Test it";
96
+ readonly testing: "Testing…";
97
+ readonly testOk: "It answered in {ms} ms.";
98
+ readonly testFailed: "It did not answer: {message}";
99
+ readonly remove: "Remove";
100
+ readonly used: "{used} of {limit} used this month.";
101
+ readonly usedNoLimit: "{used} used this month.";
102
+ readonly capability: {
103
+ readonly tools: "Tools";
104
+ readonly streaming: "Streaming";
105
+ readonly vision: "Images";
106
+ readonly json: "JSON";
107
+ readonly voice: "Voice";
108
+ };
109
+ };
110
+ export type Labels = { [K in keyof typeof DEFAULT_LABELS]: (typeof DEFAULT_LABELS)[K] extends string ? string : { [P in keyof (typeof DEFAULT_LABELS)[K]]: string; }; };
111
+ export type LabelOverrides = { [K in keyof Labels]?: Labels[K] extends string ? string : Partial<Labels[K]>; };
112
+ /** Replace `{name}` placeholders. */
113
+ export declare const fill: (template: string, values: Record<string, string | number>) => string;
114
+ export declare function mergeLabels(...layers: (LabelOverrides | undefined)[]): Labels;