@absolutejs/billing 0.5.0 → 0.7.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.
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/prepaid.ts", "../src/prepaidPostgres.ts", "../src/creditWork.ts"],
4
+ "sourcesContent": [
5
+ "/** Service-credit accounting. Host authorization and payment verification happen\n * before these commands. Every command and its receipt commit in one transaction. */\nexport type CreditAccount = {\n periodId: string;\n periodEnd: string | null;\n periodAllowance: number;\n periodRemaining: number;\n purchasedRemaining: number;\n promotionalRemaining: number;\n debt: number;\n reserved: number;\n consumed: number;\n};\nexport type CreditAllocation = {\n period: number;\n purchased: number;\n promotional: number;\n};\nexport type CreditReservation = {\n id: string;\n periodId: string;\n allocation: CreditAllocation;\n status: \"reserved\" | \"settled\" | \"released\";\n charged: number | null;\n};\nexport type CreditCommand =\n | { kind: \"grant\"; bucket: \"purchased\" | \"promotional\"; credits: number }\n | { kind: \"reverse\"; bucket: \"purchased\" | \"promotional\"; credits: number }\n | {\n kind: \"period\";\n periodId: string;\n periodEnd: string | null;\n allowance: number;\n }\n | { kind: \"reserve\"; reservationId: string; credits: number }\n | { kind: \"settle\"; reservationId: string; credits: number }\n | { kind: \"release\"; reservationId: string }\n | { kind: \"debit\"; credits: number; allowDebt?: boolean; reference?: string };\nexport type CreditReceipt = {\n command: CreditCommand;\n account: CreditAccount;\n reservation?: CreditReservation;\n};\nexport type CreditTransaction = {\n account: CreditAccount;\n receipt: (operationId: string) => Promise<CreditReceipt | null>;\n reservation: (id: string) => Promise<CreditReservation | null>;\n save: (operationId: string, receipt: CreditReceipt) => Promise<void>;\n};\nexport type CreditAccountStore = {\n /** Persist seed once. Never overwrite an existing account. */\n initialize: (accountId: string, seed: CreditAccount) => Promise<void>;\n read: (accountId: string) => Promise<CreditAccount | null>;\n /** Lock one account, serialize its commands across processes, and roll back\n * account, reservation and receipt together if the callback fails. */\n transaction: <T>(\n accountId: string,\n run: (tx: CreditTransaction) => Promise<T>,\n ) => Promise<T>;\n};\nconst integer = (value: number) => {\n if (!Number.isSafeInteger(value) || value < 0)\n throw new Error(\"Credits must be nonnegative safe integers\");\n return value;\n};\nconst periodIdentity = (value: string) => {\n if (\n !Number.isFinite(Date.parse(value)) ||\n new Date(value).toISOString() !== value\n )\n throw new Error(\"Credit period ID must be an ISO UTC start timestamp\");\n return value;\n};\nconst identity = (value: string) => {\n if (!value || value.length > 256)\n throw new Error(\"Credit identity is invalid\");\n return value;\n};\nexport const validateCreditAccount = (account: CreditAccount) => {\n periodIdentity(account.periodId);\n if (\n account.periodEnd !== null &&\n periodIdentity(account.periodEnd) <= account.periodId\n )\n throw new Error(\"Credit period end must follow its start\");\n for (const key of [\n \"periodAllowance\",\n \"periodRemaining\",\n \"purchasedRemaining\",\n \"promotionalRemaining\",\n \"debt\",\n \"reserved\",\n \"consumed\",\n ] as const)\n integer(account[key]);\n integer(\n account.periodRemaining +\n account.purchasedRemaining +\n account.promotionalRemaining,\n );\n if (account.periodRemaining > account.periodAllowance)\n throw new Error(\"Period balance exceeds its allowance\");\n};\nexport const availableCredits = (account: CreditAccount) =>\n Math.max(\n 0,\n account.periodRemaining +\n account.purchasedRemaining +\n account.promotionalRemaining -\n account.debt,\n );\n\n/** Preserve the currently observable legacy balance without inventing purchase\n * provenance. Historical mixed bonus grants remain promotional carryover. */\nexport const migrateLegacyCreditAccount = (input: {\n periodId: string;\n periodEnd?: string | null;\n periodAllowance: number;\n bonusCredits: number;\n consumed: number;\n}): CreditAccount => {\n integer(input.periodAllowance);\n integer(input.consumed);\n if (!Number.isSafeInteger(input.bonusCredits))\n throw new Error(\"Invalid legacy bonus credits\");\n const account: CreditAccount = {\n periodId: input.periodId,\n periodEnd: input.periodEnd ?? null,\n periodAllowance: input.periodAllowance,\n periodRemaining: Math.max(0, input.periodAllowance - input.consumed),\n purchasedRemaining: 0,\n promotionalRemaining: Math.max(\n 0,\n input.bonusCredits - Math.max(0, input.consumed - input.periodAllowance),\n ),\n debt:\n Math.max(0, -input.bonusCredits) +\n Math.max(\n 0,\n input.consumed -\n input.periodAllowance -\n Math.max(0, input.bonusCredits),\n ),\n reserved: 0,\n consumed: input.consumed,\n };\n validateCreditAccount(account);\n return account;\n};\nconst allocationTotal = (value: CreditAllocation) =>\n value.period + value.promotional + value.purchased;\nconst take = (account: CreditAccount, credits: number): CreditAllocation => {\n // A reversal liability consumes existing available credits exactly once.\n let owed = account.debt;\n for (const key of [\n \"periodRemaining\",\n \"promotionalRemaining\",\n \"purchasedRemaining\",\n ] as const) {\n const covered = Math.min(account[key], owed);\n account[key] -= covered;\n owed -= covered;\n }\n account.debt = owed;\n const period = Math.min(account.periodRemaining, credits);\n const promotional = Math.min(account.promotionalRemaining, credits - period);\n const purchased = Math.min(\n account.purchasedRemaining,\n credits - period - promotional,\n );\n account.periodRemaining -= period;\n account.promotionalRemaining -= promotional;\n account.purchasedRemaining -= purchased;\n return { period, promotional, purchased };\n};\nconst grant = (\n account: CreditAccount,\n key: \"periodRemaining\" | \"purchasedRemaining\" | \"promotionalRemaining\",\n credits: number,\n) => {\n const covered = Math.min(account.debt, credits);\n account.debt -= covered;\n account[key] = integer(account[key] + credits - covered);\n};\nconst normalize = (command: CreditCommand): CreditCommand => {\n switch (command.kind) {\n case \"grant\":\n case \"reverse\":\n if (command.bucket !== \"purchased\" && command.bucket !== \"promotional\")\n throw new Error(\"Invalid credit bucket\");\n return {\n kind: command.kind,\n bucket: command.bucket,\n credits: integer(command.credits),\n };\n case \"period\":\n return {\n kind: command.kind,\n periodId: periodIdentity(command.periodId),\n periodEnd:\n command.periodEnd === null ? null : periodIdentity(command.periodEnd),\n allowance: integer(command.allowance),\n };\n case \"reserve\":\n case \"settle\":\n return {\n kind: command.kind,\n reservationId: identity(command.reservationId),\n credits: integer(command.credits),\n };\n case \"release\":\n return {\n kind: command.kind,\n reservationId: identity(command.reservationId),\n };\n case \"debit\":\n return {\n kind: command.kind,\n credits: integer(command.credits),\n allowDebt: command.allowDebt === true,\n ...(command.reference === undefined\n ? {}\n : { reference: identity(command.reference) }),\n };\n default:\n throw new Error(\"Invalid credit command\");\n }\n};\nexport const createCreditAccountLedger = (store: CreditAccountStore) => ({\n initialize: async (accountId: string, seed: CreditAccount) => {\n identity(accountId);\n validateCreditAccount(seed);\n await store.initialize(accountId, seed);\n },\n receipt: (accountId: string, operationId: string) =>\n store.transaction(identity(accountId), (tx) =>\n tx.receipt(identity(operationId)),\n ),\n balance: (accountId: string) => store.read(identity(accountId)),\n execute: async (\n accountId: string,\n operationId: string,\n input: CreditCommand,\n ): Promise<CreditReceipt> => {\n identity(accountId);\n identity(operationId);\n const command = normalize(input);\n return store.transaction(accountId, async (tx) => {\n const previous = await tx.receipt(operationId);\n if (previous) {\n if (\n JSON.stringify(normalize(previous.command)) !==\n JSON.stringify(command)\n )\n throw new Error(\"Credit operation ID reused with different input\");\n return previous;\n }\n const account = { ...tx.account };\n validateCreditAccount(account);\n let reservation: CreditReservation | undefined;\n switch (command.kind) {\n case \"grant\":\n grant(\n account,\n command.bucket === \"purchased\"\n ? \"purchasedRemaining\"\n : \"promotionalRemaining\",\n command.credits,\n );\n break;\n case \"reverse\": {\n const key =\n command.bucket === \"purchased\"\n ? \"purchasedRemaining\"\n : \"promotionalRemaining\";\n const covered = Math.min(account[key], command.credits);\n account[key] -= covered;\n account.debt += command.credits - covered;\n break;\n }\n case \"period\":\n if (command.periodId < account.periodId)\n throw new Error(\"Credit period cannot move backwards\");\n if (command.periodId === account.periodId) {\n // Upgrades add only the increase. Downgrades take effect next period.\n const increase = Math.max(\n 0,\n command.allowance - account.periodAllowance,\n );\n if (account.periodEnd === null)\n account.periodEnd = command.periodEnd;\n account.periodAllowance += increase;\n grant(account, \"periodRemaining\", increase);\n } else {\n account.periodId = command.periodId;\n account.periodEnd = command.periodEnd;\n account.periodAllowance = command.allowance;\n account.periodRemaining = 0;\n account.consumed = 0;\n grant(account, \"periodRemaining\", command.allowance);\n }\n break;\n case \"debit\": {\n if (!command.allowDebt && availableCredits(account) < command.credits)\n throw new Error(\"Insufficient credits\");\n const used = allocationTotal(take(account, command.credits));\n account.debt += command.credits - used;\n account.consumed += command.credits;\n break;\n }\n case \"reserve\":\n if (command.credits === 0)\n throw new Error(\"Reservation must be positive\");\n if (await tx.reservation(command.reservationId))\n throw new Error(\"Credit reservation already exists\");\n if (availableCredits(account) < command.credits)\n throw new Error(\"Insufficient credits\");\n reservation = {\n id: command.reservationId,\n periodId: account.periodId,\n allocation: take(account, command.credits),\n status: \"reserved\",\n charged: null,\n };\n account.reserved += command.credits;\n break;\n case \"settle\":\n case \"release\": {\n const held = await tx.reservation(command.reservationId);\n if (!held || held.status !== \"reserved\")\n throw new Error(\"Credit reservation is not active\");\n const total = allocationTotal(held.allocation);\n const charged = command.kind === \"settle\" ? command.credits : 0;\n if (charged > total)\n throw new Error(\"Charge exceeds reserved credits\");\n let refund = total - charged;\n for (const [bucket, key] of [\n [\"purchased\", \"purchasedRemaining\"],\n [\"promotional\", \"promotionalRemaining\"],\n [\"period\", \"periodRemaining\"],\n ] as const) {\n const restored = Math.min(held.allocation[bucket], refund);\n refund -= restored;\n if (bucket !== \"period\" || held.periodId === account.periodId)\n grant(account, key, restored);\n }\n account.reserved -= total;\n if (held.periodId === account.periodId) account.consumed += charged;\n reservation = {\n ...held,\n status: command.kind === \"settle\" ? \"settled\" : \"released\",\n charged,\n };\n break;\n }\n }\n validateCreditAccount(account);\n const receipt: CreditReceipt = {\n command,\n account,\n ...(reservation ? { reservation } : {}),\n };\n await tx.save(operationId, receipt);\n return receipt;\n });\n },\n});\n\n/** Portal access and funded MCP access are independent. Period-only free\n * allowances do not silently unlock prepaid work; carryover grants may. */\nexport const creditEntitlements = (input: {\n subscribed: boolean;\n prepaidEnabled: boolean;\n account: CreditAccount | null;\n}) => {\n const funded =\n input.prepaidEnabled &&\n input.account !== null &&\n input.account.purchasedRemaining + input.account.promotionalRemaining > 0 &&\n availableCredits(input.account) > 0;\n return {\n portal: input.subscribed,\n mcp: input.subscribed\n ? (\"member\" as const)\n : funded\n ? (\"prepaid\" as const)\n : (\"free\" as const),\n };\n};\n",
6
+ "import {\n validateCreditAccount,\n type CreditAccount,\n type CreditAccountStore,\n type CreditReceipt,\n type CreditReservation,\n} from \"./prepaid\";\nexport type CreditSql = {\n query: (\n query: string,\n parameters: readonly unknown[],\n ) => Promise<{ rows: Record<string, unknown>[] }>;\n};\nexport type CreditSqlClient = CreditSql & {\n transaction: <T>(run: (sql: CreditSql) => Promise<T>) => Promise<T>;\n};\nconst namespace = (value: string) => {\n if (!/^[a-z][a-z0-9_]*$/.test(value))\n throw new Error(\"Invalid credit schema name\");\n return value;\n};\nexport const creditAccountPostgresSchemaSql = (schema = \"billing_credits\") => {\n const n = namespace(schema);\n return `CREATE SCHEMA IF NOT EXISTS ${n};\nCREATE TABLE IF NOT EXISTS ${n}.accounts (\n account_id text PRIMARY KEY, state jsonb NOT NULL, initial_state jsonb NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE TABLE IF NOT EXISTS ${n}.operations (\n account_id text NOT NULL REFERENCES ${n}.accounts(account_id), operation_id text NOT NULL,\n receipt jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (account_id, operation_id)\n);\nCREATE TABLE IF NOT EXISTS ${n}.reservations (\n account_id text NOT NULL REFERENCES ${n}.accounts(account_id), reservation_id text NOT NULL,\n state jsonb NOT NULL, updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (account_id, reservation_id)\n);`;\n};\nexport const createPostgresCreditAccountStore = (\n client: CreditSqlClient,\n schema = \"billing_credits\",\n): CreditAccountStore => {\n const n = namespace(schema);\n const read = async (sql: CreditSql, accountId: string, lock = false) => {\n const { rows } = await sql.query(\n `SELECT state FROM ${n}.accounts WHERE account_id = $1${lock ? \" FOR UPDATE\" : \"\"}`,\n [accountId],\n );\n if (!rows[0]) return null;\n const state = rows[0].state as CreditAccount;\n validateCreditAccount(state);\n return state;\n };\n return {\n initialize: async (accountId, seed) => {\n validateCreditAccount(seed);\n await client.query(\n `INSERT INTO ${n}.accounts (account_id, state, initial_state) VALUES ($1, $2::jsonb, $2::jsonb) ON CONFLICT DO NOTHING`,\n [accountId, JSON.stringify(seed)],\n );\n },\n read: (accountId) => read(client, accountId),\n transaction: (accountId, run) =>\n client.transaction(async (sql) => {\n const account = await read(sql, accountId, true);\n if (!account) throw new Error(\"Credit account is not initialized\");\n return run({\n account,\n receipt: async (operationId) => {\n const { rows } = await sql.query(\n `SELECT receipt FROM ${n}.operations WHERE account_id = $1 AND operation_id = $2`,\n [accountId, operationId],\n );\n return (rows[0]?.receipt as CreditReceipt | undefined) ?? null;\n },\n reservation: async (id) => {\n const { rows } = await sql.query(\n `SELECT state FROM ${n}.reservations WHERE account_id = $1 AND reservation_id = $2`,\n [accountId, id],\n );\n return (rows[0]?.state as CreditReservation | undefined) ?? null;\n },\n save: async (operationId, receipt) => {\n await sql.query(\n `UPDATE ${n}.accounts SET state = $2::jsonb, updated_at = now() WHERE account_id = $1`,\n [accountId, JSON.stringify(receipt.account)],\n );\n if (receipt.reservation)\n await sql.query(\n `INSERT INTO ${n}.reservations (account_id, reservation_id, state) VALUES ($1, $2, $3::jsonb) ON CONFLICT (account_id, reservation_id) DO UPDATE SET state = EXCLUDED.state, updated_at = now()`,\n [\n accountId,\n receipt.reservation.id,\n JSON.stringify(receipt.reservation),\n ],\n );\n await sql.query(\n `INSERT INTO ${n}.operations (account_id, operation_id, receipt) VALUES ($1, $2, $3::jsonb)`,\n [accountId, operationId, JSON.stringify(receipt)],\n );\n },\n });\n }),\n };\n};\n",
7
+ "import { createCreditAccountLedger } from \"./prepaid\";\nimport {\n createPostgresCreditAccountStore,\n type CreditSql,\n type CreditSqlClient,\n} from \"./prepaidPostgres\";\nexport type CreditWork = {\n request: string;\n budget: number;\n charged: number;\n absorbed: number;\n status: \"running\" | \"completed\" | \"failed\";\n result: string | null;\n};\nconst namespace = (value: string) => {\n if (!/^[a-z][a-z0-9_]*$/.test(value))\n throw new Error(\"Invalid credit schema name\");\n return value;\n};\nconst id = (value: string) => {\n if (!value || value.length > 128) throw new Error(\"Invalid credit work ID\");\n};\nconst integer = (value: number) => {\n if (!Number.isSafeInteger(value) || value < 0)\n throw new Error(\"Invalid credit work amount\");\n};\nexport const creditWorkPostgresSchemaSql = (schema = \"billing_credits\") => {\n const n = namespace(schema);\n return `CREATE TABLE IF NOT EXISTS ${n}.work (\n account_id text NOT NULL REFERENCES ${n}.accounts(account_id), work_id text NOT NULL,\n state jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id, work_id)\n );\n CREATE TABLE IF NOT EXISTS ${n}.work_usage (\n account_id text NOT NULL, work_id text NOT NULL, event_id text NOT NULL,\n credits bigint NOT NULL CHECK (credits >= 0), charged bigint NOT NULL CHECK (charged >= 0 AND charged <= credits), reference text NOT NULL,\n PRIMARY KEY(account_id, work_id, event_id), FOREIGN KEY(account_id, work_id) REFERENCES ${n}.work(account_id, work_id)\n );`;\n};\n/** Durable execution claim + capped customer charge. A crash leaves work running\n * and its credits held: never automatically rerun an uncertain external effect.\n * Provider cost over the agreed budget is recorded as absorbed, not customer debt. */\nexport const createPostgresCreditWork = (\n client: CreditSqlClient,\n schema = \"billing_credits\",\n) => {\n const n = namespace(schema);\n const read = async (sql: CreditSql, accountId: string, workId: string) => {\n const { rows } = await sql.query(\n `SELECT state FROM ${n}.work WHERE account_id = $1 AND work_id = $2 FOR UPDATE`,\n [accountId, workId],\n );\n return rows[0]?.state as CreditWork | undefined;\n };\n const save = (\n sql: CreditSql,\n accountId: string,\n workId: string,\n state: CreditWork,\n ) =>\n sql.query(\n `UPDATE ${n}.work SET state = $3::jsonb, updated_at = now() WHERE account_id = $1 AND work_id = $2`,\n [accountId, workId, JSON.stringify(state)],\n );\n const ledger = (sql: CreditSql) =>\n createCreditAccountLedger(\n createPostgresCreditAccountStore(\n { ...sql, transaction: (run) => run(sql) },\n schema,\n ),\n );\n return {\n get: (accountId: string, workId: string) => {\n id(accountId);\n id(workId);\n return client.transaction(\n async (sql) => (await read(sql, accountId, workId)) ?? null,\n );\n },\n begin: (\n accountId: string,\n workId: string,\n request: string,\n budget: number,\n ) => {\n id(accountId);\n id(workId);\n integer(budget);\n if (!budget || !request || request.length > 256)\n throw new Error(\"Invalid credit work request\");\n return client.transaction(async (sql) => {\n // One account lock serializes competing claims, including absent work rows.\n await sql.query(\n `SELECT account_id FROM ${n}.accounts WHERE account_id = $1 FOR UPDATE`,\n [accountId],\n );\n const existing = await read(sql, accountId, workId);\n if (existing) {\n if (existing.request !== request || existing.budget !== budget)\n throw new Error(\"Credit work ID reused with different input\");\n return { fresh: false, work: existing };\n }\n await ledger(sql).execute(accountId, `work-reserve:${workId}`, {\n kind: \"reserve\",\n reservationId: `work:${workId}`,\n credits: budget,\n });\n const work: CreditWork = {\n request,\n budget,\n charged: 0,\n absorbed: 0,\n status: \"running\",\n result: null,\n };\n await sql.query(\n `INSERT INTO ${n}.work (account_id, work_id, state) VALUES ($1, $2, $3::jsonb)`,\n [accountId, workId, JSON.stringify(work)],\n );\n return { fresh: true, work };\n });\n },\n record: (\n accountId: string,\n workId: string,\n eventId: string,\n credits: number,\n reference: string,\n ) => {\n id(accountId);\n id(workId);\n id(eventId);\n integer(credits);\n id(reference);\n return client.transaction(async (sql) => {\n const work = await read(sql, accountId, workId);\n if (!work) throw new Error(\"Credit work does not exist\");\n const { rows } = await sql.query(\n `SELECT credits, charged, reference FROM ${n}.work_usage WHERE account_id = $1 AND work_id = $2 AND event_id = $3`,\n [accountId, workId, eventId],\n );\n const previous = rows[0];\n if (previous) {\n if (\n Number(previous.credits) !== credits ||\n previous.reference !== reference\n )\n throw new Error(\"Credit work event reused with different input\");\n return { charged: Number(previous.charged), fresh: false };\n }\n if (work.status !== \"running\")\n throw new Error(\"Credit work already finished\");\n const charged = Math.min(credits, work.budget - work.charged);\n work.charged += charged;\n work.absorbed += credits - charged;\n integer(work.charged);\n integer(work.absorbed);\n await sql.query(\n `INSERT INTO ${n}.work_usage (account_id, work_id, event_id, credits, charged, reference) VALUES ($1, $2, $3, $4, $5, $6)`,\n [accountId, workId, eventId, credits, charged, reference],\n );\n await save(sql, accountId, workId, work);\n return { charged, fresh: true };\n });\n },\n finish: (\n accountId: string,\n workId: string,\n result: string,\n failed = false,\n ) => {\n id(accountId);\n id(workId);\n return client.transaction(async (sql) => {\n // Match begin's account -> work lock order to avoid a retry/finalize deadlock.\n await sql.query(\n `SELECT account_id FROM ${n}.accounts WHERE account_id = $1 FOR UPDATE`,\n [accountId],\n );\n const work = await read(sql, accountId, workId);\n if (!work) throw new Error(\"Credit work does not exist\");\n if (work.status !== \"running\") return work;\n await ledger(sql).execute(accountId, `work-settle:${workId}`, {\n kind: \"settle\",\n reservationId: `work:${workId}`,\n credits: work.charged,\n });\n work.status = failed ? \"failed\" : \"completed\";\n work.result = result;\n await save(sql, accountId, workId, work);\n return work;\n });\n },\n };\n};\n"
8
+ ],
9
+ "mappings": ";;;;;;;;;;;;;;;;;AA4DA,IAAM,UAAU,CAAC,UAAkB;AAAA,EACjC,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ;AAAA,IAC1C,MAAM,IAAI,MAAM,2CAA2C;AAAA,EAC7D,OAAO;AAAA;AAET,IAAM,iBAAiB,CAAC,UAAkB;AAAA,EACxC,IACE,CAAC,OAAO,SAAS,KAAK,MAAM,KAAK,CAAC,KAClC,IAAI,KAAK,KAAK,EAAE,YAAY,MAAM;AAAA,IAElC,MAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE,OAAO;AAAA;AAET,IAAM,WAAW,CAAC,UAAkB;AAAA,EAClC,IAAI,CAAC,SAAS,MAAM,SAAS;AAAA,IAC3B,MAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C,OAAO;AAAA;AAEF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AAAA,MACT,OAAO,OAAO,YAAY,OAAO,QAAQ;AAAA,QAEvC,MAAM,IAAI,MACR,0BAA0B,+CAC1B,CAAC,SAAS,CACZ;AAAA,QACA,MAAM,OAAO,MAAM,KAAK,KAAK,WAAW,MAAM;AAAA,QAC9C,IAAI,CAAC;AAAA,UAAM,MAAM,IAAI,MAAM,4BAA4B;AAAA,QACvD,IAAI,KAAK,WAAW;AAAA,UAAW,OAAO;AAAA,QACtC,MAAM,OAAO,GAAG,EAAE,QAAQ,WAAW,eAAe,UAAU;AAAA,UAC5D,MAAM;AAAA,UACN,eAAe,QAAQ;AAAA,UACvB,SAAS,KAAK;AAAA,QAChB,CAAC;AAAA,QACD,KAAK,SAAS,SAAS,WAAW;AAAA,QAClC,KAAK,SAAS;AAAA,QACd,MAAM,KAAK,KAAK,WAAW,QAAQ,IAAI;AAAA,QACvC,OAAO;AAAA,OACR;AAAA;AAAA,EAEL;AAAA;",
10
+ "debugId": "AA6CCB44B9F64D8964756E2164756E21",
11
+ "names": []
12
+ }
package/dist/index.js CHANGED
@@ -539,13 +539,13 @@ var formatMicros = (amount, currency, {
539
539
  return `${sign}${whole}.${fractionStr} ${upper}`;
540
540
  };
541
541
  export {
542
- readProviderBalances,
543
- formatMicros,
544
- createPlan,
545
- computeInvoice,
542
+ DEFAULT_DENOMINATION,
546
543
  NANO_DENOMINATION,
547
- DEFAULT_DENOMINATION
544
+ computeInvoice,
545
+ createPlan,
546
+ formatMicros,
547
+ readProviderBalances
548
548
  };
549
549
 
550
- //# debugId=D50F9899A29C0CBA64756E2164756E21
550
+ //# debugId=4B467E2C09E4F21F64756E2164756E21
551
551
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -6,6 +6,6 @@
6
6
  "/**\n * @absolutejs/billing — cost-model substrate for the AbsoluteJS PaaS.\n *\n * Two pieces:\n *\n * - `createPlan(...)` — declarative pricing config: optional flat\n * base fee + per-dimension unit prices, with optional graduated\n * tiers and free-tier allowances per dimension.\n *\n * - `computeInvoice({ plan, period, tenant, usage, currency? })`\n * — pure function that turns a `@absolutejs/metering`-shaped\n * `Usage` snapshot (or any record of metered numbers) into an\n * `Invoice` of line items + total. All money math is done in\n * integer **micros** (1 micro = 1/1,000,000 of a currency unit\n * — the same denomination Stripe uses internally) so float\n * drift is structurally impossible.\n *\n * Invoice sinks (push to Stripe, post to QuickBooks, mail a PDF)\n * live OUTSIDE this package, in `@absolutejs/billing-adapters/*`.\n * Keeping the substrate pure means the control plane can preview\n * invoices, run dry-run \"would-charge\" projections, and replay an\n * old usage snapshot through a new plan without touching any\n * vendor SDK.\n */\n\n// =============================================================================\n// Money primitives\n// =============================================================================\n\n/**\n * An integer amount in a plan's sub-units. 1,000,000 (micros) by default, but\n * a plan may choose a finer denomination — see `Plan.denomination`.\n */\nexport type Micros = number;\n\n/** Sub-units per currency unit when a plan does not say otherwise. */\nexport const DEFAULT_DENOMINATION = 1_000_000;\n\n/** Nanos — the denomination token-priced APIs need. */\nexport const NANO_DENOMINATION = 1_000_000_000;\n\n/**\n * Round a fractional micros value to an integer. The substrate uses\n * **truncation** (banker's-style would surprise callers expecting\n * \"$0.0009 → $0.00\" not \"$0.0009 → $0.001\"). Plans override per-plan.\n */\nexport type Rounding = \"truncate\" | \"round-half-up\";\n\nconst roundMicros = (value: number, rounding: Rounding): Micros => {\n if (rounding === \"truncate\") return Math.trunc(value);\n return Math.round(value);\n};\n\n// =============================================================================\n// Pricing config\n// =============================================================================\n\n/**\n * One step in a graduated-tier price table. `upTo` is the inclusive\n * upper bound (in metered units, NOT micros) for this band.\n * `perUnitMicros` is what the customer pays per single metered unit\n * within this band. The last entry must have `upTo: Infinity` to\n * cover any overflow.\n */\nexport type PricingTier = {\n upTo: number;\n perUnitMicros: number;\n};\n\n/**\n * Per-dimension pricing. Three shapes:\n *\n * - Flat per-unit: `{ perUnitMicros: 200, unit: 1024 * 1024 }`\n * charges 200 micros ($0.0002) per MB of usage.\n *\n * - Tiered: `{ tiers: [...], unit: 1 }` charges per the first\n * matching `PricingTier` band.\n *\n * - Custom: `{ price: (quantity) => micros, unit: 1 }` — escape\n * hatch for surge / caps / non-monotonic pricing. The substrate\n * stays pure; you ship whatever function you want.\n *\n * `freeTier` is subtracted from the metered quantity BEFORE pricing\n * — the conventional \"first N units free\" rule.\n *\n * `unit` is the metered-unit denominator: 1 means \"price per single\n * metered unit\", 1024*1024 means \"price per MB when quantity is in\n * bytes.\" Default 1.\n *\n * `label` overrides the line-item display name.\n */\nexport type PricedDimension = {\n label?: string;\n freeTier?: number;\n unit?: number;\n} & (\n | { perUnitMicros: number; tiers?: never; price?: never }\n | { tiers: PricingTier[]; perUnitMicros?: never; price?: never }\n | {\n price: (chargedQuantity: number) => Micros;\n perUnitMicros?: never;\n tiers?: never;\n }\n);\n\nexport type Plan = {\n /** Human label for the invoice (`'pro'`, `'enterprise'`, etc.). */\n name: string;\n /**\n * Sub-units per currency unit. Defaults to 1,000,000 (micros).\n *\n * Micros are too coarse for token-priced APIs: at $0.16 per million\n * embedding tokens a five-token call costs $0.0000008, which truncates to\n * ZERO in micros — so a plan priced in micros systematically under-bills\n * its cheapest calls. Set `1_000_000_000` to price in nanos, or any other\n * power of ten the vendor's rate card needs. Every `*Micros` field on the\n * plan and the invoice is denominated in these sub-units.\n */\n denomination?: number;\n /** Optional flat base fee charged once per invoice period. */\n basePriceMicros?: Micros;\n /**\n * Dimensions priced from usage. Keys must match keys on the\n * `usage` record passed to `computeInvoice`. Anything not listed\n * is ignored.\n */\n pricedDimensions: Record<string, PricedDimension>;\n /** Default currency for invoices generated from this plan. */\n currency?: string;\n /** Rounding strategy applied per line item. Default `'truncate'`. */\n rounding?: Rounding;\n /**\n * Minimum charge (in micros) — if the computed total is below\n * this floor, the invoice total is raised to the floor and a\n * single `'minimum-charge-adjustment'` line item captures the\n * difference. Defaults to 0 (no floor).\n */\n minimumChargeMicros?: Micros;\n /** Arbitrary plan-level metadata that flows through to invoices. */\n metadata?: Record<string, string>;\n};\n\nexport const createPlan = (plan: Plan): Plan => {\n for (const [key, dim] of Object.entries(plan.pricedDimensions)) {\n if (dim.tiers !== undefined) {\n if (dim.tiers.length === 0) {\n throw new Error(`billing: dimension '${key}' has no tiers`);\n }\n const last = dim.tiers[dim.tiers.length - 1];\n if (last !== undefined && Number.isFinite(last.upTo)) {\n throw new Error(\n `billing: dimension '${key}' final tier must have upTo: Infinity`,\n );\n }\n let prev = 0;\n for (let i = 0; i < dim.tiers.length; i += 1) {\n const tier = dim.tiers[i]!;\n if (tier.upTo < prev) {\n throw new Error(\n `billing: dimension '${key}' tier #${i} upTo (${tier.upTo}) must be >= previous (${prev})`,\n );\n }\n prev = tier.upTo;\n }\n }\n }\n return plan;\n};\n\n// =============================================================================\n// Invoice shape\n// =============================================================================\n\nexport type LineItem = {\n /**\n * Stable key for the line item. For priced dimensions it's the\n * usage-record key (`'requests'`, `'cpuMs'`, etc.). For the base\n * fee it's `'base'`. For minimum-charge top-up it's\n * `'minimum-charge-adjustment'`.\n */\n key: string;\n /** Human-readable label. */\n label: string;\n /** Metered units BEFORE applying free tier. 0 for the base fee. */\n quantity: number;\n /** Metered units AFTER applying free tier (what's actually charged). */\n chargedQuantity: number;\n /** Free-tier units subtracted from `quantity`. */\n freeTier?: number;\n /** Charge for this line in integer micros. */\n amountMicros: Micros;\n /**\n * Tier-by-tier breakdown when graduated pricing was used. Each\n * entry: `{ tierIndex, unitsInTier, perUnitMicros, amountMicros }`.\n */\n tierBreakdown?: Array<{\n tierIndex: number;\n unitsInTier: number;\n perUnitMicros: number;\n amountMicros: Micros;\n }>;\n};\n\nexport type InvoicePeriod = {\n /** Inclusive period start (`Date.now()` ms). */\n start: number;\n /** Exclusive period end. */\n end: number;\n};\n\nexport type Invoice = {\n tenant: string;\n plan: string;\n currency: string;\n /** Sub-units per currency unit these amounts are in (default micros). */\n denomination: number;\n period: InvoicePeriod;\n lineItems: LineItem[];\n /** Sum of all `lineItems[].amountMicros`. */\n totalMicros: Micros;\n /** Convenience: `totalMicros / 1_000_000` as a number. */\n totalUnits: number;\n /** Plan-level metadata copied through unchanged. */\n metadata?: Record<string, string>;\n};\n\n// =============================================================================\n// Pricing math\n// =============================================================================\n\ntype ComputeDimensionInput = {\n quantity: number;\n dim: PricedDimension;\n rounding: Rounding;\n};\n\ntype ComputeDimensionResult = {\n amountMicros: Micros;\n chargedQuantity: number;\n tierBreakdown?: LineItem[\"tierBreakdown\"];\n};\n\nconst computeDimension = ({\n quantity,\n dim,\n rounding,\n}: ComputeDimensionInput): ComputeDimensionResult => {\n const free = dim.freeTier ?? 0;\n const charged = Math.max(0, quantity - free);\n const unit = dim.unit ?? 1;\n const chargedUnits = unit === 1 ? charged : charged / unit;\n\n if (dim.perUnitMicros !== undefined) {\n const amountMicros = roundMicros(\n chargedUnits * dim.perUnitMicros,\n rounding,\n );\n return { amountMicros, chargedQuantity: charged };\n }\n\n if (dim.price !== undefined) {\n const amountMicros = roundMicros(dim.price(charged), rounding);\n return { amountMicros, chargedQuantity: charged };\n }\n\n // Tiered pricing — walk tiers, allocate chargedUnits into bands.\n const tierBreakdown: NonNullable<LineItem[\"tierBreakdown\"]> = [];\n let remaining = chargedUnits;\n let bandFloor = 0;\n let totalMicros = 0;\n for (let i = 0; i < dim.tiers!.length && remaining > 0; i += 1) {\n const tier = dim.tiers![i]!;\n const bandWidth = tier.upTo - bandFloor;\n const unitsInTier = Math.min(remaining, bandWidth);\n if (unitsInTier > 0) {\n const tierMicros = roundMicros(\n unitsInTier * tier.perUnitMicros,\n rounding,\n );\n tierBreakdown.push({\n amountMicros: tierMicros,\n perUnitMicros: tier.perUnitMicros,\n tierIndex: i,\n unitsInTier,\n });\n totalMicros += tierMicros;\n }\n remaining -= unitsInTier;\n bandFloor = tier.upTo;\n }\n return {\n amountMicros: totalMicros,\n chargedQuantity: charged,\n tierBreakdown,\n };\n};\n\n// =============================================================================\n// computeInvoice — pure\n// =============================================================================\n\nexport type ComputeInvoiceInput = {\n plan: Plan;\n tenant: string;\n period: InvoicePeriod;\n /** Metered numbers keyed by the same names as `plan.pricedDimensions`. */\n usage: Record<string, number>;\n /** Override the plan's currency (e.g. for tenant-local invoicing). */\n currency?: string;\n};\n\nexport const computeInvoice = ({\n plan,\n tenant,\n period,\n usage,\n currency,\n}: ComputeInvoiceInput): Invoice => {\n const rounding = plan.rounding ?? \"truncate\";\n const lineItems: LineItem[] = [];\n\n if (plan.basePriceMicros !== undefined && plan.basePriceMicros > 0) {\n lineItems.push({\n amountMicros: plan.basePriceMicros,\n chargedQuantity: 1,\n key: \"base\",\n label: `${plan.name} base fee`,\n quantity: 1,\n });\n }\n\n for (const [key, dim] of Object.entries(plan.pricedDimensions)) {\n const quantity = usage[key] ?? 0;\n if (!Number.isFinite(quantity) || quantity < 0) continue;\n const result = computeDimension({ dim, quantity, rounding });\n if (result.amountMicros === 0 && result.chargedQuantity === 0) continue;\n const item: LineItem = {\n amountMicros: result.amountMicros,\n chargedQuantity: result.chargedQuantity,\n key,\n label: dim.label ?? key,\n quantity,\n };\n if (dim.freeTier !== undefined) item.freeTier = dim.freeTier;\n if (result.tierBreakdown !== undefined && result.tierBreakdown.length > 0) {\n item.tierBreakdown = result.tierBreakdown;\n }\n lineItems.push(item);\n }\n\n let totalMicros = lineItems.reduce((sum, item) => sum + item.amountMicros, 0);\n\n const floor = plan.minimumChargeMicros ?? 0;\n if (floor > 0 && totalMicros < floor) {\n const gap = floor - totalMicros;\n lineItems.push({\n amountMicros: gap,\n chargedQuantity: 1,\n key: \"minimum-charge-adjustment\",\n label: \"Minimum charge adjustment\",\n quantity: 1,\n });\n totalMicros = floor;\n }\n\n const denomination = plan.denomination ?? DEFAULT_DENOMINATION;\n const invoice: Invoice = {\n currency: currency ?? plan.currency ?? \"usd\",\n denomination,\n lineItems,\n period,\n plan: plan.name,\n tenant,\n totalMicros,\n totalUnits: totalMicros / denomination,\n };\n if (plan.metadata !== undefined) invoice.metadata = plan.metadata;\n return invoice;\n};\n\n// =============================================================================\n// Display helpers\n// =============================================================================\n\n/**\n * Format an integer micros amount as a human currency string. Pure\n * — no Intl side effects. For locales / advanced formatting, pipe\n * through `Intl.NumberFormat` yourself.\n */\nexport const formatMicros = (\n amount: Micros,\n currency: string,\n {\n denomination = DEFAULT_DENOMINATION,\n minorUnits = 2,\n }: { denomination?: number; minorUnits?: number } = {},\n): string => {\n const sign = amount < 0 ? \"-\" : \"\";\n const abs = Math.abs(amount);\n const exponent = Math.round(Math.log10(denomination));\n const wholeMicrosPerMinor = 10 ** (exponent - minorUnits);\n const minorTotal = Math.round(abs / wholeMicrosPerMinor);\n const divisor = 10 ** minorUnits;\n const whole = Math.trunc(minorTotal / divisor);\n const upper = currency.toUpperCase();\n if (minorUnits === 0) return `${sign}${whole} ${upper}`;\n const fraction = minorTotal % divisor;\n const fractionStr = fraction.toString().padStart(minorUnits, \"0\");\n return `${sign}${whole}.${fractionStr} ${upper}`;\n};\n\n// Provider balances — read upstream vendors' real balance/quota/spend (the\n// inverse of computeInvoice). See ./balances.\nexport {\n readProviderBalances,\n type ProviderBalance,\n type ProviderBalanceConfig,\n type ProviderBalanceKind,\n type ProviderBalanceStatus,\n type BraveUsageSnapshot,\n type EmbeddingUsageSnapshot,\n} from \"./balances\";\n"
7
7
  ],
