import { env } from "cloudflare:workers";
import Stripe from "stripe";
import { HttpError } from "../errors";
import { PACKS, PRO_PRICE_CENTS } from "~/lib/pricing";
import type { PackDef } from "~/lib/pricing";
/** Stripe is optional: every billing path checks this first, and nothing else in the app requires Stripe. */
export function stripeEnabled(): boolean {
return Boolean(env.STRIPE_SECRET_KEY);
}
export function isTestKey(key: string | undefined): boolean {
return Boolean(key && /^(sk|rk)_test_/.test(key));
}
export function billingNotConfigured(): HttpError {
return new HttpError(501, "Billing is not configured on this instance");
}
let cached: { key: string; client: Stripe } | null = null;
const STRIPE_TIMEOUT_MS = 10_000;
/** The Stripe client, on the fetch HTTP client so it runs on Workers. Throws when Stripe is not configured. */
export function stripe(): Stripe {
const key = env.STRIPE_SECRET_KEY;
if (!key) throw billingNotConfigured();
if (cached?.key !== key) {
cached = {
key,
client: new Stripe(key, {
httpClient: Stripe.createFetchHttpClient(),
maxNetworkRetries: 2,
timeout: STRIPE_TIMEOUT_MS,
}),
};
}
return cached.client;
}
export const webCrypto = Stripe.createSubtleCryptoProvider();