@hjam91/billing 0.7.1 → 0.9.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.
- package/README.md +124 -0
- package/dist/admin.d.ts +150 -1
- package/dist/admin.js +39 -0
- package/dist/config.d.ts +4 -0
- package/dist/hono.d.ts +3 -1
- package/dist/hono.js +114 -4
- package/dist/index.d.ts +60 -2
- package/dist/index.js +139 -41
- package/dist/react.d.ts +98 -1
- package/dist/react.js +206 -5
- package/dist/types.d.ts +70 -3
- package/dist/usage.d.ts +39 -0
- package/dist/usage.js +65 -0
- package/package.json +7 -2
package/dist/types.d.ts
CHANGED
|
@@ -196,7 +196,7 @@ export interface UsageSettingsInput {
|
|
|
196
196
|
export interface UsageEvent {
|
|
197
197
|
id: string;
|
|
198
198
|
/** 0.6 usage events, and (since 0.7.0, only the types the app chose in event_types) lifecycle events. */
|
|
199
|
-
type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed';
|
|
199
|
+
type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed' | 'invoice.payment_action_required';
|
|
200
200
|
created: string;
|
|
201
201
|
app_id: string;
|
|
202
202
|
account_id: string;
|
|
@@ -206,6 +206,8 @@ export interface UsageEvent {
|
|
|
206
206
|
export type BillingEvent = EntitlementChangedEvent | UsageEvent;
|
|
207
207
|
/** POST /v1/subscriptions/change (since 0.7.0): what happened to the plan. */
|
|
208
208
|
export interface PlanChange {
|
|
209
|
+
quantity?: number;
|
|
210
|
+
from_quantity?: number;
|
|
209
211
|
status: 'applied' | 'scheduled' | 'requires_action';
|
|
210
212
|
plan: string;
|
|
211
213
|
from_plan: string | null;
|
|
@@ -217,6 +219,8 @@ export interface PlanChange {
|
|
|
217
219
|
}
|
|
218
220
|
/** POST /v1/subscriptions/change/preview (since 0.7.0). Amounts in minor units. */
|
|
219
221
|
export interface ChangePreview {
|
|
222
|
+
quantity?: number;
|
|
223
|
+
from_quantity?: number;
|
|
220
224
|
plan: string;
|
|
221
225
|
from_plan: string | null;
|
|
222
226
|
direction: 'upgrade' | 'downgrade' | 'interval';
|
|
@@ -252,6 +256,57 @@ export interface PublicPlan {
|
|
|
252
256
|
expires_in_days?: number;
|
|
253
257
|
}>;
|
|
254
258
|
}
|
|
259
|
+
/** A discount as an app shows it (since 0.8.0). Amounts in minor units. */
|
|
260
|
+
export interface DiscountView {
|
|
261
|
+
id: string;
|
|
262
|
+
/** The code (discount codes only; an offer has none). */
|
|
263
|
+
code?: string;
|
|
264
|
+
percent_off: number | null;
|
|
265
|
+
amount_off: number | null;
|
|
266
|
+
currency: string | null;
|
|
267
|
+
duration: 'once' | 'repeating' | 'forever';
|
|
268
|
+
duration_in_months: number | null;
|
|
269
|
+
/** Ready to show: "50% off for 3 months", "$5.00 off once", "20% off forever". */
|
|
270
|
+
label: string;
|
|
271
|
+
}
|
|
272
|
+
/** One plan a discount applies to, with the discounted first paid period (since 0.8.0). Minor units. */
|
|
273
|
+
export interface DiscountPlanPreview {
|
|
274
|
+
plan: string;
|
|
275
|
+
amount: number;
|
|
276
|
+
currency: string;
|
|
277
|
+
interval: string | null;
|
|
278
|
+
interval_count: number | null;
|
|
279
|
+
/** The first paid period with the discount; never below 0. */
|
|
280
|
+
first_amount: number;
|
|
281
|
+
}
|
|
282
|
+
/** Why a code cannot be used (checkDiscount, and `details.reason` of a 409 discount_invalid at checkout). Since 0.8.0. */
|
|
283
|
+
export type DiscountReason = 'unknown' | 'inactive' | 'expired' | 'used_up' | 'not_first_time' | 'plan_not_eligible';
|
|
284
|
+
/** POST /v1/discounts/check (since 0.8.0). `code` is the normalized (upper-case) code. */
|
|
285
|
+
export type DiscountCheck = {
|
|
286
|
+
valid: true;
|
|
287
|
+
code: string;
|
|
288
|
+
discount: DiscountView;
|
|
289
|
+
plans: DiscountPlanPreview[];
|
|
290
|
+
} | {
|
|
291
|
+
valid: false;
|
|
292
|
+
code: string;
|
|
293
|
+
reason: DiscountReason;
|
|
294
|
+
};
|
|
295
|
+
/** Who an automatic offer is for (since 0.8.0). */
|
|
296
|
+
export type OfferAudience = 'trial_ended' | 'lapsed' | 'canceling';
|
|
297
|
+
/** An offer the account may take now (GET /v1/accounts/:id/offers, since 0.8.0). */
|
|
298
|
+
export interface OfferView {
|
|
299
|
+
id: string;
|
|
300
|
+
name: string;
|
|
301
|
+
audience: OfferAudience;
|
|
302
|
+
/** The owner's short marketing line (≤ 120 characters), or null. */
|
|
303
|
+
headline: string | null;
|
|
304
|
+
discount: DiscountView;
|
|
305
|
+
/** The plans it applies to with previews (a 'canceling' offer applies to the subscription the account has). */
|
|
306
|
+
plans: DiscountPlanPreview[];
|
|
307
|
+
/** When the offer stops being shown (ISO), null = no end. */
|
|
308
|
+
ends_at: string | null;
|
|
309
|
+
}
|
|
255
310
|
/**
|
|
256
311
|
* Where an answer came from:
|
|
257
312
|
* - live: fetched from the service just now
|
|
@@ -268,6 +323,16 @@ export interface EntitlementResult extends Entitlement {
|
|
|
268
323
|
error?: string;
|
|
269
324
|
}
|
|
270
325
|
export interface SubscriptionView {
|
|
326
|
+
scheduled_change?: {
|
|
327
|
+
plan: string;
|
|
328
|
+
quantity: number;
|
|
329
|
+
effective_at: string;
|
|
330
|
+
};
|
|
331
|
+
invoice?: {
|
|
332
|
+
id: string;
|
|
333
|
+
due_at: string | null;
|
|
334
|
+
hosted_invoice_url: string | null;
|
|
335
|
+
};
|
|
271
336
|
id: string;
|
|
272
337
|
plan: string | null;
|
|
273
338
|
quantity: number;
|
|
@@ -388,6 +453,8 @@ export interface EntitlementChangedEvent {
|
|
|
388
453
|
/** Error codes the API returns (stable; branch on these, not on messages). */
|
|
389
454
|
export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
|
|
390
455
|
/** 0.7 security: the service is locked down (only the owner key works). */
|
|
391
|
-
| 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
|
|
456
|
+
| 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
|
|
392
457
|
/** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
|
|
393
|
-
| 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
|
|
458
|
+
| 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
|
|
459
|
+
/** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
|
|
460
|
+
| 'discount_invalid' | 'offer_not_eligible' | 'code_exists' | 'discount_not_found' | 'offer_not_found' | 'stripe_error' | 'internal' | 'network_error' | 'timeout' | (string & {});
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Pluggable usage delivery storage. Store operations must be durable before resolving. */
|
|
2
|
+
export interface UsageRecord {
|
|
3
|
+
scope: string;
|
|
4
|
+
id: string;
|
|
5
|
+
body: Record<string, unknown>;
|
|
6
|
+
attempts: number;
|
|
7
|
+
createdAt: number;
|
|
8
|
+
status: 'pending' | 'rejected';
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface UsageStatus {
|
|
12
|
+
pending: number;
|
|
13
|
+
rejected: number;
|
|
14
|
+
oldestPendingAt: number | null;
|
|
15
|
+
}
|
|
16
|
+
export interface UsageStore {
|
|
17
|
+
put(record: UsageRecord): Promise<void>;
|
|
18
|
+
remove(scope: string, id: string): Promise<void>;
|
|
19
|
+
list(scope: string, status: UsageRecord['status'], limit: number): Promise<UsageRecord[]>;
|
|
20
|
+
status(scope: string): Promise<UsageStatus>;
|
|
21
|
+
}
|
|
22
|
+
/** Process-local default. A persistent implementation can be shared by successive SDK instances. */
|
|
23
|
+
export declare function memoryUsageStore(maxRejected?: number): UsageStore;
|
|
24
|
+
/** Apply this schema in the consuming app's database before using d1UsageStore. */
|
|
25
|
+
export declare const USAGE_QUEUE_SCHEMA = "CREATE TABLE IF NOT EXISTS billing_usage_queue (\n scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL,\n created_at INTEGER NOT NULL, status TEXT NOT NULL, error TEXT, PRIMARY KEY (scope, id)\n);\nCREATE INDEX IF NOT EXISTS billing_usage_pending ON billing_usage_queue (scope, status, created_at, id);";
|
|
26
|
+
export interface UsageDatabase {
|
|
27
|
+
prepare(sql: string): {
|
|
28
|
+
bind(...args: (string | number | null)[]): {
|
|
29
|
+
run(): Promise<unknown>;
|
|
30
|
+
all<T>(): Promise<{
|
|
31
|
+
results: T[];
|
|
32
|
+
}>;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Cloudflare D1 adapter, without importing a platform package. Event keys survive process restarts. */
|
|
37
|
+
export declare function d1UsageStore(db: UsageDatabase): UsageStore;
|
|
38
|
+
/** A per-event failure inside a successful HTTP batch response. */
|
|
39
|
+
export declare function usageOutcome(result: unknown): 'sent' | 'retry' | 'rejected';
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Process-local default. A persistent implementation can be shared by successive SDK instances. */
|
|
2
|
+
export function memoryUsageStore(maxRejected = 1000) {
|
|
3
|
+
const rows = new Map();
|
|
4
|
+
const key = (scope, id) => JSON.stringify([scope, id]);
|
|
5
|
+
return {
|
|
6
|
+
async put(row) {
|
|
7
|
+
rows.set(key(row.scope, row.id), structuredClone(row));
|
|
8
|
+
const rejected = [...rows.values()].filter((r) => r.scope === row.scope && r.status === 'rejected');
|
|
9
|
+
for (const r of rejected.slice(0, Math.max(0, rejected.length - maxRejected)))
|
|
10
|
+
rows.delete(key(r.scope, r.id));
|
|
11
|
+
},
|
|
12
|
+
async remove(scope, id) { rows.delete(key(scope, id)); },
|
|
13
|
+
async list(scope, status, limit) {
|
|
14
|
+
return structuredClone([...rows.values()].filter((r) => r.scope === scope && r.status === status)
|
|
15
|
+
.sort((a, b) => a.createdAt - b.createdAt).slice(0, limit));
|
|
16
|
+
},
|
|
17
|
+
async status(scope) {
|
|
18
|
+
const all = [...rows.values()].filter((r) => r.scope === scope);
|
|
19
|
+
const pending = all.filter((r) => r.status === 'pending');
|
|
20
|
+
return { pending: pending.length, rejected: all.length - pending.length, oldestPendingAt: pending.length ? Math.min(...pending.map((r) => r.createdAt)) : null };
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Apply this schema in the consuming app's database before using d1UsageStore. */
|
|
25
|
+
export const USAGE_QUEUE_SCHEMA = `CREATE TABLE IF NOT EXISTS billing_usage_queue (
|
|
26
|
+
scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL,
|
|
27
|
+
created_at INTEGER NOT NULL, status TEXT NOT NULL, error TEXT, PRIMARY KEY (scope, id)
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS billing_usage_pending ON billing_usage_queue (scope, status, created_at, id);`;
|
|
30
|
+
/** Cloudflare D1 adapter, without importing a platform package. Event keys survive process restarts. */
|
|
31
|
+
export function d1UsageStore(db) {
|
|
32
|
+
return {
|
|
33
|
+
async put(r) {
|
|
34
|
+
await db.prepare(`INSERT INTO billing_usage_queue (scope,id,body,attempts,created_at,status,error) VALUES (?,?,?,?,?,?,?)
|
|
35
|
+
ON CONFLICT(scope,id) DO UPDATE SET body=excluded.body,attempts=excluded.attempts,status=excluded.status,error=excluded.error`)
|
|
36
|
+
.bind(r.scope, r.id, JSON.stringify(r.body), r.attempts, r.createdAt, r.status, r.error ?? null).run();
|
|
37
|
+
},
|
|
38
|
+
async remove(scope, id) { await db.prepare('DELETE FROM billing_usage_queue WHERE scope=? AND id=?').bind(scope, id).run(); },
|
|
39
|
+
async list(scope, status, limit) {
|
|
40
|
+
const r = await db.prepare('SELECT * FROM billing_usage_queue WHERE scope=? AND status=? ORDER BY created_at,id LIMIT ?').bind(scope, status, limit)
|
|
41
|
+
.all();
|
|
42
|
+
return r.results.map((x) => ({ scope: x.scope, id: x.id, body: JSON.parse(x.body), attempts: x.attempts, createdAt: x.created_at, status: x.status, ...(x.error ? { error: x.error } : {}) }));
|
|
43
|
+
},
|
|
44
|
+
async status(scope) {
|
|
45
|
+
const r = await db.prepare(`SELECT SUM(status='pending') AS pending,SUM(status='rejected') AS rejected,
|
|
46
|
+
MIN(CASE WHEN status='pending' THEN created_at END) AS oldestPendingAt FROM billing_usage_queue WHERE scope=?`).bind(scope)
|
|
47
|
+
.all();
|
|
48
|
+
const row = r.results[0];
|
|
49
|
+
return { pending: row?.pending ?? 0, rejected: row?.rejected ?? 0, oldestPendingAt: row?.oldestPendingAt ?? null };
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** A per-event failure inside a successful HTTP batch response. */
|
|
54
|
+
export function usageOutcome(result) {
|
|
55
|
+
if (!result || typeof result !== 'object')
|
|
56
|
+
return 'retry';
|
|
57
|
+
const r = result;
|
|
58
|
+
if (r.applied === true || r.replayed === true)
|
|
59
|
+
return 'sent';
|
|
60
|
+
if (typeof r.error === 'string')
|
|
61
|
+
return ['internal', 'storage_unavailable', 'stripe_error', 'network_error', 'timeout', 'rate_limited', 'service_locked_down', 'app_disabled'].includes(r.error) ? 'retry' : 'rejected';
|
|
62
|
+
if (r.allowed === false)
|
|
63
|
+
return 'rejected';
|
|
64
|
+
return 'retry';
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hjam91/billing",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Zero-dependency client for a billing-kit service: cached, fail-open entitlement and feature checks, usage tracking, Stripe Checkout / portal, signed webhook verification, a Hono gate and an optional React billing card.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"billing",
|
|
@@ -48,7 +48,12 @@
|
|
|
48
48
|
"import": "./dist/config.js",
|
|
49
49
|
"default": "./dist/config.js"
|
|
50
50
|
},
|
|
51
|
-
"./package.json": "./package.json"
|
|
51
|
+
"./package.json": "./package.json",
|
|
52
|
+
"./usage": {
|
|
53
|
+
"types": "./dist/usage.d.ts",
|
|
54
|
+
"import": "./dist/usage.js",
|
|
55
|
+
"default": "./dist/usage.js"
|
|
56
|
+
}
|
|
52
57
|
},
|
|
53
58
|
"bin": {
|
|
54
59
|
"billing-cli": "dist/cli.mjs"
|