8
8
  "mappings": ";;;;;;;;;;;;;;;;;AAoBA,IAAM,mBAAmB;AAGzB,IAAM,wBAAwB;AAC9B,IAAM,gBAAgB;AACtB,IAAM,aAAa;AACnB,IAAM,UAAU;AAChB,IAAM,WAAW;AACjB,IAAM,mBAAmB;AAkEzB,IAAM,SAAS,MAAM,IAAI,KAAK,EAAE,YAAY;AAE5C,IAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU;AAEzC,IAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AAEhE,IAAM,MAAM,CAAC,WAAmB,IAAI,OAAO,QAAQ,CAAC;AAEpD,IAAM,UAAU,CAAC,UAAkB;AAAA,EACjC,IAAI,SAAS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,KAAK,aAAa;AAAA,IAAW,QAAQ,WAAW,KAAK;AAAA,EACzD,OAAO;AAAA;AAYF,IAAM,eAAe,CAC1B,QACA;AAAA,EAEE,eAAe;AAAA,EACf,aAAa;AAAA,IACqC,CAAC,MAC1C;AAAA,EACX,MAAM,OAAO,SAAS,IAAI,MAAM;AAAA,EAChC,MAAM,MAAM,KAAK,IAAI,MAAM;AAAA,EAC3B,MAAM,WAAW,KAAK,MAAM,KAAK,MAAM,YAAY,CAAC;AAAA,EACpD,MAAM,sBAAsB,OAAO,WAAW;AAAA,EAC9C,MAAM,aAAa,KAAK,MAAM,MAAM,mBAAmB;AAAA,EACvD,MAAM,UAAU,MAAM;AAAA,EACtB,MAAM,QAAQ,KAAK,MAAM,aAAa,OAAO;AAAA,EAC7C,MAAM,QAAQ,SAAS,YAAY;AAAA,EACnC,IAAI,eAAe;AAAA,IAAG,OAAO,GAAG,OAAO,SAAS;AAAA,EAChD,MAAM,WAAW,aAAa;AAAA,EAC9B,MAAM,cAAc,SAAS,SAAS,EAAE,SAAS,YAAY,GAAG;AAAA,EAChE,OAAO,GAAG,OAAO,SAAS,eAAe;AAAA;",
