diff --git a/AGENTS.md b/AGENTS.md index edb47e0..e1a003f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,11 +99,12 @@ protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by ## Where things stand -Phase 3: `@pegma/billing-core` (ledger collection, `(eventAt, eventId)` +Phase 4: `@pegma/billing-core` (ledger collection, `(eventAt, eventId)` watermark, effective-watermark guard, lifecycle-rank tie-break, declared `sticky` / `firstWins` combinators, checkout reservation, snapshot -reconciliation). Nothing is published. `@pegma/billing-stripe` is Phase 4 -— do not create that package here yet. +reconciliation) and `@pegma/billing-stripe` (Stripe event and snapshot +translation). Nothing is published. Phase 5 is the first-consumer +`repo.js` swap — do not implement that here. Siblings: [spine](https://github.com/pegma-dev/spine), [storage-core](https://github.com/pegma-dev/storage-core), diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7069dc1..3d0584b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,9 +10,9 @@ Thank you for helping improve Billing Core. violate (arrival-order application, payment processing, entitlements, receipt dedup, invoicing/tax/metering, or storing card data / payloads / amounts). -- If a proposal needs this package to process payments or to create a - provider adapter before a consumer exists, say so explicitly — those are - the changes the design cannot absorb. +- If a proposal needs this package to process payments, verify webhook + signatures, resolve entitlements, or swap a host `repo.js`, say so + explicitly — those are the changes the design cannot absorb. ## Local development diff --git a/README.md b/README.md index 808d665..3d8701b 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,9 @@ hosts: the durable record of what a customer's subscription **is**, maintained correctly under out-of-order webhook delivery. > [!IMPORTANT] -> Pegma is in early `0.x` development. `@pegma/billing-core` Phase 3 is -> in-tree and unpublished. No public API is stable. +> Pegma is in early `0.x` development. `@pegma/billing-core` and +> `@pegma/billing-stripe` Phase 4 are in-tree and unpublished. No public +> API is stable. ## The part everyone gets wrong @@ -29,13 +30,13 @@ makes that impossible: - periodic **snapshot reconciliation** that repairs field drift without disturbing the dedup identity of the events themselves. -Phase 3 ships the watermark, the effective-watermark guard, +Phase 4 ships the watermark, the effective-watermark guard, lifecycle-rank arbitration, declared ledger invariants (`sticky`, -`firstWins`), the checkout reservation, and snapshot reconciliation. -The Stripe adapter is a later phase. The core knows lifecycle states, not -Stripe's vocabulary. And the data boundary is absolute: the ledger stores -provider identifiers and derived state — never a card number, a raw -payload, or an amount. +`firstWins`), the checkout reservation, snapshot reconciliation, and +Stripe event/snapshot translation. The core knows lifecycle states, not +Stripe's vocabulary — `@pegma/billing-stripe` is the translation. And +the data boundary is absolute: the ledger stores provider identifiers +and derived state — never a card number, a raw payload, or an amount. Not here, on purpose: payment processing and checkout flows, entitlement resolution ([Authorization Core](https://github.com/pegma-dev/authorization-core)'s @@ -56,10 +57,8 @@ application. | Package | Role | Phase | | ----------------------- | ------------------------------------------------------- | ----- | -| `@pegma/billing-core` | Ledger, watermark, rank, invariants, reservation, sweep | 3 | -| `@pegma/billing-stripe` | Event and snapshot translation | later | - -The Stripe adapter package is not created until Phase 4. +| `@pegma/billing-core` | Ledger, watermark, rank, invariants, reservation, sweep | 4 | +| `@pegma/billing-stripe` | Event and snapshot translation | 4 | ## Constraint that shapes everything diff --git a/SECURITY.md b/SECURITY.md index 1560881..1ac2f23 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,7 +4,7 @@ This project is in early `0.x` development and is not published yet. Security fixes apply to the latest reviewed source until the first -advertised release of `@pegma/billing-core`. +advertised release of `@pegma/billing-core` and `@pegma/billing-stripe`. ## Reporting a vulnerability diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index 953d196..dfe6414 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,7 +2,7 @@ ## Status -**Stage:** Phase 3 — snapshot reconciliation in-tree. Nothing is +**Stage:** Phase 4 — Stripe adapter in-tree. Nothing is published. (`0.1.0`, unpublished.) **Extraction source:** the RetireGolden account API's subscription ledger — @@ -176,10 +176,15 @@ reservation with its read-winner-back semantics and TTL expiry. The sweep, the domain CAS token, the always-write freshness rule — with the delayed-intermediate-webhook scenario pinned as a named test. -### Phase 4 — the Stripe adapter +### Phase 4 — the Stripe adapter (this tree) -Translation from Stripe events and subscription snapshots, against the -reference application's real event corpus. +Translation from Stripe events and subscription snapshots into +`LedgerEvent` / snapshot fetches. The core stays provider-agnostic. +Signature verification stays with the host; the vendor client stays +behind the adapter. Named consumers are RetireGolden.org (Stripe +subscriptions) and Exsimplify (Stripe Checkout today; the adapter still +translates subscription and event shapes). Their private internals stay +out of this tree. ### Phase 5 — first consumer @@ -191,10 +196,9 @@ acceptance bar. ## Timing -Phase 3 is implemented in-tree. Later phases remain gated: the Stripe -adapter (Phase 4) waits until a named consumer needs it. Phase 5 (first -consumer cutover) stays gated on that application's operational calendar -— never swap code under a soak or mid-migration. +Phase 4 is implemented in-tree. Phase 5 (first consumer cutover) stays +gated on that application's operational calendar — never swap code under +a soak or mid-migration. ## Open questions diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 3cfa5b0..e8da150 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -1,16 +1,17 @@ # Release operations -`@pegma/billing-core` publishes only from a stable GitHub release. Merging a -pull request never publishes, and the workflow has no manual-dispatch or -npm-token fallback. +`@pegma/billing-core` and `@pegma/billing-stripe` publish only from a +stable GitHub release. Merging a pull request never publishes, and the +workflow has no manual-dispatch or npm-token fallback. ## Required external configuration Before the first release through this workflow: -- configure `@pegma/billing-core` on npm with the GitHub Actions trusted - publisher `pegma-dev/billing-core`, workflow `publish.yml`, environment - `npm-publish`, and allowed action `npm publish`; +- configure `@pegma/billing-core` and `@pegma/billing-stripe` on npm with + the GitHub Actions trusted publisher `pegma-dev/billing-core`, workflow + `publish.yml`, environment `npm-publish`, and allowed action + `npm publish`; - create the GitHub `npm-publish` environment. A second reviewer is not required under Pegma's single-maintainer policy; - create the repository Actions variable `RELEASE_ALLOWED_SIGNERS` containing @@ -25,7 +26,8 @@ remaining traditional npm publish tokens. ## Release procedure -The version in `packages/billing-core/package.json` is the release version. +The versions in `packages/billing-core/package.json` and +`packages/billing-stripe/package.json` are the release versions. Change it through an ordinary reviewed pull request and run the complete gate on Node 22 and 24. diff --git a/packages/billing-core/README.md b/packages/billing-core/README.md index ed8af78..353725f 100644 --- a/packages/billing-core/README.md +++ b/packages/billing-core/README.md @@ -88,6 +88,5 @@ clobber fresher fields. `snapshotAt` never jumps into a later Unix second than the sampled bound, so same-second webhooks still get lifecycle-rank arbitration. The watermark identity is never touched. -Phase 3 is the arbitration core, combinators, reservation, and snapshot -reconciliation. The Stripe adapter is a later phase — do not import it -from this package. +Phase 4 keeps this package provider-agnostic. Import Stripe translation +from `@pegma/billing-stripe`, not from here. diff --git a/packages/billing-stripe/LICENSE b/packages/billing-stripe/LICENSE new file mode 100644 index 0000000..897032a --- /dev/null +++ b/packages/billing-stripe/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 RetireGolden, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/billing-stripe/README.md b/packages/billing-stripe/README.md new file mode 100644 index 0000000..eea515f --- /dev/null +++ b/packages/billing-stripe/README.md @@ -0,0 +1,90 @@ +# `@pegma/billing-stripe` + +Stripe event and snapshot translation for +[`@pegma/billing-core`](https://github.com/pegma-dev/billing-core). The +ledger stays provider-agnostic. This adapter maps Stripe event types and +subscription objects onto `LedgerEvent` / snapshot fetches. + +> [!IMPORTANT] +> Pegma is in early `0.x` development. This package's public API is unstable. + +```ts +import { createBillingLedger } from "@pegma/billing-core"; +import { createStripeBillingAdapter } from "@pegma/billing-stripe"; +import { createMemoryStore } from "@pegma/storage-core"; + +const ledger = createBillingLedger({ + store: createMemoryStore(), + clock: { now: () => "2026-08-15T16:00:00.000Z" }, +}); + +const stripe = createStripeBillingAdapter({ + client: { + retrieveSubscription: (id) => hostStripe.subscriptions.retrieve(id), + }, +}); + +// Host verifies the webhook signature, then: +const event = stripe.translateEvent(verifiedStripeEvent); +if (event !== null) { + await ledger.apply(accountId, event); +} + +await ledger.reconcile(accountId, stripe.fetchSnapshot); +``` + +The host verifies Stripe signatures and binds a customer to an account +id. This package never calls `constructEvent`, never processes a +payment, and never resolves entitlements. The vendor client stays behind +`retrieveSubscription`. + +Translation copies provider identifiers and derived state only — never +card data, raw payloads, line items, or amounts, even when those fields +are present on the Stripe object. + +## Lifecycle mapping + +| Stripe `status` | Ledger `LifecycleStatus` | +| -------------------- | ------------------------ | +| `incomplete` | `incomplete` | +| `incomplete_expired` | `canceled` | +| `trialing` | `trialing` | +| `active` | `active` | +| `past_due` | `past_due` | +| `canceled` | `canceled` | +| `unpaid` | `unpaid` | +| `paused` | `unpaid` | + +`incomplete_expired` is a finished first-invoice failure. `paused` is +non-granting and still live; it maps to `unpaid` so a same-second +`active` cannot resurrect it. Unknown Stripe statuses are dropped, not +coerced into a grant. + +`event.id` and `event.created` become the ledger watermark +`(eventId, eventAt)`. Arrival order is not an input. A same-second +Stripe `canceled` and `active` are ranked by the core: canceled wins in +either delivery order. + +Checkout Session and Invoice objects translate only when they carry an +**expanded** Subscription. A bare `sub_…` id is not enough to write +derived state — fetch the subscription through the snapshot port. + +`plan` defaults to the Price `lookup_key`. Pass `planFromPrice` to map a +Price id to a host plan name. Do not put customer-specific price tables +in this package. + +## What this is not + +- Payment processing, Checkout UI, or Customer Portal orchestration +- Webhook signature verification (host) or receipt dedup + ([`@pegma/webhooks`](https://github.com/pegma-dev/webhooks)) +- Entitlement resolution + ([`@pegma/authorization-stripe`](https://github.com/pegma-dev/authorization-core)) +- A host `repo.js` swap (Phase 5) + +Named consumers of this translation are RetireGolden.org (Stripe +subscriptions) and Exsimplify (Stripe Checkout today; the adapter still +translates subscription and event shapes for the ledger). Their private +account internals stay out of this tree. + +Phase 4 is in-tree and unpublished. diff --git a/packages/billing-stripe/package.json b/packages/billing-stripe/package.json new file mode 100644 index 0000000..af7b903 --- /dev/null +++ b/packages/billing-stripe/package.json @@ -0,0 +1,43 @@ +{ + "name": "@pegma/billing-stripe", + "version": "0.1.0", + "description": "Stripe event and snapshot translation for the Pegma billing ledger.", + "license": "MIT", + "type": "module", + "sideEffects": false, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist/**/*.d.ts", + "dist/**/*.d.ts.map", + "dist/**/*.js", + "dist/**/*.js.map" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "engines": { + "node": ">=22" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/pegma-dev/billing-core.git", + "directory": "packages/billing-stripe" + }, + "dependencies": { + "@pegma/billing-core": "0.1.0", + "@pegma/spine": "0.1.2" + }, + "devDependencies": { + "@pegma/storage-core": "0.4.0" + }, + "scripts": { + "build": "tsc -p tsconfig.json", + "check": "tsc -p tsconfig.json --noEmit", + "prepack": "pnpm run build" + } +} diff --git a/packages/billing-stripe/src/index.test.ts b/packages/billing-stripe/src/index.test.ts new file mode 100644 index 0000000..e197c61 --- /dev/null +++ b/packages/billing-stripe/src/index.test.ts @@ -0,0 +1,715 @@ +import { + createBillingLedger, + decideLedgerApplication, + type ApplicationDecision, + type LedgerRecord, +} from "@pegma/billing-core"; +import { createMemoryStore } from "@pegma/storage-core"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { + createStripeBillingAdapter, + createStripeSnapshotFetcher, + STRIPE_LIFECYCLE_STATUS, + stripeSubscriptionFromObject, + translateStripeEvent, + translateStripeLifecycleStatus, + translateStripeSubscription, +} from "./index.js"; + +const SECOND = 1_723_737_600; +const SECOND_ISO = "2024-08-15T16:00:00.000Z"; +const PERIOD_START = 1_722_513_600; +const PERIOD_END = 1_725_192_000; +const PERIOD_START_ISO = "2024-08-01T12:00:00.000Z"; +const PERIOD_END_ISO = "2024-09-01T12:00:00.000Z"; +const TRIAL_START = 1_722_427_200; +const TRIAL_END = 1_723_737_600; + +function stripeSubscription( + overrides: Record = {}, +): Record { + return { + id: "sub_123", + object: "subscription", + customer: "cus_123", + status: "active", + cancel_at_period_end: false, + current_period_start: PERIOD_START, + current_period_end: PERIOD_END, + trial_start: null, + trial_end: null, + items: { + object: "list", + data: [ + { + id: "si_123", + object: "subscription_item", + price: { + id: "price_pro", + object: "price", + lookup_key: "pro", + unit_amount: 9900, + }, + }, + ], + }, + latest_invoice: { + id: "in_secret", + amount_paid: 9900, + lines: { data: [{ amount: 9900, description: "Pro" }] }, + }, + default_payment_method: { + id: "pm_card", + card: { last4: "4242", brand: "visa" }, + }, + ...overrides, + }; +} + +function stripeEvent( + type: string, + object: unknown, + overrides: Record = {}, +): Record { + return { + id: "evt_123", + object: "event", + type, + created: SECOND, + data: { object }, + ...overrides, + }; +} + +function expectedSnapshot(overrides: Record = {}) { + return { + status: "active", + providerCustomerId: "cus_123", + providerSubscriptionId: "sub_123", + providerPriceId: "price_pro", + plan: "pro", + periodStartAt: PERIOD_START_ISO, + periodEndAt: PERIOD_END_ISO, + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + ...overrides, + }; +} + +function assertNoForbiddenFields(value: object): void { + const serialized = JSON.stringify(value); + expect(serialized).not.toMatch(/4242|unit_amount|amount_paid|last4|visa/u); + expect(value).not.toHaveProperty("amount"); + expect(value).not.toHaveProperty("card"); + expect(value).not.toHaveProperty("payload"); + expect(value).not.toHaveProperty("line_items"); + expect(value).not.toHaveProperty("latest_invoice"); + expect(value).not.toHaveProperty("default_payment_method"); +} + +describe("translateStripeLifecycleStatus", () => { + it("maps Stripe statuses onto ledger statuses", () => { + expect(translateStripeLifecycleStatus("incomplete")).toBe("incomplete"); + expect(translateStripeLifecycleStatus("incomplete_expired")).toBe( + "canceled", + ); + expect(translateStripeLifecycleStatus("trialing")).toBe("trialing"); + expect(translateStripeLifecycleStatus("active")).toBe("active"); + expect(translateStripeLifecycleStatus("past_due")).toBe("past_due"); + expect(translateStripeLifecycleStatus("canceled")).toBe("canceled"); + expect(translateStripeLifecycleStatus("unpaid")).toBe("unpaid"); + expect(translateStripeLifecycleStatus("paused")).toBe("unpaid"); + }); + + it("refuses unknown or non-string statuses instead of inventing a grant", () => { + expect(translateStripeLifecycleStatus("paused_pending")).toBeNull(); + expect(translateStripeLifecycleStatus("active ")).toBeNull(); + expect(translateStripeLifecycleStatus(null)).toBeNull(); + expect(translateStripeLifecycleStatus(1)).toBeNull(); + }); + + it("keeps the published mapping table aligned with the translator", () => { + for (const [stripe, ledger] of Object.entries(STRIPE_LIFECYCLE_STATUS)) { + expect(translateStripeLifecycleStatus(stripe)).toBe(ledger); + } + }); +}); + +describe("translateStripeSubscription", () => { + it("copies identifiers and derived state only", () => { + const snapshot = translateStripeSubscription(stripeSubscription()); + expect(snapshot).toEqual(expectedSnapshot()); + assertNoForbiddenFields(snapshot!); + }); + + it("reads an expanded customer and a price id string", () => { + const snapshot = translateStripeSubscription( + stripeSubscription({ + customer: { id: "cus_expanded", object: "customer", email: "a@b.c" }, + items: { + data: [{ price: "price_string" }], + }, + }), + ); + expect(snapshot).toMatchObject({ + providerCustomerId: "cus_expanded", + providerPriceId: "price_string", + plan: null, + }); + expect(JSON.stringify(snapshot)).not.toContain("a@b.c"); + }); + + it("reads period bounds from the first subscription item when the top-level fields are absent", () => { + const snapshot = translateStripeSubscription( + stripeSubscription({ + current_period_start: undefined, + current_period_end: undefined, + items: { + data: [ + { + current_period_start: PERIOD_START, + current_period_end: PERIOD_END, + price: { id: "price_pro", lookup_key: "pro" }, + }, + ], + }, + }), + ); + expect(snapshot).toMatchObject({ + periodStartAt: PERIOD_START_ISO, + periodEndAt: PERIOD_END_ISO, + }); + }); + + it("translates trial bounds and cancel-at-period-end", () => { + const snapshot = translateStripeSubscription( + stripeSubscription({ + status: "trialing", + trial_start: TRIAL_START, + trial_end: TRIAL_END, + cancel_at_period_end: true, + }), + ); + expect(snapshot).toMatchObject({ + status: "trialing", + trialStartAt: "2024-07-31T12:00:00.000Z", + trialEndAt: SECOND_ISO, + cancelAtPeriodEnd: true, + }); + }); + + it("lets the host map a price id to a plan name", () => { + const snapshot = translateStripeSubscription(stripeSubscription(), { + planFromPrice: (priceId) => (priceId === "price_pro" ? "founding" : null), + }); + expect(snapshot?.plan).toBe("founding"); + }); + + it("returns null for a bare subscription id or an unknown status", () => { + expect(translateStripeSubscription("sub_123")).toBeNull(); + expect( + translateStripeSubscription(stripeSubscription({ status: "mystery" })), + ).toBeNull(); + expect(translateStripeSubscription({ object: "customer" })).toBeNull(); + }); + + it("extracts an expanded subscription from a Checkout Session and an Invoice", () => { + const subscription = stripeSubscription({ status: "trialing" }); + expect( + translateStripeSubscription({ + id: "cs_123", + object: "checkout.session", + status: "complete", + mode: "subscription", + subscription, + amount_total: 9900, + }), + ).toMatchObject({ status: "trialing", providerSubscriptionId: "sub_123" }); + expect( + translateStripeSubscription({ + id: "in_123", + object: "invoice", + status: "paid", + subscription, + amount_paid: 9900, + }), + ).toMatchObject({ status: "trialing", providerSubscriptionId: "sub_123" }); + expect( + translateStripeSubscription({ + id: "in_parent", + object: "invoice", + status: "open", + parent: { subscription_details: { subscription } }, + }), + ).toMatchObject({ status: "trialing", providerSubscriptionId: "sub_123" }); + expect( + stripeSubscriptionFromObject({ + id: "cs_bare", + object: "checkout.session", + status: "complete", + subscription: "sub_123", + }), + ).toBeNull(); + }); + + it("does not treat a PaymentIntent or other id+status object as a Subscription", () => { + expect( + stripeSubscriptionFromObject({ + id: "pi_123", + object: "payment_intent", + status: "canceled", + customer: "cus_123", + }), + ).toBeNull(); + expect( + translateStripeSubscription({ + id: "pi_123", + object: "payment_intent", + status: "canceled", + customer: "cus_123", + }), + ).toBeNull(); + expect( + stripeSubscriptionFromObject({ + id: "cs_123", + object: "checkout.session", + status: "complete", + }), + ).toBeNull(); + expect( + stripeSubscriptionFromObject({ + id: "in_123", + object: "invoice", + status: "paid", + }), + ).toBeNull(); + }); +}); + +describe("translateStripeEvent", () => { + it("uses the event id and created second as the watermark", () => { + const event = translateStripeEvent( + stripeEvent("customer.subscription.updated", stripeSubscription()), + ); + expect(event).toEqual({ + eventId: "evt_123", + eventAt: SECOND_ISO, + ...expectedSnapshot(), + }); + assertNoForbiddenFields(event!); + }); + + it("translates each subscription event type", () => { + for (const type of [ + "customer.subscription.created", + "customer.subscription.updated", + "customer.subscription.deleted", + "customer.subscription.paused", + "customer.subscription.resumed", + "customer.subscription.pending_update_applied", + "customer.subscription.pending_update_expired", + ]) { + const status = + type === "customer.subscription.deleted" + ? "canceled" + : type === "customer.subscription.paused" + ? "paused" + : "active"; + const event = translateStripeEvent( + stripeEvent(type, stripeSubscription({ status })), + ); + expect(event?.eventId).toBe("evt_123"); + expect(event?.status).toBe(STRIPE_LIFECYCLE_STATUS[status]); + } + }); + + it("translates checkout.session.completed when the subscription is expanded", () => { + const event = translateStripeEvent( + stripeEvent("checkout.session.completed", { + id: "cs_123", + object: "checkout.session", + status: "complete", + mode: "subscription", + customer: "cus_123", + subscription: stripeSubscription({ status: "active" }), + amount_total: 9900, + }), + ); + expect(event).toMatchObject({ + eventId: "evt_123", + eventAt: SECOND_ISO, + status: "active", + providerSubscriptionId: "sub_123", + }); + expect(event?.providerSubscriptionId).not.toBe("cs_123"); + assertNoForbiddenFields(event!); + }); + + it("translates invoice.paid when the subscription is expanded", () => { + const event = translateStripeEvent( + stripeEvent("invoice.paid", { + id: "in_123", + object: "invoice", + status: "paid", + customer: "cus_123", + subscription: stripeSubscription({ status: "active" }), + amount_paid: 9900, + }), + ); + expect(event).toMatchObject({ + eventId: "evt_123", + eventAt: SECOND_ISO, + status: "active", + providerSubscriptionId: "sub_123", + }); + expect(event?.providerSubscriptionId).not.toBe("in_123"); + }); + + it("does not write a PaymentIntent id as providerSubscriptionId", () => { + const event = translateStripeEvent( + stripeEvent("payment_intent.canceled", { + id: "pi_123", + object: "payment_intent", + status: "canceled", + customer: "cus_123", + amount: 9900, + }), + ); + expect(event).toBeNull(); + expect( + translateStripeEvent( + stripeEvent("payment_intent.canceled", { + id: "pi_stripped", + status: "canceled", + customer: "cus_123", + }), + ), + ).toBeNull(); + }); + + it("still accepts a discriminator-less subscription-shaped retrieve", () => { + const { object: _object, ...stripped } = stripeSubscription(); + expect(translateStripeSubscription(stripped)).toMatchObject({ + providerSubscriptionId: "sub_123", + status: "active", + }); + }); + + it("ignores events that do not carry an expanded subscription", () => { + expect( + translateStripeEvent( + stripeEvent("checkout.session.completed", { + object: "checkout.session", + mode: "subscription", + subscription: "sub_123", + }), + ), + ).toBeNull(); + expect( + translateStripeEvent( + stripeEvent("charge.succeeded", { + object: "charge", + amount: 9900, + payment_method_details: { card: { last4: "4242" } }, + }), + ), + ).toBeNull(); + expect(translateStripeEvent({ object: "event", type: "ping" })).toBeNull(); + expect(translateStripeEvent(stripeSubscription())).toBeNull(); + }); +}); + +describe("same-second rank through translated Stripe events", () => { + it("keeps canceled over active in both arrival orders", () => { + const canceled = translateStripeEvent( + stripeEvent( + "customer.subscription.deleted", + stripeSubscription({ status: "canceled" }), + { id: "evt_canceled" }, + ), + ); + const active = translateStripeEvent( + stripeEvent( + "customer.subscription.updated", + stripeSubscription({ status: "active" }), + { id: "evt_active" }, + ), + ); + expect(canceled?.eventAt).toBe(active?.eventAt); + expect(canceled?.status).toBe("canceled"); + expect(active?.status).toBe("active"); + + for (const [accountId, order] of [ + ["acct_canceled_first", [canceled!, active!]], + ["acct_active_first", [active!, canceled!]], + ] as const) { + let current: LedgerRecord | null = null; + for (const incoming of order) { + const decision: ApplicationDecision = decideLedgerApplication( + current, + accountId, + incoming, + ); + if (decision.action === "write") { + current = decision.value; + } + } + expect(current).toMatchObject({ + status: "canceled", + eventId: "evt_canceled", + eventAt: SECOND_ISO, + }); + } + }); + + it("applies the same canceled-over-active outcome through the ledger", async () => { + const canceled = translateStripeEvent( + stripeEvent( + "customer.subscription.deleted", + stripeSubscription({ status: "canceled" }), + { id: "evt_canceled" }, + ), + )!; + const active = translateStripeEvent( + stripeEvent( + "customer.subscription.updated", + stripeSubscription({ status: "active" }), + { id: "evt_active" }, + ), + )!; + + for (const [accountId, order] of [ + ["acct_apply_canceled_first", [canceled, active]], + ["acct_apply_active_first", [active, canceled]], + ] as const) { + const ledger = createBillingLedger({ store: createMemoryStore() }); + for (const incoming of order) { + await ledger.apply(accountId, incoming); + } + expect(await ledger.get(accountId)).toMatchObject({ + status: "canceled", + eventId: "evt_canceled", + }); + } + }); + + it("lets a same-second paused Stripe status outrank active", () => { + const paused = translateStripeEvent( + stripeEvent( + "customer.subscription.paused", + stripeSubscription({ status: "paused" }), + { id: "evt_paused" }, + ), + )!; + const active = translateStripeEvent( + stripeEvent( + "customer.subscription.updated", + stripeSubscription({ status: "active" }), + { id: "evt_active" }, + ), + )!; + expect(paused.status).toBe("unpaid"); + + const afterActive = decideLedgerApplication(null, "acct_pause", active); + expect(afterActive.action).toBe("write"); + const afterPaused = decideLedgerApplication( + afterActive.action === "write" ? afterActive.value : null, + "acct_pause", + paused, + ); + expect(afterPaused).toMatchObject({ + action: "write", + value: { status: "unpaid", eventId: "evt_paused" }, + }); + }); +}); + +describe("createStripeSnapshotFetcher", () => { + const observed = { + accountId: "acct_snap", + providerCustomerId: "cus_123", + providerSubscriptionId: "sub_123", + providerPriceId: "price_stale", + status: "active" as const, + plan: "stale", + periodStartAt: PERIOD_START_ISO, + periodEndAt: PERIOD_END_ISO, + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + eventAt: SECOND_ISO, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + reservationId: null, + reservationExpiresAt: null, + reservationSeeded: false, + offerRedeemed: true, + }; + + it("retrieves the observed subscription and translates provider truth", async () => { + const retrieved: unknown[] = []; + const fetchSnapshot = createStripeSnapshotFetcher({ + client: { + async retrieveSubscription(id) { + retrieved.push(id); + return stripeSubscription({ + status: "past_due", + cancel_at_period_end: true, + items: { + data: [{ price: { id: "price_pro", lookup_key: "pro" } }], + }, + }); + }, + }, + }); + + const snapshot = await fetchSnapshot(observed); + expect(retrieved).toEqual(["sub_123"]); + expect(snapshot).toEqual( + expectedSnapshot({ + status: "past_due", + cancelAtPeriodEnd: true, + }), + ); + assertNoForbiddenFields(snapshot!); + }); + + it("returns null when the row has no subscription id or retrieve yields nothing translatable", async () => { + const fetchSnapshot = createStripeSnapshotFetcher({ + client: { + retrieveSubscription: async () => null, + }, + }); + expect( + await fetchSnapshot({ ...observed, providerSubscriptionId: null }), + ).toBeNull(); + expect(await fetchSnapshot(observed)).toBeNull(); + }); + + it("propagates retrieve failures so a sweep can fail closed", async () => { + const fetchSnapshot = createStripeSnapshotFetcher({ + client: { + retrieveSubscription: async () => { + throw new Error("stripe unavailable"); + }, + }, + }); + await expect(fetchSnapshot(observed)).rejects.toThrow("stripe unavailable"); + }); + + it("repairs drift through ledger.reconcile", async () => { + const store = createMemoryStore(); + const ledger = createBillingLedger({ + store, + clock: { now: () => "2024-08-15T16:05:00.000Z" }, + }); + const applied = translateStripeEvent( + stripeEvent("customer.subscription.created", stripeSubscription()), + )!; + await ledger.apply("acct_repair", applied); + + const fetchSnapshot = createStripeSnapshotFetcher({ + client: { + retrieveSubscription: async () => + stripeSubscription({ + status: "past_due", + items: { + data: [{ price: { id: "price_pro", lookup_key: "pro" } }], + }, + }), + }, + }); + const result = await ledger.reconcile("acct_repair", fetchSnapshot); + expect(result.written).toBe(true); + if (result.written) { + expect(result.record).toMatchObject({ + status: "past_due", + eventId: "evt_123", + eventAt: SECOND_ISO, + plan: "pro", + }); + } + }); + + it("logs account id and translation outcome, never payloads", async () => { + const lines: Array<{ message: string; extra: unknown }> = []; + const fetchSnapshot = createStripeSnapshotFetcher({ + logger: { + log(level, message, extra) { + expect(level).toBe("info"); + lines.push({ message, extra }); + }, + }, + client: { + retrieveSubscription: async () => stripeSubscription(), + }, + }); + await fetchSnapshot(observed); + expect(lines).toEqual([ + { + message: "Billing Stripe snapshot translated", + extra: { accountId: "acct_snap", translated: true }, + }, + ]); + expect(JSON.stringify(lines)).not.toMatch(/4242|unit_amount|payload/u); + }); +}); + +describe("createStripeBillingAdapter", () => { + it("exposes event translation and snapshot fetch behind the injected client", async () => { + const adapter = createStripeBillingAdapter({ + client: { + retrieveSubscription: async () => + stripeSubscription({ status: "canceled" }), + }, + }); + const event = adapter.translateEvent( + stripeEvent("customer.subscription.updated", stripeSubscription()), + ); + expect(event?.status).toBe("active"); + const snapshot = await adapter.fetchSnapshot({ + accountId: "acct_adapter", + providerCustomerId: "cus_123", + providerSubscriptionId: "sub_123", + providerPriceId: "price_pro", + status: "active", + plan: "pro", + periodStartAt: PERIOD_START_ISO, + periodEndAt: PERIOD_END_ISO, + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + eventAt: SECOND_ISO, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + reservationId: null, + reservationExpiresAt: null, + reservationSeeded: false, + offerRedeemed: true, + }); + expect(snapshot?.status).toBe("canceled"); + }); + + it("rejects a client without retrieveSubscription", () => { + expect(() => + createStripeSnapshotFetcher({ + client: {} as { retrieveSubscription: () => Promise }, + }), + ).toThrow(/retrieveSubscription/u); + }); +}); + +describe("package contract", () => { + it("does not call Date.now or verify signatures on the production path", () => { + const source = readFileSync(join(import.meta.dirname, "index.ts"), "utf8"); + expect(source).not.toMatch(/Date\.now\s*\(/u); + expect(source).not.toMatch(/constructEvent|stripe-signature/u); + expect(source).not.toMatch(/from ["']stripe["']/u); + }); +}); diff --git a/packages/billing-stripe/src/index.ts b/packages/billing-stripe/src/index.ts new file mode 100644 index 0000000..4d6f24d --- /dev/null +++ b/packages/billing-stripe/src/index.ts @@ -0,0 +1,419 @@ +import { noopLogger, type IsoTimestamp, type Logger } from "@pegma/spine"; +import type { + FetchLedgerSnapshot, + HostFields, + LedgerEvent, + LedgerRecord, + LedgerSnapshot, + LifecycleStatus, +} from "@pegma/billing-core"; + +/** + * Stripe subscription statuses that exist on both sides of the adapter. + * Extra Stripe statuses map onto the nearest ledger status by grant and + * terminal-ness — never by arrival order. + * + * `incomplete_expired` is a finished first-invoice failure → `canceled`. + * `paused` is non-granting and still live → `unpaid` (same rank as + * `canceled`, so a same-second `active` cannot resurrect it). + */ +export const STRIPE_LIFECYCLE_STATUS = { + incomplete: "incomplete", + incomplete_expired: "canceled", + trialing: "trialing", + active: "active", + past_due: "past_due", + canceled: "canceled", + unpaid: "unpaid", + paused: "unpaid", +} as const satisfies Record; + +export type StripeLifecycleStatus = keyof typeof STRIPE_LIFECYCLE_STATUS; + +/** Host mapping from a Stripe Price id to the ledger `plan` field. */ +export type PlanFromPrice = (priceId: string) => string | null; + +export interface StripeTranslateOptions { + readonly planFromPrice?: PlanFromPrice; +} + +/** + * Narrow retrieve port. The host's Stripe SDK stays behind this function — + * this package never imports `stripe` and never verifies signatures. + */ +export interface StripeSubscriptionClient { + retrieveSubscription(subscriptionId: string): Promise; +} + +export interface StripeSnapshotFetcherOptions extends StripeTranslateOptions { + readonly client: StripeSubscriptionClient; + readonly logger?: Logger; +} + +export interface StripeBillingAdapter { + translateEvent(event: unknown): LedgerEvent | null; + fetchSnapshot: FetchLedgerSnapshot; +} + +const STRIPE_STATUS_NAMES = new Set( + Object.keys(STRIPE_LIFECYCLE_STATUS), +); + +function isPlainRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function idFrom(value: unknown, objectName?: string): string | null { + if (typeof value === "string" && value.length > 0) { + return value; + } + if (!isPlainRecord(value)) { + return null; + } + if ( + objectName !== undefined && + value["object"] !== undefined && + value["object"] !== objectName + ) { + return null; + } + const id = value["id"]; + return typeof id === "string" && id.length > 0 ? id : null; +} + +function unixSecondsToIso(value: unknown): IsoTimestamp | null { + if (typeof value !== "number" || !Number.isFinite(value)) { + return null; + } + const milliseconds = Math.trunc(value) * 1000; + if (!Number.isSafeInteger(milliseconds)) { + return null; + } + return new Date(milliseconds).toISOString() as IsoTimestamp; +} + +function firstItem( + subscription: Record, +): Record | null { + const items = subscription["items"]; + if (!isPlainRecord(items)) { + return null; + } + const data = items["data"]; + if (!Array.isArray(data) || data.length === 0) { + return null; + } + const first = data[0]; + return isPlainRecord(first) ? first : null; +} + +function priceFromSubscription( + subscription: Record, +): Record | string | null { + const item = firstItem(subscription); + if (item === null) { + const legacy = subscription["plan"]; + return isPlainRecord(legacy) || typeof legacy === "string" ? legacy : null; + } + const price = item["price"]; + if (isPlainRecord(price) || typeof price === "string") { + return price; + } + const plan = item["plan"]; + return isPlainRecord(plan) || typeof plan === "string" ? plan : null; +} + +function priceIdFromSubscription( + subscription: Record, +): string | null { + return idFrom(priceFromSubscription(subscription), "price"); +} + +function lookupKeyFromPrice( + price: Record | string | null, +): string | null { + if (!isPlainRecord(price)) { + return null; + } + const lookupKey = price["lookup_key"]; + return typeof lookupKey === "string" && lookupKey.length > 0 + ? lookupKey + : null; +} + +function periodUnix( + subscription: Record, + field: "current_period_start" | "current_period_end", +): unknown { + const top = subscription[field]; + if (top != null) { + return top; + } + const item = firstItem(subscription); + return item?.[field]; +} + +function defaultPlan( + subscription: Record, + planFromPrice: PlanFromPrice | undefined, +): string | null { + const priceId = priceIdFromSubscription(subscription); + if (planFromPrice !== undefined && priceId !== null) { + const mapped = planFromPrice(priceId); + return mapped == null ? null : String(mapped); + } + return lookupKeyFromPrice(priceFromSubscription(subscription)); +} + +/** + * Maps a Stripe subscription status onto {@link LifecycleStatus}. + * Unknown names return null — the adapter does not invent a grant. + */ +export function translateStripeLifecycleStatus( + status: unknown, +): LifecycleStatus | null { + if (typeof status !== "string" || !STRIPE_STATUS_NAMES.has(status)) { + return null; + } + return STRIPE_LIFECYCLE_STATUS[status as StripeLifecycleStatus]; +} + +function subscriptionRecord(value: unknown): Record | null { + if (!isPlainRecord(value)) { + return null; + } + if (value["object"] === "subscription") { + return value; + } + // A present discriminator that is not "subscription" is never a + // Subscription — PaymentIntent, Checkout Session, Invoice, and similar + // all carry their own id + status. + if (value["object"] !== undefined) { + return null; + } + // Structural fallback only when Stripe omitted the discriminator, and + // only for a subscription-shaped id. A bare `pi_…` / `cs_…` / `in_…` + // with a lifecycle-like status must not become providerSubscriptionId. + const id = idFrom(value); + if ( + id !== null && + id.startsWith("sub_") && + typeof value["status"] === "string" + ) { + return value; + } + return null; +} + +/** + * Pulls an expanded Subscription out of a verified Stripe object. + * + * Accepts a Subscription (`object === "subscription"`), a Checkout + * Session whose `subscription` is expanded, or an Invoice whose + * `subscription` (or `parent.subscription_details.subscription`) is + * expanded. Wrappers are never themselves a Subscription, even when they + * have an id and a status. A bare id is not enough to write derived + * state — the host should snapshot-fetch. + */ +export function stripeSubscriptionFromObject( + value: unknown, +): Record | null { + const direct = subscriptionRecord(value); + if (direct !== null) { + return direct; + } + if (!isPlainRecord(value)) { + return null; + } + const nested = value["subscription"]; + const fromNested = subscriptionRecord(nested); + if (fromNested !== null) { + return fromNested; + } + const parent = value["parent"]; + if (isPlainRecord(parent)) { + const details = parent["subscription_details"]; + if (isPlainRecord(details)) { + const fromParent = subscriptionRecord(details["subscription"]); + if (fromParent !== null) { + return fromParent; + } + } + } + return null; +} + +function translateSubscriptionFields( + subscription: Record, + options: StripeTranslateOptions | undefined, +): Omit | null { + const status = translateStripeLifecycleStatus(subscription["status"]); + if (status === null) { + return null; + } + const providerSubscriptionId = idFrom(subscription); + if (providerSubscriptionId === null) { + return null; + } + return { + status, + providerCustomerId: idFrom(subscription["customer"], "customer"), + providerSubscriptionId, + providerPriceId: priceIdFromSubscription(subscription), + plan: defaultPlan(subscription, options?.planFromPrice), + periodStartAt: unixSecondsToIso( + periodUnix(subscription, "current_period_start"), + ), + periodEndAt: unixSecondsToIso( + periodUnix(subscription, "current_period_end"), + ), + trialStartAt: unixSecondsToIso(subscription["trial_start"]), + trialEndAt: unixSecondsToIso(subscription["trial_end"]), + cancelAtPeriodEnd: subscription["cancel_at_period_end"] === true, + }; +} + +/** + * Translates a Stripe Subscription (or an object that embeds one) into + * ledger snapshot fields. Identifiers and derived state only. + */ +export function translateStripeSubscription( + subscription: unknown, + options?: StripeTranslateOptions, +): LedgerSnapshot | null { + const record = stripeSubscriptionFromObject(subscription); + if (record === null) { + return null; + } + return translateSubscriptionFields(record, options) as LedgerSnapshot; +} + +function eventEnvelope(value: unknown): Record | null { + if (!isPlainRecord(value)) { + return null; + } + if (value["object"] === "event") { + return value; + } + if (typeof value["id"] === "string" && typeof value["type"] === "string") { + return value; + } + return null; +} + +function eventDataObject(event: Record): unknown { + const data = event["data"]; + if (!isPlainRecord(data)) { + return undefined; + } + return data["object"]; +} + +/** + * Translates a verified Stripe Event into a {@link LedgerEvent}. + * + * The host verifies the signature and supplies the parsed event. This + * function never inspects a signing secret. Events that do not carry an + * expanded subscription, or whose status has no ledger mapping, return + * null so the host can ignore them without applying invented state. + */ +export function translateStripeEvent( + event: unknown, + options?: StripeTranslateOptions, +): LedgerEvent | null { + const envelope = eventEnvelope(event); + if (envelope === null) { + return null; + } + const eventId = envelope["id"]; + if (typeof eventId !== "string" || eventId.length === 0) { + return null; + } + const eventAt = unixSecondsToIso(envelope["created"]); + if (eventAt === null) { + return null; + } + const fields = translateStripeSubscription( + eventDataObject(envelope), + options, + ); + if (fields === null) { + return null; + } + return { + eventId, + eventAt, + ...fields, + }; +} + +/** + * Builds a {@link FetchLedgerSnapshot} that retrieves the observed + * subscription through the injected client and translates it. + * + * A missing subscription id, a retrieve that returns null, or an + * untranslatable object yields null (`unavailable`). Retrieve errors + * propagate so a sweep can fail closed. + */ +export function createStripeSnapshotFetcher( + options: StripeSnapshotFetcherOptions, +): FetchLedgerSnapshot { + const retrieve = options.client.retrieveSubscription; + if (typeof retrieve !== "function") { + throw new TypeError( + "Stripe snapshot fetch requires client.retrieveSubscription.", + ); + } + const logger = options.logger ?? noopLogger; + const translateOptions: StripeTranslateOptions = { + ...(options.planFromPrice === undefined + ? {} + : { planFromPrice: options.planFromPrice }), + }; + + return async (observed: LedgerRecord) => { + const subscriptionId = observed.providerSubscriptionId; + if (subscriptionId === null || subscriptionId.length === 0) { + logger.log("info", "Billing Stripe snapshot ignored", { + accountId: observed.accountId, + translated: false, + }); + return null; + } + const retrieved = await retrieve.call(options.client, subscriptionId); + const snapshot = translateStripeSubscription( + retrieved, + translateOptions, + ); + logger.log( + "info", + snapshot === null + ? "Billing Stripe snapshot ignored" + : "Billing Stripe snapshot translated", + { + accountId: observed.accountId, + translated: snapshot !== null, + }, + ); + return snapshot; + }; +} + +/** + * Bundles event translation and snapshot fetch behind one injected client. + * Signature verification and account-id binding stay with the host. + */ +export function createStripeBillingAdapter( + options: StripeSnapshotFetcherOptions, +): StripeBillingAdapter { + const translateOptions: StripeTranslateOptions = { + ...(options.planFromPrice === undefined + ? {} + : { planFromPrice: options.planFromPrice }), + }; + return { + translateEvent: (event) => + translateStripeEvent(event, translateOptions), + fetchSnapshot: createStripeSnapshotFetcher(options), + }; +} diff --git a/packages/billing-stripe/tsconfig.json b/packages/billing-stripe/tsconfig.json new file mode 100644 index 0000000..30c0d9c --- /dev/null +++ b/packages/billing-stripe/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "tsBuildInfoFile": "tsconfig.tsbuildinfo", + "types": [] + }, + "include": ["src/**/*.ts"], + "exclude": ["src/**/*.test.ts"], + "references": [{ "path": "../billing-core" }] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7527b3a..4ad5956 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -44,6 +44,19 @@ importers: specifier: 0.4.0 version: 0.4.0 + packages/billing-stripe: + dependencies: + '@pegma/billing-core': + specifier: 0.1.0 + version: link:../billing-core + '@pegma/spine': + specifier: 0.1.2 + version: 0.1.2 + devDependencies: + '@pegma/storage-core': + specifier: 0.4.0 + version: 0.4.0 + packages: '@azure-rest/core-client@2.8.0': diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 699c9c6..0b998e6 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -29,6 +29,10 @@ export const RELEASE_PACKAGES = [ directory: "billing-core", name: "@pegma/billing-core", }, + { + directory: "billing-stripe", + name: "@pegma/billing-stripe", + }, ]; const RELEASE_NAMES = new Set(RELEASE_PACKAGES.map(({ name }) => name)); diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 8e296ec..a60cc58 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -36,6 +36,7 @@ describe("release package metadata", () => { it("keeps the exact public package inventory", () => { expect(RELEASE_PACKAGES.map(({ name }) => name)).toEqual([ "@pegma/billing-core", + "@pegma/billing-stripe", ]); }); @@ -55,9 +56,12 @@ describe("release package metadata", () => { expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ { name: "@pegma/billing-core", version: "0.1.0" }, + { name: "@pegma/billing-stripe", version: "0.1.0" }, ]); expect(manifests[0]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); expect(manifests[0]?.dependencies?.["@pegma/storage-core"]).toBe("0.4.0"); + expect(manifests[1]?.dependencies?.["@pegma/billing-core"]).toBe("0.1.0"); + expect(manifests[1]?.dependencies?.["@pegma/spine"]).toBe("0.1.2"); expect(packageVersion).toBe("0.1.0"); }); @@ -127,6 +131,19 @@ packages: "0.4.0", ), ).toBe(true); + expect( + lockDependencyMatches( + live["packages/billing-stripe"]?.dependencies?.["@pegma/billing-core"], + "0.1.0", + { workspace: true }, + ), + ).toBe(true); + expect( + lockDependencyMatches( + live["packages/billing-stripe"]?.dependencies?.["@pegma/spine"], + "0.1.2", + ), + ).toBe(true); }); it("matches each lockfile dependency to its own specifier and resolved version", () => { diff --git a/tsconfig.json b/tsconfig.json index ae6a283..1ccd2f2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,4 +1,7 @@ { "files": [], - "references": [{ "path": "./packages/billing-core" }] + "references": [ + { "path": "./packages/billing-core" }, + { "path": "./packages/billing-stripe" } + ] }