lib.billing-runtime
Pure backend-neutral BillingOS runtime helpers for deterministic quote-to-cash lifecycle projections.
@lssm-tech/lib.billing-runtimebun add @lssm-tech/lib.billing-runtimeManifest declarations describe the current workspace; they do not verify registry publication or runtime execution.
Package guide
Pure, backend-neutral BillingOS runtime helpers over @lssm-tech/lib.billing-spec.
France readiness metadata is not PA accreditation, production PA submission, legal advice, or tax advice.
Runtime helpers
@lssm-tech/lib.billing-runtime provides pure helper engines over @lssm-tech/lib.billing-spec:
- quote/order/invoice/payment/reconciliation lifecycle projections;
- deterministic pricing totals with an injected synchronous tax-calculation port;
- local workflow event creation/appending;
- payment-state reconciliation hints;
- draft accounting export shaping;
- deterministic quote-to-cash cockpit projections with lifecycle, approval-packet, surface, and finance-review handoff metadata; and
- agent planning guards that produce approval packets instead of executing high-impact billing actions.
The package performs no network calls, filesystem access, provider SDK calls, credential handling, persistence writes, PA submission, or autonomous production billing execution.
BillingOS truth and FinanceOS handoff
The additive ./truth surface projects normalized billing facts into the append-only economic-evidence lifecycle, provides a tenant-isolated in-memory reference store with revision and idempotency guards, records superseding corrections without deleting history, and validates balanced, company-scoped posting handoffs. A posting handoff remains a proposal until an explicit ContractSpec Connect authorization reference is supplied.
Persistence ports (additive)
Backend-neutral port interfaces that a host implements against its store; the package defines the contracts, never the adapters:
InvoiceRepositoryPort— persist and read issued invoices.EventLogAppendPort— append-only billing workflow event log.InvoiceChainAppendPort— append entries to the per-period invoice hash-chain.CreditNoteRepositoryPort— persist and read credit notes (avoir).
Observability (additive)
BillingObservabilityPort— structured, correlation-id-propagating observability hook for issuance and submission.- Field-level redaction of SIREN/SIRET/VAT identifiers, secrets, and amounts so no sensitive payload is logged; redaction is applied before any sink receives the record.
Service agreements (./service-agreement, additive)
Pure engines and host ports for @lssm-tech/lib.billing-spec/service-agreement:
recordServiceUsage/correctServiceUsageoverServiceUsageLedgerPort: atomic usage + outbox + work-completion transaction; identical replay returns the stored receipt, a changed payload conflicts, corrections supersede the current head without deleting history.recordMeteredServiceUsageoverServicePriceTablePortandMeteredServiceUsageStorePort: meters one platform service call exactly once per tenant and usage ref, rated byselectServicePriceVersion/rateServiceUsageagainst the version effective at the occurrence. It never guesses a price: the call isunpriceduntil the owner sets one. An optionalMeteredServiceBillingPortappends the call to the service usage ledger throughrecordServiceUsagewhen the tenant's agreement sells the meter; a replay returns the stored receipt and a changed payload conflicts.occurredAtis metadata: the first recorded occurrence wins, and a retry after a crash that left the call in the ledger only adopts that ledger event. The bound ledger must scope event ids (usage:<usageRef>) by tenant.toMeterServiceUsageOutputprojects a result onto thebilling.service.usage.meteroutput; the host emits itsbilling.service.usage.meteredaudit record.InMemoryServicePriceTableandInMemoryMeteredServiceUsageStoreare the reference adapters.computeServiceInvoiceDraft: deterministic, digest-bound drafts per cadence period with frozen price editions; late usage and post-issue corrections become adjustment or credit lines for the earlier period instead of rewriting issued invoices; BYOK never yields passthrough.reserveServiceCapacity/settleServiceReservation/resumeServiceBudgetover a compare-and-setServiceBudgetStorePort: allowance, approved overage ceiling, bounded grace and pause, plus a separate internal provider budget.buildOnPremUsageBatch/importOnPremUsageBatch: signed digest-only batches with replay, gap, fork, instance-change, key-rotation and clock checks.submitServiceInvoiceOnce/issueServiceInvoice/applyServicePaymentEvent: approved, exactly-once submission (unique per tenant and merchant), approved issue, and idempotent, order-safe payment evidence.openServiceCollection/issueStoredServiceInvoice/receiveServicePaymentEventoverServiceCollectionStorePort: collection state per invoice under a row lock; a verified webhook is stored once per merchant and provider event id (redelivery is a duplicate, a changed payload conflicts), and events that arrive before issuance are held and applied at issuance.requireServiceApproval: consequential actions verify anOperationApprovalReceiptthrough the host'sOperationApprovalPort(subject, operation key/version, input digest, consumed nonce). A caller-supplied decision string is never authority; with no port bound the action fails closed.
In-memory reference adapters mirror the required host semantics for tests; they are not durable storage. Hosts bind the ports to their database.
Subscriptions (./subscriptions/durable, additive)
Store port and engines for @lssm-tech/lib.billing-spec/subscriptions:
SubscriptionStorePortunits of work: insert-only plan versions (identical republish isduplicate, different content under the same version isPLAN_VERSION_CONFLICT), one subscription row per tenant, product and subject under a revision check, and grants that record tier, per-period limit and whether they rest on confirmed or last-known state.- State events are unique per tenant, source and event id: a redelivery with the same digest is
duplicate, a changed payload isSUBSCRIPTION_EVENT_CONFLICT, an older fact isstale, and a test/live mode mismatch isSUBSCRIPTION_MODE_CONFLICT. - Checkout intents atomically claim one subject across offers and runtimes. Short committed begin/renew/complete/release units never hold a database transaction over provider I/O; an unexpired owner excludes competitors, stale owners cannot settle, and release or expiry permits read-first recovery.
- Access:
canceled/expiredrevokes at the provider end time (falling back to the period end) and keeps the revoked row with its reason; a scheduled cancellation keeps access until the period end;past_duekeeps access and a missed renewal never revokes;pendingandpausednever grant. - An
unknownprovider outcome never invents a status: an existing subscription is flagged for reconciliation and access continues on the last known state withreconciliationRequired: true; with no stored subscriptioncheckdenies withoutcome_unknown.reconcileresolves it from a provider snapshot (unavailablestays unknown,not_foundexpires a non-terminal subscription and revokes its grants,foundpicks one subscription deterministically).
InMemorySubscriptionStore is a reference adapter for tests and test mode; it is not durable storage. These grants are billing entitlements, separate from AuthOS product admission.
The durable Postgres adapter lives outside this package (D-125): @lssm-tech/integration.billing-subscriptions-postgres implements SubscriptionStorePort over an injected SQL interface with forced tenant RLS, a NOSUPERUSER NOBYPASSRLS runtime role, insert-only plans, unchangeable event payloads and final revocations, and refuses superuser or RLS-bypassing roles. Stripe test-mode webhook and snapshot mapping lives in @lssm-tech/integration.provider-payments.
./subscriptions/durable/conformance is a test-support subpath (it imports bun:test): the shared store, checkout-intent, boundary, reconcile and concurrency suites, the SubscriptionStoreHarness contract and fixtures. This package runs them on the in-memory store; every durable adapter runs the same suites on its store.
Relationships
Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.
3 declarations
@lssm-tech/lib.billing-specworkspace:^
Read the package manual ↗@lssm-tech/lib.economic-evidenceworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-spec-coreworkspace:^
Read the package manual ↗
Declared capabilities
Pure backend-neutral BillingOS runtime helpers for deterministic quote-to-cash lifecycle projections.
Scripts
publish:pkgbun publish --tolerate-republish --ignore-scripts --verbosepublish:pkg:canarybun publish:pkg --tag canarybuildcontractspec-bun-build buildbuild:bundlecontractspec-bun-build transpilebuild:typescontractspec-bun-build typesdevcontractspec-bun-build devcleanrimraf dist .turbolintbun lint:fixlint:fixnode ../../../../scripts/biome.cjs check --write .lint:checknode ../../../../scripts/biome.cjs check .testbun testprebuildcontractspec-bun-build prebuildtypechecktsgo --noEmit