9
- "debugId": "D50F9899A29C0CBA64756E2164756E21",
9
+ "debugId": "4B467E2C09E4F21F64756E2164756E21",
10
10
  "names": []
11
11
  }
package/dist/ledger.d.ts CHANGED
@@ -54,3 +54,52 @@ export type UsageLedger = {
54
54
  overCap: (capSubUnits: number, since: Date) => Promise<boolean>;
55
55
  };
56
56
  export declare const createUsageLedger: (options: UsageLedgerOptions) => UsageLedger;
57
+ export type CreditBalanceInput = {
58
+ /** Granted credits that SURVIVE a period reset (referrals, goodwill). */
59
+ bonusCredits: number;
60
+ consumed: number;
61
+ /** Credits the plan grants for the current period. */
62
+ periodAllowance: number;
63
+ periodEnd?: Date | null;
64
+ };
65
+ export type CreditBalance = {
66
+ /** periodAllowance + bonusCredits — the spendable ceiling this period. */
67
+ allowance: number;
68
+ bonusCredits: number;
69
+ consumed: number;
70
+ periodAllowance: number;
71
+ periodEnd: Date | null;
72
+ /** Never negative: an over-spend reads as zero left, not a debt. */
73
+ remaining: number;
74
+ };
75
+ /** Derive the spendable view of a stored balance row. */
76
+ export declare const creditBalanceFrom: (row: CreditBalanceInput) => CreditBalance;
77
+ /** Whether the billing window has closed and the allowance should re-snapshot.
78
+ * A null end date means "no window" — an unbounded balance never lapses. */
79
+ export declare const isPeriodLapsed: (periodEnd: Date | null | undefined, now?: Date) => boolean;
80
+ /**
81
+ * How hard the gate bites. `off` skips the balance read entirely, `warn`
82
+ * always allows but reports `low` so the UI can say so, `block` refuses once
83
+ * the remaining balance cannot cover the estimate.
84
+ */
85
+ export type CreditEnforcementMode = "block" | "off" | "warn";
86
+ export type CreditGate = {
87
+ allowance: number;
88
+ allowed: boolean;
89
+ /** True when the balance cannot cover the estimate, in ANY mode — the
90
+ * signal a product surfaces before it starts refusing work. */
91
+ low: boolean;
92
+ mode: CreditEnforcementMode;
93
+ remaining: number;
94
+ };
95
+ export type CreditGateInput = {
96
+ allowance: number;
97
+ estimatedCredits?: number;
98
+ mode: CreditEnforcementMode;
99
+ remaining: number;
100
+ };
101
+ /** Decide whether a metered call proceeds. Pure — the caller does the reads. */
102
+ export declare const creditGate: (input: CreditGateInput) => CreditGate;
103
+ /** Whether a bonus grant is worth writing — guards against NaN and negatives
104
+ * quietly corrupting a balance. */
105
+ export declare const isGrantableCredits: (credits: number) => boolean;
package/dist/ledger.js CHANGED
@@ -45,10 +45,41 @@ var createUsageLedger = (options) => {
45
45
  }
