@hjam91/billing 0.0.0-stage → 0.7.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haroon Jameel
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,146 @@
1
- # Temporary Holding Version
1
+ # @hjam91/billing
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 app-side client for a **billing-kit** service: one shared Stripe billing backend that many apps use. Your server
4
+ asks it "may this account do this?" and it answers from Stripe's subscriptions, trials, plans, features, credits and
5
+ usage limits — so the app never stores billing state itself.
6
+
7
+ - **Zero runtime dependencies.** ESM, with TypeScript types. Node >= 20, Cloudflare Workers, Deno and bundlers.
8
+ - **Fail-open by design:** entitlement checks are cached and keep working through a billing outage.
9
+ - Entitlements, feature checks and usage tracking, Stripe Checkout and the customer portal, plan changes and add-ons,
10
+ signed webhook verification, a Hono gate, and an optional React billing card.
11
+
12
+ SDK: MIT. The billing service is a hosted product.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install @hjam91/billing
18
+ ```
19
+
20
+ `hono` and `react` are optional peer dependencies, needed only for `@hjam91/billing/hono` and `@hjam91/billing/react`.
21
+
22
+ ## 0.7.1 fixes
23
+
24
+ `plans()` can include the service's current `trial_days` and `trial_mode`, so apps
25
+ can display trial terms from their billing settings. These fields are optional
26
+ for compatibility with older services.
27
+
28
+ - Cached entitlement reads respect `maxStaleSeconds`, including ordinary reads without `fresh`.
29
+ - Feature checks clear cached access after authentication failures or a kill-switch denial, so later reads cannot restore the rejected access.
30
+ - Malformed successful entitlement/status responses become `BillingError(502, 'invalid_response')` and never replace a valid cached entitlement. Entitlement checks retain the configured outage policy.
31
+
32
+ No API migration is required. The default fail-open and kill-switch policies are unchanged.
33
+
34
+ ## Quick start (server)
35
+
36
+ The client holds your app's secret: **server-side only**.
37
+
38
+ ```ts
39
+ import { createBilling } from '@hjam91/billing';
40
+
41
+ const billing = createBilling({
42
+ baseUrl: process.env.BILLING_URL!, // e.g. https://billing.example.com
43
+ appId: process.env.BILLING_APP_ID!,
44
+ secret: process.env.BILLING_SECRET!,
45
+ });
46
+
47
+ // Is the account entitled at all? (cached; fails open on an outage)
48
+ const ent = await billing.getEntitlement('org:42');
49
+ if (!ent.active) return paymentRequired();
50
+
51
+ // Features and usage limits
52
+ const c = await billing.check('org:42', 'ai_images');
53
+ if (!c.allowed) return limitReached(c.balance);
54
+ await billing.track('org:42', 'ai_images', 1); // atomic, idempotent; queued for retry on an outage
55
+
56
+ // Stripe Checkout and the customer portal
57
+ const { url } = await billing.checkout({ accountId: 'org:42', plan: 'pro', successUrl, cancelUrl });
58
+ const portal = await billing.portal({ accountId: 'org:42', returnUrl });
59
+ ```
60
+
61
+ **Who may act for an account is your app's decision.** Check that the signed-in user may manage `accountId` before
62
+ calling `checkout`, `portal` or `setAutoRenew`.
63
+
64
+ ## Webhooks
65
+
66
+ The service POSTs a signed `entitlement.changed` (and, if you opt in, usage and lifecycle events) to your app.
67
+
68
+ ```ts
69
+ import { verifyBillingWebhook } from '@hjam91/billing';
70
+
71
+ const event = await verifyBillingWebhook(request, process.env.BILLING_WEBHOOK_SECRET!, { billing });
72
+ // throws BillingWebhookError (answer 400) on a bad or stale signature; `billing` drops the cached entitlement
73
+ ```
74
+
75
+ ## Hono
76
+
77
+ ```ts
78
+ import { requireEntitlement, requireFeature, billingRoutes } from '@hjam91/billing/hono';
79
+
80
+ app.use('/api/pro/*', requireEntitlement(billing, (c) => c.get('orgId'))); // 402 when not entitled
81
+ app.post('/api/images', requireFeature(billing, 'ai_images', (c) => c.get('orgId'))); // 402 when over the limit
82
+ app.route('/api/billing', billingRoutes(billing, {
83
+ getAccountId: (c) => c.get('orgId'),
84
+ canManage: (c, accountId) => isOrgAdmin(c.get('user'), accountId), // YOUR rule: e.g. org admins, not members
85
+ returnUrl: 'https://app.example.com/billing',
86
+ webhookSecret: process.env.BILLING_WEBHOOK_SECRET,
87
+ }));
88
+ ```
89
+
90
+ ## React
91
+
92
+ The browser talks to **your** backend (`billingRoutes` above), never to the billing service.
93
+
94
+ ```tsx
95
+ import { BillingCard, useBilling, useFeature, Gate } from '@hjam91/billing/react';
96
+
97
+ // A ready-made card (status, Subscribe, Manage, auto-renew) …
98
+ <BillingCard basePath="/api/billing" plan="pro" />
99
+
100
+ // … or your own UI
101
+ const { status, subscribe, openPortal } = useBilling({ basePath: '/api/billing' });
102
+ const { allowed } = useFeature('ai_images');
103
+ <Gate feature="ai_images" fallback={<Upgrade />}><ImageButton /></Gate>
104
+ ```
105
+
106
+ ## Caching on Workers
107
+
108
+ ```ts
109
+ import { kvStore } from '@hjam91/billing/kv';
110
+ const billing = createBilling({ baseUrl, appId, secret, cache: kvStore(env.BILLING_KV), waitUntil: ctx.waitUntil.bind(ctx) });
111
+ ```
112
+
113
+ ## Failure behaviour
114
+
115
+ | Situation | What checks answer |
116
+ |---|---|
117
+ | Service slow, down, 5xx, timeout | The last known answer (up to `maxStaleSeconds`, default 7 days); with nothing cached, **allowed** (`reason: 'unverified'`, `source: 'fail_open'`) and a warning. `failOpen: false` denies instead. |
118
+ | 401 / 403 / 404 (wrong secret, wrong app id, revoked key) | **Denied** (`source: 'error'`), logged at ERROR, `onError` called: a misconfiguration never means free access. `failOpenOnAuthError: true` restores allow. |
119
+ | The operator's kill switch: 403 `app_disabled`, 503 `service_locked_down` | `onKill: 'fail_open'` (default): the last known answer for a cached account, while an account with nothing cached follows `failOpen`; every check logs `!!! KILL SWITCH` at ERROR. `onKill: 'deny'`: deny and drop the cache. |
120
+
121
+ Actions (`checkout`, `portal`, `changePlan`, …) never fail open: they throw `BillingError`.
122
+
123
+ There is deliberately **no client-side kill or self-destruct**: anyone holding a copied secret can edit or skip a
124
+ client, so every kill (key revocation, app disable, lockdown) is enforced by the service, and the SDK only chooses what
125
+ to serve your users meanwhile.
126
+
127
+ ## Config as code
128
+
129
+ ```ts
130
+ // billing.config.ts
131
+ import { defineConfig } from '@hjam91/billing/config';
132
+ export default defineConfig({ features: [...], plans: { pro: { price: { amount: 1900, currency: 'usd', interval: 'month' } } } });
133
+ ```
134
+
135
+ ```bash
136
+ BILLING_URL=… BILLING_APP_ID=… BILLING_CONFIG_KEY=… npx billing-cli diff # exit 2 when the service drifted
137
+ npx billing-cli push
138
+ ```
139
+
140
+ `billing-cli` needs a scoped app key with `read` + `config` (and `pricing` to create prices). A `billing.config.ts`
141
+ needs Node >= 22.18; `.json` / `.mjs` configs work on any supported Node.
142
+
143
+ ## API reference
144
+
145
+ Full API documentation will be published at a public URL (placeholder: _API docs link_). Every export carries TSDoc in
146
+ its `.d.ts`.
@@ -0,0 +1,186 @@
1
+ /**
2
+ * createBillingAdmin() — an app's OWN server drives its support levers with a
3
+ * scoped app key (minted per app with read | support | refund | config | pricing
4
+ * scopes; since 0.4.0). SERVER-SIDE ONLY. It never needs the service-wide
5
+ * ADMIN_KEY, and the key reaches only this app's /admin/apps/:app routes:
6
+ * another app answers 404, a route outside the key's scopes 403 key_scope_denied.
7
+ *
8
+ * const admin = createBillingAdmin({ baseUrl, appId, key: env.BILLING_SUPPORT_KEY });
9
+ * await admin.setTrial('org:42', '2027-01-31T00:00:00Z'); // or null to clear the override
10
+ * const { invoices } = await admin.invoices('org:42');
11
+ * await admin.refund('org:42', { invoiceId: invoices[0].id, mode: 'prorated', cancel: 'now', access: 'keep' });
12
+ *
13
+ * Every method throws BillingError on failure (nothing here fails open: these
14
+ * are actions and owner reads, not entitlement checks).
15
+ */
16
+ import type { AccountStatus } from './types.js';
17
+ export interface BillingAdminOptions {
18
+ baseUrl: string;
19
+ appId: string;
20
+ /** The scoped app key (minted per app in the dashboard). Never ship it to a browser. */
21
+ key: string;
22
+ fetch?: typeof fetch;
23
+ /** Per-request timeout. Default 10000 ms (invoices and refunds call Stripe). */
24
+ timeoutMs?: number;
25
+ }
26
+ export interface InvoiceView {
27
+ id: string;
28
+ subscription_id: string;
29
+ stripe_subscription_id: string | null;
30
+ covers_account_id: string | null;
31
+ amount_paid: number;
32
+ currency: string;
33
+ period_start: string | null;
34
+ period_end: string | null;
35
+ paid_at: string | null;
36
+ charge_id: string | null;
37
+ amount_refunded: number;
38
+ /** What can still be refunded (minor units). */
39
+ refundable: number;
40
+ /** What a prorated refund would be right now (minor units). */
41
+ prorated_now: number;
42
+ unused_fraction: number;
43
+ hosted_invoice_url: string | null;
44
+ }
45
+ export interface RefundParams {
46
+ invoiceId: string;
47
+ /** full = what is left; prorated = the unused share of the period, now; amount = `amount` minor units (capped). */
48
+ mode: 'full' | 'prorated' | 'amount';
49
+ amount?: number;
50
+ /** What happens to the subscription AFTER the money moved. Default keep (or now with access revoke). */
51
+ cancel?: 'keep' | 'period_end' | 'now';
52
+ /** keep: access runs to the end of the paid period (then grace); revoke: access ends now. Default: the app's policy. */
53
+ access?: 'keep' | 'revoke';
54
+ note?: string;
55
+ }
56
+ export interface RefundResult {
57
+ ok: boolean;
58
+ refund_id: string | null;
59
+ status: string | null;
60
+ amount: number;
61
+ currency: string;
62
+ amount_formatted: string;
63
+ invoice_id: string;
64
+ subscription_id: string;
65
+ mode: string;
66
+ access: 'keep' | 'revoke';
67
+ cancel: string;
68
+ /** What actually happened to the subscription: 'failed' leaves the refund standing (see cancel_error). */
69
+ cancelled: 'keep' | 'period_end' | 'now' | 'failed';
70
+ cancel_error: string | null;
71
+ account: AccountStatus;
72
+ }
73
+ /** GET /admin/apps/:app/health (since 0.5.0). */
74
+ import type { BillingConfig, ConfigPushResult } from './config.js';
75
+ export interface AppHealth {
76
+ app_id: string;
77
+ ok: boolean;
78
+ checked_at: string;
79
+ checks: {
80
+ outbox_failed: number;
81
+ outbox_overdue: number;
82
+ flagged_subscriptions: number;
83
+ config_problems: number;
84
+ };
85
+ config: string[];
86
+ last_stripe_event_at: string | null;
87
+ last_delivery_at: string | null;
88
+ webhook_url_set: boolean;
89
+ }
90
+ export interface BillingAdmin {
91
+ /** The app's configuration (read). */
92
+ app(): Promise<Record<string, unknown>>;
93
+ /** Change policy (config scope): trial_days, grace_days, launched_at, prelaunch, trial_anchor, allow_promotion_codes, grace_on, refund_policy / revoke_on_refund, immediate_cancel_policy. */
94
+ updateApp(patch: Record<string, unknown>): Promise<Record<string, unknown>>;
95
+ /** Counts by state, MRR estimate, flags, webhook health (read). */
96
+ summary(): Promise<Record<string, unknown>>;
97
+ /** This app's own health: its outbox, flagged subscriptions and Stripe configuration (read; since 0.5.0). */
98
+ health(): Promise<AppHealth>;
99
+ /** One-time balance for an account (support scope; since 0.6.0): spent before anything expiring later. Audited. */
100
+ grant(accountId: string, g: {
101
+ featureId: string;
102
+ amount: number;
103
+ reason: string;
104
+ expiresAt?: string | Date | null;
105
+ }): Promise<{
106
+ grant: Record<string, unknown>;
107
+ }>;
108
+ /** Balances plus purchases, the latest usage events (ledger) and overage periods (read; since 0.6.0). */
109
+ balances(accountId: string): Promise<Record<string, unknown>>;
110
+ /** The app as a config document (read; since 0.7.0). */
111
+ pullConfig(): Promise<BillingConfig>;
112
+ /** Diff (dryRun) or apply a config document (config scope; since 0.7.0). A second identical push changes nothing. */
113
+ pushConfig(config: BillingConfig, opts?: {
114
+ dryRun?: boolean;
115
+ prune?: boolean;
116
+ }): Promise<ConfigPushResult>;
117
+ /** A Stripe product + price for one of the app's plans (config; since 0.7.0). */
118
+ createPrice(p: {
119
+ plan: string;
120
+ amount: number;
121
+ currency: string;
122
+ interval?: 'day' | 'week' | 'month' | 'year';
123
+ intervalCount?: number;
124
+ oneTime?: boolean;
125
+ }): Promise<{
126
+ plan: string;
127
+ price: string;
128
+ product: string;
129
+ lookup_key: string;
130
+ created: boolean;
131
+ }>;
132
+ /** A plan for ONE account: its own price, items and trial; never listed (config; since 0.7.0). */
133
+ customPlan(accountId: string, p: {
134
+ plan: string;
135
+ price: string | {
136
+ amount: number;
137
+ currency: string;
138
+ interval?: string;
139
+ };
140
+ items?: unknown[];
141
+ trialDays?: number;
142
+ }): Promise<Record<string, unknown>>;
143
+ /** A plan's versions with subscriber counts (read; since 0.7.0). */
144
+ planVersions(plan: string): Promise<Record<string, unknown>>;
145
+ /** Moves subscribers between plan versions in batches; dryRun counts (config; since 0.7.0). */
146
+ migratePlan(plan: string, p: {
147
+ fromVersion: number;
148
+ toVersion?: number;
149
+ when?: 'now' | 'period_end';
150
+ dryRun?: boolean;
151
+ limit?: number;
152
+ }): Promise<Record<string, unknown>>;
153
+ /** Accounts with their status and Stripe ids, filtered and paged (read). */
154
+ listAccounts(params?: {
155
+ q?: string;
156
+ state?: string;
157
+ plan?: string;
158
+ trial?: string;
159
+ coverage?: string;
160
+ limit?: number;
161
+ offset?: number;
162
+ }): Promise<Record<string, unknown>>;
163
+ /** One account as the owner sees it, with Stripe ids (read). */
164
+ account(accountId: string): Promise<AccountStatus & Record<string, unknown>>;
165
+ /** Set the trial override (Date/ISO) or clear it (null) — support scope. */
166
+ setTrial(accountId: string, endsAt: string | Date | null): Promise<AccountStatus>;
167
+ /** Set or clear exempt — support scope. Policy children inherit it. */
168
+ setExempt(accountId: string, exempt: boolean, reason?: string): Promise<AccountStatus>;
169
+ /** Cancel at period end / now, or resume, subscriptions the account owns — support scope. */
170
+ cancel(accountId: string, params: {
171
+ when: 'period_end' | 'now' | 'resume';
172
+ subscriptionId?: string;
173
+ coversAccountId?: string;
174
+ all?: boolean;
175
+ }): Promise<AccountStatus>;
176
+ /** Paid invoices of every subscription the account owns, with refundable / prorated_now (read). */
177
+ invoices(accountId: string, opts?: {
178
+ limit?: number;
179
+ }): Promise<{
180
+ account_id: string;
181
+ invoices: InvoiceView[];
182
+ }>;
183
+ /** Refund one paid invoice; the service computes the amount (refund scope). */
184
+ refund(accountId: string, params: RefundParams): Promise<RefundResult>;
185
+ }
186
+ export declare function createBillingAdmin(opts: BillingAdminOptions): BillingAdmin;
package/dist/admin.js ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * createBillingAdmin() — an app's OWN server drives its support levers with a
3
+ * scoped app key (minted per app with read | support | refund | config | pricing
4
+ * scopes; since 0.4.0). SERVER-SIDE ONLY. It never needs the service-wide
5
+ * ADMIN_KEY, and the key reaches only this app's /admin/apps/:app routes:
6
+ * another app answers 404, a route outside the key's scopes 403 key_scope_denied.
7
+ *
8
+ * const admin = createBillingAdmin({ baseUrl, appId, key: env.BILLING_SUPPORT_KEY });
9
+ * await admin.setTrial('org:42', '2027-01-31T00:00:00Z'); // or null to clear the override
10
+ * const { invoices } = await admin.invoices('org:42');
11
+ * await admin.refund('org:42', { invoiceId: invoices[0].id, mode: 'prorated', cancel: 'now', access: 'keep' });
12
+ *
13
+ * Every method throws BillingError on failure (nothing here fails open: these
14
+ * are actions and owner reads, not entitlement checks).
15
+ */
16
+ import { BillingError } from "./errors.js";
17
+ export function createBillingAdmin(opts) {
18
+ const base = `${opts.baseUrl.replace(/\/+$/, '')}/admin/apps/${encodeURIComponent(opts.appId)}`;
19
+ const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
20
+ const timeoutMs = opts.timeoutMs ?? 10_000;
21
+ const enc = encodeURIComponent;
22
+ async function call(method, path, body) {
23
+ let res;
24
+ try {
25
+ res = await doFetch(`${base}${path}`, {
26
+ method,
27
+ headers: { Authorization: `Bearer ${opts.key}`, ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
28
+ body: body !== undefined ? JSON.stringify(body) : undefined,
29
+ signal: AbortSignal.timeout(timeoutMs),
30
+ });
31
+ }
32
+ catch (err) {
33
+ const name = err?.name;
34
+ if (name === 'TimeoutError' || name === 'AbortError')
35
+ throw new BillingError(0, 'timeout', `Billing service did not answer within ${timeoutMs} ms`);
36
+ throw new BillingError(0, 'network_error', `Billing service unreachable: ${err?.message ?? err}`);
37
+ }
38
+ const data = (await res.json().catch(() => null));
39
+ if (!res.ok || data === null) {
40
+ throw new BillingError(res.status, data?.error ?? 'internal', data?.message ?? `Billing service answered HTTP ${res.status}`, (data ?? {}));
41
+ }
42
+ return data;
43
+ }
44
+ return {
45
+ app: async () => (await call('GET', '')).app,
46
+ updateApp: async (patch) => (await call('PATCH', '', patch)).app,
47
+ summary: () => call('GET', '/summary'),
48
+ health: () => call('GET', '/health'),
49
+ grant: (accountId, g) => call('POST', `/accounts/${enc(accountId)}/balances`, {
50
+ feature_id: g.featureId,
51
+ amount: g.amount,
52
+ reason: g.reason,
53
+ ...(g.expiresAt != null ? { expires_at: g.expiresAt instanceof Date ? g.expiresAt.toISOString() : g.expiresAt } : {}),
54
+ }),
55
+ balances: (accountId) => call('GET', `/accounts/${enc(accountId)}/balances`),
56
+ pullConfig: async () => (await call('GET', '/config')).config,
57
+ pushConfig: (config, o = {}) => call('POST', '/config', { config, ...(o.dryRun ? { dry_run: true } : {}), ...(o.prune ? { prune: true } : {}) }),
58
+ createPrice: (p) => call('POST', '/prices', { plan: p.plan, amount: p.amount, currency: p.currency, ...(p.interval ? { interval: p.interval } : {}), ...(p.intervalCount ? { interval_count: p.intervalCount } : {}), ...(p.oneTime ? { one_time: true } : {}) }),
59
+ customPlan: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/custom-plan`, { plan: p.plan, price: p.price, ...(p.items ? { items: p.items } : {}), ...(p.trialDays !== undefined ? { trial_days: p.trialDays } : {}) }),
60
+ planVersions: (plan) => call('GET', `/plans/${enc(plan)}/versions`),
61
+ migratePlan: (plan, p) => call('POST', `/plans/${enc(plan)}/migrate`, { from_version: p.fromVersion, ...(p.toVersion ? { to_version: p.toVersion } : {}), ...(p.when ? { when: p.when } : {}), ...(p.dryRun ? { dry_run: true } : {}), ...(p.limit ? { limit: p.limit } : {}) }),
62
+ listAccounts(params = {}) {
63
+ const q = new URLSearchParams();
64
+ for (const [k, v] of Object.entries(params))
65
+ if (v !== undefined && v !== '')
66
+ q.set(k, String(v));
67
+ return call('GET', `/accounts${q.size ? `?${q}` : ''}`);
68
+ },
69
+ account: (accountId) => call('GET', `/accounts/${enc(accountId)}`),
70
+ setTrial: (accountId, endsAt) => call('PUT', `/accounts/${enc(accountId)}/trial`, { ends_at: endsAt === null ? null : endsAt instanceof Date ? endsAt.toISOString() : endsAt }),
71
+ setExempt: (accountId, exempt, reason) => call('PUT', `/accounts/${enc(accountId)}/exempt`, { exempt, ...(reason ? { reason } : {}) }),
72
+ cancel: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/cancel`, {
73
+ when: p.when,
74
+ ...(p.subscriptionId ? { subscription_id: p.subscriptionId } : {}),
75
+ ...(p.coversAccountId ? { covers_account_id: p.coversAccountId } : {}),
76
+ ...(p.all ? { all: true } : {}),
77
+ }),
78
+ invoices: (accountId, o = {}) => call('GET', `/accounts/${enc(accountId)}/invoices${o.limit ? `?limit=${o.limit}` : ''}`),
79
+ refund: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/refunds`, {
80
+ invoice_id: p.invoiceId,
81
+ mode: p.mode,
82
+ ...(p.amount !== undefined ? { amount: p.amount } : {}),
83
+ ...(p.cancel ? { cancel: p.cancel } : {}),
84
+ ...(p.access ? { access: p.access } : {}),
85
+ ...(p.note ? { note: p.note } : {}),
86
+ }),
87
+ };
88
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Entitlement cache stores. A store keeps the LAST KNOWN answer per account
3
+ * for as long as it can: an old entry is not junk, it is what fail-open serves
4
+ * when the billing service is down. Freshness is decided by the client
5
+ * (`ttlSeconds`), not by the store.
6
+ */
7
+ import type { Entitlement } from './types.js';
8
+ export interface CacheEntry {
9
+ value: Entitlement;
10
+ /** Epoch ms when the value was fetched from the service. */
11
+ fetchedAt: number;
12
+ }
13
+ export interface CacheStore {
14
+ get(key: string): Promise<CacheEntry | undefined>;
15
+ set(key: string, entry: CacheEntry): Promise<void>;
16
+ delete(key: string): Promise<void>;
17
+ }
18
+ /**
19
+ * In-memory store (the default). Per isolate / per process: in a Worker each
20
+ * isolate has its own copy, which is fine for a cache but means a webhook
21
+ * invalidation only reaches the isolate that received it — use kvStore() when
22
+ * that matters.
23
+ */
24
+ export declare function memoryStore(opts?: {
25
+ maxEntries?: number;
26
+ }): CacheStore;
package/dist/cache.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Entitlement cache stores. A store keeps the LAST KNOWN answer per account
3
+ * for as long as it can: an old entry is not junk, it is what fail-open serves
4
+ * when the billing service is down. Freshness is decided by the client
5
+ * (`ttlSeconds`), not by the store.
6
+ */
7
+ /**
8
+ * In-memory store (the default). Per isolate / per process: in a Worker each
9
+ * isolate has its own copy, which is fine for a cache but means a webhook
10
+ * invalidation only reaches the isolate that received it — use kvStore() when
11
+ * that matters.
12
+ */
13
+ export function memoryStore(opts = {}) {
14
+ const max = opts.maxEntries ?? 10_000;
15
+ const map = new Map();
16
+ return {
17
+ async get(key) {
18
+ const v = map.get(key);
19
+ if (v) {
20
+ // Refresh recency: Map iteration order is insertion order.
21
+ map.delete(key);
22
+ map.set(key, v);
23
+ }
24
+ return v;
25
+ },
26
+ async set(key, entry) {
27
+ map.delete(key);
28
+ map.set(key, entry);
29
+ while (map.size > max)
30
+ map.delete(map.keys().next().value);
31
+ },
32
+ async delete(key) {
33
+ map.delete(key);
34
+ },
35
+ };
36
+ }
package/dist/cli.mjs ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * billing-cli — sync a billing config document with billing-kit (since 0.7.0).
4
+ *
5
+ * billing-cli pull [--out billing.config.json] write the app's config
6
+ * billing-cli diff [file] what push would change (a dry run; nothing is written)
7
+ * billing-cli push [file] [--prune] [--yes] apply it (asks first unless --yes)
8
+ *
9
+ * file: billing.config.ts | .mjs | .js (default export) or .json; default ./billing.config.ts, then .json.
10
+ * Environment: BILLING_URL, BILLING_APP_ID, and BILLING_CONFIG_KEY (a scoped app key with read + config scopes, + pricing to create prices)
11
+ * or BILLING_ADMIN_KEY. A billing.config.ts needs Node >= 22.18 (type stripping); .json / .mjs work on any supported Node.
12
+ * Exit codes: 0 ok, 1 error, 2 `diff` found changes (for CI: fail when the service drifted from the file).
13
+ */
14
+
15
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
16
+ import { resolve } from 'node:path';
17
+ import { pathToFileURL } from 'node:url';
18
+ import { createInterface } from 'node:readline/promises';
19
+ import { createBillingAdmin } from './admin.js';
20
+ import { formatChanges } from './config.js';
21
+
22
+ const [cmd, ...rest] = process.argv.slice(2);
23
+ const flags = new Set(rest.filter((a) => a.startsWith('--')));
24
+ const args = rest.filter((a) => !a.startsWith('--'));
25
+ const outIdx = rest.indexOf('--out');
26
+
27
+ function usage(code = 1) {
28
+ console.error('usage: billing-cli pull [--out file] | diff [file] | push [file] [--prune] [--yes]');
29
+ process.exit(code);
30
+ }
31
+
32
+ async function loadConfig(file) {
33
+ const path = resolve(file ?? (existsSync('billing.config.ts') ? 'billing.config.ts' : 'billing.config.json'));
34
+ if (!existsSync(path)) throw new Error(`no config file at ${path}`);
35
+ if (path.endsWith('.json')) return JSON.parse(readFileSync(path, 'utf8'));
36
+ const mod = await import(pathToFileURL(path).href);
37
+ return mod.default ?? mod.config;
38
+ }
39
+
40
+ async function main() {
41
+ if (!cmd || !['pull', 'diff', 'push'].includes(cmd)) usage();
42
+ const baseUrl = process.env.BILLING_URL;
43
+ const appId = process.env.BILLING_APP_ID;
44
+ const key = process.env.BILLING_CONFIG_KEY ?? process.env.BILLING_ADMIN_KEY;
45
+ if (!baseUrl || !appId || !key) throw new Error('set BILLING_URL, BILLING_APP_ID and BILLING_CONFIG_KEY (or BILLING_ADMIN_KEY)');
46
+ const admin = createBillingAdmin({ baseUrl, appId, key });
47
+ if (cmd === 'pull') {
48
+ const config = await admin.pullConfig();
49
+ const text = `${JSON.stringify(config, null, 2)}\n`;
50
+ if (outIdx >= 0 && rest[outIdx + 1]) {
51
+ writeFileSync(rest[outIdx + 1], text);
52
+ console.log(`wrote ${rest[outIdx + 1]}`);
53
+ } else process.stdout.write(text);
54
+ return 0;
55
+ }
56
+ const config = await loadConfig(args[0]);
57
+ const prune = flags.has('--prune');
58
+ const dry = await admin.pushConfig(config, { dryRun: true, prune });
59
+ console.log(formatChanges(dry.changes));
60
+ if (cmd === 'diff') return dry.changes.length ? 2 : 0;
61
+ if (!dry.changes.length) return 0;
62
+ if (!flags.has('--yes')) {
63
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
64
+ const answer = await rl.question(`Apply ${dry.changes.length} change(s) to ${appId}? [y/N] `);
65
+ rl.close();
66
+ if (!/^y(es)?$/i.test(answer.trim())) {
67
+ console.log('Nothing applied.');
68
+ return 0;
69
+ }
70
+ }
71
+ const r = await admin.pushConfig(config, { prune });
72
+ console.log(`Applied ${r.changes.length} change(s).`);
73
+ return 0;
74
+ }
75
+
76
+ main().then(
77
+ (code) => process.exit(code),
78
+ (err) => {
79
+ console.error(`billing-cli: ${err?.message ?? err}`);
80
+ process.exit(1);
81
+ },
82
+ );