46
46
  };
47
47
  };
48
+ var creditBalanceFrom = (row) => {
49
+ const allowance = row.periodAllowance + row.bonusCredits;
50
+ return {
51
+ allowance,
52
+ bonusCredits: row.bonusCredits,
53
+ consumed: row.consumed,
54
+ periodAllowance: row.periodAllowance,
55
+ periodEnd: row.periodEnd ?? null,
56
+ remaining: Math.max(0, allowance - row.consumed)
57
+ };
58
+ };
59
+ var isPeriodLapsed = (periodEnd, now = new Date) => periodEnd !== null && periodEnd !== undefined && periodEnd.getTime() <= now.getTime();
60
+ var creditGate = (input) => {
61
+ const { allowance, estimatedCredits = 1, mode, remaining } = input;
62
+ if (mode === "off") {
63
+ return { allowance: 0, allowed: true, low: false, mode, remaining: 0 };
64
+ }
65
+ const sufficient = remaining >= estimatedCredits;
66
+ return {
67
+ allowance,
68
+ allowed: mode === "block" ? sufficient : true,
69
+ low: !sufficient,
70
+ mode,
71
+ remaining
72
+ };
73
+ };
74
+ var isGrantableCredits = (credits) => Number.isFinite(credits) && credits > 0;
48
75
  export {
76
+ createUsageLedger,
77
+ creditBalanceFrom,
78
+ creditGate,
49
79
  creditsFor,
50
- createUsageLedger
80
+ isGrantableCredits,
81
+ isPeriodLapsed
51
82
  };
52
83
 
53
- //# debugId=0E1FB04E107E92A964756E2164756E21
84
+ //# debugId=CB2DC54F3ACBA03564756E2164756E21
54
85
  //# sourceMappingURL=ledger.js.map
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/ledger.ts"],
4
4
  "sourcesContent": [
5
- "// The layer between a meter and an invoice: every metered event gets priced,\n// converted to the customer's credit unit, written to an append-only ledger,\n// debited against a balance, and folded into a daily rollup that a spend cap\n// can read. Every app billing a metered API rebuilds this, and each one\n// rediscovers the same three traps:\n//\n// - Money in floats. Summing float ledger rows drifts; one real deployment\n// lost 2 cents across 25,740 rows before anyone noticed. Amounts here are\n// integer sub-units (see Plan.denomination) and are only ever added.\n// - The debit and the ledger row diverging. If the row is written but the\n// balance is not debited, a customer gets free usage; the reverse\n// over-charges. They must land together, so the store commits them as one\n// unit — this module never splits them.\n// - The rollup being treated as truth. It is a derived index, rebuildable\n// from the ledger, so a rollup failure must never fail the charge.\n//\n// Storage stays the host's business (Postgres, ClickHouse, anything). This\n// owns the policy and the arithmetic, which is the part that is identical\n// everywhere — and the part that is worth getting wrong only once.\n\n/** One priced, metered event, ready to persist. */\nexport type LedgerEntry = {\n /** Charge in integer sub-units of the plan's denomination (see\n * `Plan.denomination`) — never a float. */\n amount: number;\n /** What the customer is billed in the product's own unit. */\n credits: number;\n /** Product-level grouping (\"chat\", \"voice\"), not the vendor's. */\n feature?: string | null;\n model?: string;\n /** \"llm\" | \"tts\" | \"embedding\" | whatever the product meters. */\n operation: string;\n provider: string;\n /** Idempotency handle for at-least-once callers. */\n requestId?: string;\n /** Null for system/background work with nobody to bill. */\n tenant?: string | null;\n};\n\nexport type LedgerCommit = {\n /** Append the row AND debit `entry.credits` from the tenant's balance in a\n * single atomic unit. Called with tenant null for unattributed work, where\n * there is nothing to debit. */\n commit: (entry: LedgerEntry) => Promise<void>;\n /** Fold the entry into a derived daily aggregate. Best-effort by contract:\n * this module swallows its failures. */\n rollup?: (entry: LedgerEntry) => Promise<void>;\n /** Total sub-units charged since `since`, for the spend cap. */\n spentSince?: (since: Date) => Promise<number>;\n};\n\nexport type UsageLedgerOptions = {\n /** Sub-units per credit. A peg of 1_000 with micros means 1 credit =\n * $0.001. Required for credit conversion; omit to bill in raw amounts. */\n creditPegSubUnits?: number;\n /** Reported when a rollup fails. The charge already succeeded. */\n onRollupError?: (error: unknown, entry: LedgerEntry) => void;\n store: LedgerCommit;\n};\n\n/**\n * Credits for a charge. Ceiling, not rounding: a product that sells credits\n * must never hand out a fraction it cannot deduct, and rounding down means\n * the smallest calls are free — which is how a \"cheap\" endpoint becomes an\n * unmetered one.\n */\nexport const creditsFor = (amount: number, pegSubUnits: number) => {\n if (pegSubUnits <= 0) return 0;\n\n return Math.ceil(amount / pegSubUnits);\n};\n\nexport type UsageLedger = {\n /** Price-agnostic: hand it an amount already in sub-units. Returns what was\n * written, including the credits it derived. */\n record: (\n entry: Omit<LedgerEntry, \"credits\"> & { credits?: number },\n ) => Promise<LedgerEntry>;\n /** True once spend since `since` reaches `capSubUnits`. Fails OPEN — a\n * broken cap must not take down paid features, and the per-provider\n * budgets are still in front. */\n overCap: (capSubUnits: number, since: Date) => Promise<boolean>;\n};\n\nexport const createUsageLedger = (options: UsageLedgerOptions): UsageLedger => {\n const { creditPegSubUnits, onRollupError, store } = options;\n\n return {\n overCap: async (capSubUnits, since) => {\n if (!store.spentSince) return false;\n try {\n return (await store.spentSince(since)) >= capSubUnits;\n } catch {\n return false;\n }\n },\n record: async (input) => {\n const credits =\n input.credits ??\n (creditPegSubUnits === undefined\n ? 0\n : creditsFor(input.amount, creditPegSubUnits));\n const entry: LedgerEntry = { ...input, credits };\n // The charge is the thing that must not be lost; it is awaited and its\n // failure propagates to the caller.\n await store.commit(entry);\n // The rollup is a derived index — rebuildable from the ledger — so its\n // failure is reported, never raised.\n if (store.rollup) {\n await store.rollup(entry).catch((error: unknown) => {\n onRollupError?.(error, entry);\n });\n }\n\n return entry;\n },\n };\n};\n"
5
+ "// The layer between a meter and an invoice: every metered event gets priced,\n// converted to the customer's credit unit, written to an append-only ledger,\n// debited against a balance, and folded into a daily rollup that a spend cap\n// can read. Every app billing a metered API rebuilds this, and each one\n// rediscovers the same three traps:\n//\n// - Money in floats. Summing float ledger rows drifts; one real deployment\n// lost 2 cents across 25,740 rows before anyone noticed. Amounts here are\n// integer sub-units (see Plan.denomination) and are only ever added.\n// - The debit and the ledger row diverging. If the row is written but the\n// balance is not debited, a customer gets free usage; the reverse\n// over-charges. They must land together, so the store commits them as one\n// unit — this module never splits them.\n// - The rollup being treated as truth. It is a derived index, rebuildable\n// from the ledger, so a rollup failure must never fail the charge.\n//\n// Storage stays the host's business (Postgres, ClickHouse, anything). This\n// owns the policy and the arithmetic, which is the part that is identical\n// everywhere — and the part that is worth getting wrong only once.\n\n/** One priced, metered event, ready to persist. */\nexport type LedgerEntry = {\n /** Charge in integer sub-units of the plan's denomination (see\n * `Plan.denomination`) — never a float. */\n amount: number;\n /** What the customer is billed in the product's own unit. */\n credits: number;\n /** Product-level grouping (\"chat\", \"voice\"), not the vendor's. */\n feature?: string | null;\n model?: string;\n /** \"llm\" | \"tts\" | \"embedding\" | whatever the product meters. */\n operation: string;\n provider: string;\n /** Idempotency handle for at-least-once callers. */\n requestId?: string;\n /** Null for system/background work with nobody to bill. */\n tenant?: string | null;\n};\n\nexport type LedgerCommit = {\n /** Append the row AND debit `entry.credits` from the tenant's balance in a\n * single atomic unit. Called with tenant null for unattributed work, where\n * there is nothing to debit. */\n commit: (entry: LedgerEntry) => Promise<void>;\n /** Fold the entry into a derived daily aggregate. Best-effort by contract:\n * this module swallows its failures. */\n rollup?: (entry: LedgerEntry) => Promise<void>;\n /** Total sub-units charged since `since`, for the spend cap. */\n spentSince?: (since: Date) => Promise<number>;\n};\n\nexport type UsageLedgerOptions = {\n /** Sub-units per credit. A peg of 1_000 with micros means 1 credit =\n * $0.001. Required for credit conversion; omit to bill in raw amounts. */\n creditPegSubUnits?: number;\n /** Reported when a rollup fails. The charge already succeeded. */\n onRollupError?: (error: unknown, entry: LedgerEntry) => void;\n store: LedgerCommit;\n};\n\n/**\n * Credits for a charge. Ceiling, not rounding: a product that sells credits\n * must never hand out a fraction it cannot deduct, and rounding down means\n * the smallest calls are free — which is how a \"cheap\" endpoint becomes an\n * unmetered one.\n */\nexport const creditsFor = (amount: number, pegSubUnits: number) => {\n if (pegSubUnits <= 0) return 0;\n\n return Math.ceil(amount / pegSubUnits);\n};\n\nexport type UsageLedger = {\n /** Price-agnostic: hand it an amount already in sub-units. Returns what was\n * written, including the credits it derived. */\n record: (\n entry: Omit<LedgerEntry, \"credits\"> & { credits?: number },\n ) => Promise<LedgerEntry>;\n /** True once spend since `since` reaches `capSubUnits`. Fails OPEN — a\n * broken cap must not take down paid features, and the per-provider\n * budgets are still in front. */\n overCap: (capSubUnits: number, since: Date) => Promise<boolean>;\n};\n\nexport const createUsageLedger = (options: UsageLedgerOptions): UsageLedger => {\n const { creditPegSubUnits, onRollupError, store } = options;\n\n return {\n overCap: async (capSubUnits, since) => {\n if (!store.spentSince) return false;\n try {\n return (await store.spentSince(since)) >= capSubUnits;\n } catch {\n return false;\n }\n },\n record: async (input) => {\n const credits =\n input.credits ??\n (creditPegSubUnits === undefined\n ? 0\n : creditsFor(input.amount, creditPegSubUnits));\n const entry: LedgerEntry = { ...input, credits };\n // The charge is the thing that must not be lost; it is awaited and its\n // failure propagates to the caller.\n await store.commit(entry);\n // The rollup is a derived index — rebuildable from the ledger — so its\n // failure is reported, never raised.\n if (store.rollup) {\n await store.rollup(entry).catch((error: unknown) => {\n onRollupError?.(error, entry);\n });\n }\n\n return entry;\n },\n };\n};\n\n// -----------------------------------------------------------------------------\n// Credit balances\n// -----------------------------------------------------------------------------\n\n// A credit-based product needs the same four decisions no matter what it\n// sells: what the customer may spend, whether the period has rolled, whether\n// this call is allowed, and whether a grant is real. The lookups behind them\n// (subscriptions, comps, plan tables) are the host's; the arithmetic is not,\n// and it is the part where an off-by-one hands out free usage.\n\nexport type CreditBalanceInput = {\n /** Granted credits that SURVIVE a period reset (referrals, goodwill). */\n bonusCredits: number;\n consumed: number;\n /** Credits the plan grants for the current period. */\n periodAllowance: number;\n periodEnd?: Date | null;\n};\n\nexport type CreditBalance = {\n /** periodAllowance + bonusCredits — the spendable ceiling this period. */\n allowance: number;\n bonusCredits: number;\n consumed: number;\n periodAllowance: number;\n periodEnd: Date | null;\n /** Never negative: an over-spend reads as zero left, not a debt. */\n remaining: number;\n};\n\n/** Derive the spendable view of a stored balance row. */\nexport const creditBalanceFrom = (row: CreditBalanceInput): CreditBalance => {\n const allowance = row.periodAllowance + row.bonusCredits;\n\n return {\n allowance,\n bonusCredits: row.bonusCredits,\n consumed: row.consumed,\n periodAllowance: row.periodAllowance,\n periodEnd: row.periodEnd ?? null,\n remaining: Math.max(0, allowance - row.consumed),\n };\n};\n\n/** Whether the billing window has closed and the allowance should re-snapshot.\n * A null end date means \"no window\" — an unbounded balance never lapses. */\nexport const isPeriodLapsed = (\n periodEnd: Date | null | undefined,\n now = new Date(),\n) =>\n periodEnd !== null &&\n periodEnd !== undefined &&\n periodEnd.getTime() <= now.getTime();\n\n/**\n * How hard the gate bites. `off` skips the balance read entirely, `warn`\n * always allows but reports `low` so the UI can say so, `block` refuses once\n * the remaining balance cannot cover the estimate.\n */\nexport type CreditEnforcementMode = \"block\" | \"off\" | \"warn\";\n\nexport type CreditGate = {\n allowance: number;\n allowed: boolean;\n /** True when the balance cannot cover the estimate, in ANY mode — the\n * signal a product surfaces before it starts refusing work. */\n low: boolean;\n mode: CreditEnforcementMode;\n remaining: number;\n};\n\nexport type CreditGateInput = {\n allowance: number;\n estimatedCredits?: number;\n mode: CreditEnforcementMode;\n remaining: number;\n};\n\n/** Decide whether a metered call proceeds. Pure — the caller does the reads. */\nexport const creditGate = (input: CreditGateInput): CreditGate => {\n const { allowance, estimatedCredits = 1, mode, remaining } = input;\n if (mode === \"off\") {\n return { allowance: 0, allowed: true, low: false, mode, remaining: 0 };\n }\n const sufficient = remaining >= estimatedCredits;\n\n return {\n allowance,\n allowed: mode === \"block\" ? sufficient : true,\n low: !sufficient,\n mode,\n remaining,\n };\n};\n\n/** Whether a bonus grant is worth writing — guards against NaN and negatives\n * quietly corrupting a balance. */\nexport const isGrantableCredits = (credits: number) =>\n Number.isFinite(credits) && credits > 0;\n"
6
6
  ],
7
- "mappings": ";;;;;;;;;;;;;;;;;AAkEO,IAAM,aAAa,CAAC,QAAgB,gBAAwB;AAAA,EACjE,IAAI,eAAe;AAAA,IAAG,OAAO;AAAA,EAE7B,OAAO,KAAK,KAAK,SAAS,WAAW;AAAA;AAehC,IAAM,oBAAoB,CAAC,YAA6C;AAAA,EAC7E,QAAQ,mBAAmB,eAAe,UAAU;AAAA,EAEpD,OAAO;AAAA,IACL,SAAS,OAAO,aAAa,UAAU;AAAA,MACrC,IAAI,CAAC,MAAM;AAAA,QAAY,OAAO;AAAA,MAC9B,IAAI;AAAA,QACF,OAAQ,MAAM,MAAM,WAAW,KAAK,KAAM;AAAA,QAC1C,MAAM;AAAA,QACN,OAAO;AAAA;AAAA;AAAA,IAGX,QAAQ,OAAO,UAAU;AAAA,MACvB,MAAM,UACJ,MAAM,YACL,sBAAsB,YACnB,IACA,WAAW,MAAM,QAAQ,iBA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