@voltro/plugin-billing 0.89.2 → 0.91.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +1943 -0
  2. package/README.md +0 -435
  3. package/THIRD-PARTY-NOTICES.md +22 -646
  4. package/dist/catalog.js +169 -70
  5. package/dist/custodyInventory.js +101 -65
  6. package/dist/dunning.js +14 -6
  7. package/dist/eventDelivery.js +14 -5
  8. package/dist/historicalUsage.js +94 -0
  9. package/dist/index.d.ts +777 -68
  10. package/dist/index.js +354 -233
  11. package/dist/invoiceHistoryJournal.js +204 -179
  12. package/dist/invoiceHistoryProgress.js +130 -106
  13. package/dist/invoiceHistoryWork.js +188 -186
  14. package/dist/invoicePaymentEpoch.js +145 -0
  15. package/dist/invoicePaymentObservation.js +64 -0
  16. package/dist/invoiceSnapshot.js +56 -46
  17. package/dist/invoiceStore.js +124 -90
  18. package/dist/paidInvoiceCoverage.js +84 -0
  19. package/dist/plans.js +15 -2
  20. package/dist/providers.js +149 -92
  21. package/dist/provision.js +84 -73
  22. package/dist/rpc.d.ts +53 -13
  23. package/dist/rpc.js +141 -78
  24. package/dist/service.js +1208 -722
  25. package/dist/stores.js +240 -148
  26. package/dist/stripeIdentity.js +17 -17
  27. package/dist/stripeInvoiceHistory.js +21 -21
  28. package/dist/stripeInvoicePayments.js +129 -0
  29. package/dist/stripeInvoiceSnapshot.js +65 -46
  30. package/dist/stripeProvider.js +570 -201
  31. package/dist/stripeRest.js +10 -10
  32. package/dist/subscriptionObservation.js +93 -0
  33. package/dist/subscriptionWriteStore.js +325 -0
  34. package/dist/table.js +75 -66
  35. package/dist/types.d.ts +415 -27
  36. package/dist/types.js +21 -4
  37. package/dist/web/index.d.ts +93 -3
  38. package/dist/web/index.js +76 -33
  39. package/dist/web/writeRequest.js +65 -0
  40. package/package.json +9 -9
@@ -0,0 +1,84 @@
1
+ import { BILLING_SUBSCRIPTIONS_TABLE as e } from "./table.js";
2
+ import { dataStoreCustomerStore as t } from "./customerStore.js";
3
+ import { dataStoreInvoiceStore as n } from "./invoiceStore.js";
4
+ import { captureSubscriptionObservation as r } from "./subscriptionObservation.js";
5
+ import { BillingError as i } from "./types.js";
6
+ import { Effect as a } from "effect";
7
+ import { and as o, eq as s } from "@voltro/database";
8
+ // src/paidInvoiceCoverage.ts
9
+ var c = () => new i({
10
+ source: "paidInvoiceCoverage",
11
+ message: "Current native paid invoice coverage requires reconciliation.",
12
+ transient: !0
13
+ }), l = (e) => {
14
+ let t = e.paymentObservation;
15
+ if (e.status !== "paid" || e.paidAt === null || t === null || e.amountDueMinor <= 0 || e.amountRemainingMinor !== 0 || e.amountPaidMinor < e.amountDueMinor || t.prePaymentCreditNotesMinor !== 0 || t.postPaymentCreditNotesMinor !== 0 || typeof t.invoiceTotalMinor != "number" || typeof t.startingBalanceMinor != "number" || typeof t.endingBalanceMinor != "number" || t.invoiceTotalMinor <= 0 || e.amountDueMinor < t.invoiceTotalMinor || t.startingBalanceMinor < 0 || t.endingBalanceMinor < 0 || e.lines.some((e) => e.amountMinor < 0)) return !1;
16
+ let n = 0n, r = /* @__PURE__ */ new Map();
17
+ for (let e of t.payments) {
18
+ if (e.status !== "paid") continue;
19
+ let t = e.cash;
20
+ if (t === null || e.amountPaidMinor === null || e.paidAt === null || !t.paid || !t.captured || t.disputed || t.refundedMinor !== 0 || t.refunds.some((e) => e.status !== "failed" && e.status !== "canceled") || t.providerPaymentIntentId !== null && t.paymentIntentStatus !== "succeeded") return !1;
21
+ let i = BigInt(e.amountPaidMinor), a = BigInt(t.capturedMinor), o = r.get(t.providerChargeId);
22
+ if (o !== void 0 && o.captured !== a) return !1;
23
+ let s = (o?.allocated ?? 0n) + i;
24
+ if (s > a) return !1;
25
+ r.set(t.providerChargeId, {
26
+ allocated: s,
27
+ captured: a
28
+ }), n += i;
29
+ }
30
+ return n >= BigInt(e.amountDueMinor) && n === BigInt(e.amountPaidMinor);
31
+ }, u = async (i, u, d) => {
32
+ if (!(d instanceof Date) || !Number.isSafeInteger(d.getTime()) || d.getTime() < 0) throw c();
33
+ let f = r(u.providerObservation, u);
34
+ if (f === null) return null;
35
+ let p = await i.query({
36
+ table: e,
37
+ predicate: o(s("tenantId", u.tenantId), s("provider", u.provider), s("providerSubscriptionId", u.providerSubscriptionId)),
38
+ order: [],
39
+ take: 2,
40
+ skip: void 0,
41
+ projection: void 0,
42
+ lock: "update"
43
+ }), m = p[0];
44
+ if (p.length !== 1 || m === void 0) throw c();
45
+ let h = (e) => e == null ? null : e instanceof Date ? e : new Date(String(e)), g = r(m.providerObservation, {
46
+ tenantId: String(m.tenantId),
47
+ provider: String(m.provider),
48
+ providerSubscriptionId: String(m.providerSubscriptionId),
49
+ plan: String(m.plan),
50
+ status: String(m.status),
51
+ quantity: Number(m.quantity),
52
+ currentPeriodStart: h(m.currentPeriodStart),
53
+ currentPeriodEnd: h(m.currentPeriodEnd),
54
+ cancelAt: h(m.cancelAt)
55
+ });
56
+ if (g === null || JSON.stringify(g) !== JSON.stringify(f) || Date.parse(f.observedAt) > d.getTime()) throw c();
57
+ let _ = {
58
+ providerAccountId: f.providerAccountId,
59
+ livemode: f.livemode
60
+ }, v = t(i), y = await a.runPromise(v.accountForTenant(u.tenantId));
61
+ if (y === null || y.provider !== u.provider || y.account.providerAccountId !== _.providerAccountId || y.account.livemode !== _.livemode) throw c();
62
+ let b = {
63
+ provider: u.provider,
64
+ account: _
65
+ }, x = await a.runPromise(v.getByProviderCustomerId(f.providerCustomerId, b));
66
+ if (x === null || x.tenantId !== u.tenantId || x.provider !== u.provider) throw c();
67
+ let S = {
68
+ tenantId: u.tenantId,
69
+ provider: u.provider,
70
+ ..._,
71
+ providerCustomerId: f.providerCustomerId
72
+ }, C = n(i), w = await a.runPromise(C.currentPaymentEpoch(S, { forUpdate: !0 }));
73
+ if (w === null || f.paymentHeadId !== w.headId || f.paymentEpoch !== w.epoch) return null;
74
+ let T = await a.runPromise(C.get({
75
+ ...S,
76
+ providerInvoiceId: f.providerLatestInvoiceId
77
+ }, { forUpdate: !0 }));
78
+ if (T === null || T.paymentEpoch?.headId !== w.headId || T.paymentEpoch.epoch !== w.epoch) return null;
79
+ let E = T.snapshot;
80
+ if (E.providerSubscriptionId !== u.providerSubscriptionId || E.currency !== f.currency || E.observedAt.getTime() > d.getTime() || !l(E)) return null;
81
+ for (let e of E.lines) if (!(e.providerSubscriptionId !== u.providerSubscriptionId || e.providerSubscriptionItemId !== f.providerSubscriptionItemId || e.providerPriceId !== f.providerPriceId || e.currency !== f.currency || e.proration !== !1 || e.amountMinor <= 0 || e.quantityDecimal === null || e.quantityDecimal.length > 64 || !/^[1-9][0-9]*(?:\.0+)?$/.test(e.quantityDecimal) || BigInt(e.quantityDecimal.split(".")[0]) !== BigInt(f.quantity) || e.periodStart.getTime() > d.getTime() || e.periodStart.getTime() !== Date.parse(f.currentPeriodStart) || e.periodEnd.getTime() !== Date.parse(f.currentPeriodEnd))) return new Date(e.periodEnd.getTime());
82
+ return null;
83
+ };
84
+ export { u as paidInvoiceCoverageInTransaction };
package/dist/plans.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import { DEFAULT_PLAN as e } from "./types.js";
2
2
  // src/plans.ts
3
3
  var t = (e) => e === void 0 ? 0 : e === "unlimited" ? Infinity : e, n = (e) => {
4
- let n = /* @__PURE__ */ new Map();
5
- for (let [t, r] of Object.entries(e)) r.priceId !== void 0 && n.set(r.priceId, t);
4
+ let n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
5
+ for (let [t, i] of Object.entries(e)) if (i.priceId !== void 0 && n.set(i.priceId, t), i.seatPriceId !== void 0 || i.includedSeats !== void 0) {
6
+ if (i.priceId === void 0 || i.seatPriceId === void 0 || i.includedSeats === void 0 || !Number.isSafeInteger(i.includedSeats) || i.includedSeats < 1 || i.seatPriceId === i.priceId) throw TypeError(`billingPlugin: plan '${t}' needs priceId, seatPriceId and a positive whole includedSeats together.`);
7
+ r.set(t, {
8
+ includedSeats: i.includedSeats,
9
+ seatPriceId: i.seatPriceId
10
+ });
11
+ }
12
+ for (let [e, t] of r) if (n.has(t.seatPriceId)) throw TypeError(`billingPlugin: plan '${e}' seatPriceId is another plan's priceId.`);
6
13
  return {
7
14
  has: (t) => Object.prototype.hasOwnProperty.call(e, t),
8
15
  entitlementLimit: (n, r) => {
@@ -11,6 +18,12 @@ var t = (e) => e === void 0 ? 0 : e === "unlimited" ? Infinity : e, n = (e) => {
11
18
  },
12
19
  planForPriceId: (e) => n.get(e) ?? null,
13
20
  priceIdFor: (t) => e[t]?.priceId ?? null,
21
+ seatPricingFor: (e) => r.get(e) ?? null,
22
+ seatPricingForPriceId: (e) => {
23
+ let t = n.get(e);
24
+ return t === void 0 ? null : r.get(t) ?? null;
25
+ },
26
+ minimumSeatsFor: (e) => r.get(e)?.includedSeats ?? 1,
14
27
  meteredPriceIdsFor: (t) => e[t]?.meteredPriceIds ?? [],
15
28
  unitAmountFor: (t) => {
16
29
  let n = e[t]?.unitAmountMinor;
package/dist/providers.js CHANGED
@@ -1,35 +1,37 @@
1
1
  import { BillingError as e } from "./types.js";
2
- import { captureProviderAccount as t, captureProviderCustomer as n, providerIdentityError as r, sameProviderAccount as i } from "./providerIdentity.js";
3
- import { decodeInvoiceSnapshot as a, encodeInvoiceSnapshot as o, invoiceSnapshotError as s } from "./invoiceSnapshot.js";
4
- import { captureInvoiceHistoryInput as c, captureInvoiceHistoryPage as l, historyError as u, invoiceHistoryPreview as d } from "./invoiceHistory.js";
5
- import { STRIPE_WEBHOOK_EVENTS as f, normalizeStripeEvent as p, stripeProvider as m } from "./stripeProvider.js";
2
+ import { decodeInvoiceSnapshot as t, encodeInvoiceSnapshot as n, invoiceSnapshotError as r } from "./invoiceSnapshot.js";
3
+ import { captureProviderAccount as i, captureProviderCustomer as a, providerIdentityError as o, sameProviderAccount as s } from "./providerIdentity.js";
4
+ import { STRIPE_WEBHOOK_EVENTS as c, normalizeStripeEvent as l, stripeProvider as u } from "./stripeProvider.js";
5
+ import "./subscriptionObservation.js";
6
+ import { captureInvoiceHistoryInput as d, captureInvoiceHistoryPage as f, historyError as p, invoiceHistoryPreview as m } from "./invoiceHistory.js";
6
7
  import { Effect as h } from "effect";
8
+ import { bootRefusal as g } from "@voltro/runtime/boot-refusal";
7
9
  // src/providers.ts
8
- var g = (f) => {
9
- let p = t({
10
- providerAccountId: f?.accountId ?? "mock_" + globalThis.crypto.randomUUID(),
10
+ var _ = (c) => {
11
+ let l = i({
12
+ providerAccountId: c?.accountId ?? "mock_" + globalThis.crypto.randomUUID(),
11
13
  livemode: !1
12
- }), m = /* @__PURE__ */ new Map(), g = 0, _ = f?.baseUrl ?? "https://mock.billing.local", v = [], y = [], b = [], x = /* @__PURE__ */ new Map(), S = /* @__PURE__ */ new Map(), C = /* @__PURE__ */ new Map(), w = /* @__PURE__ */ new Map(), T = [], E = (t) => h.try({
14
+ }), u = /* @__PURE__ */ new Map(), g = 0, _ = c?.baseUrl ?? "https://mock.billing.local", v = [], y = [], b = [], x = /* @__PURE__ */ new Map(), S = /* @__PURE__ */ new Map(), C = /* @__PURE__ */ new Map(), w = /* @__PURE__ */ new Map(), T = [], E = (t) => h.try({
13
15
  try: () => {
14
- let e = c(t);
15
- if (!i(e.account, p)) throw u("The mock invoice history account differs.");
16
+ let e = d(t);
17
+ if (!s(e.account, l)) throw p("The mock invoice history account differs.");
16
18
  let n = T.filter((t) => t.providerCustomerId === e.providerCustomerId).slice().sort((e, t) => t.createdAt.getTime() - e.createdAt.getTime() || (e.providerInvoiceId < t.providerInvoiceId ? 1 : e.providerInvoiceId > t.providerInvoiceId ? -1 : 0)), r = e.cursor === void 0 ? -1 : n.findIndex((t) => t.providerInvoiceId === e.cursor?.afterInvoiceId);
17
- if (e.cursor !== void 0 && r < 0) throw u("The mock invoice cursor does not belong to this customer.");
18
- let a = n.slice(r + 1, r + 1 + e.limit), o = a[a.length - 1];
19
- return l(e, {
20
- account: p,
19
+ if (e.cursor !== void 0 && r < 0) throw p("The mock invoice cursor does not belong to this customer.");
20
+ let i = n.slice(r + 1, r + 1 + e.limit), a = i[i.length - 1];
21
+ return f(e, {
22
+ account: l,
21
23
  providerCustomerId: e.providerCustomerId,
22
- invoices: a,
23
- nextCursor: r + 1 + a.length < n.length && o !== void 0 ? {
24
- ...p,
24
+ invoices: i,
25
+ nextCursor: r + 1 + i.length < n.length && a !== void 0 ? {
26
+ ...l,
25
27
  providerCustomerId: e.providerCustomerId,
26
- afterInvoiceId: o.providerInvoiceId
28
+ afterInvoiceId: a.providerInvoiceId
27
29
  } : null,
28
30
  observedAt: j()
29
31
  });
30
32
  },
31
- catch: (t) => t instanceof e ? t : u()
32
- }), D = [], O = [], k = [], A = [], j = f?.now ?? (() => /* @__PURE__ */ new Date()), M = /* @__PURE__ */ new Map(), N = (e) => e.status === "open" && e.expiresAt.getTime() <= j().getTime() ? {
33
+ catch: (t) => t instanceof e ? t : p()
34
+ }), D = [], O = [], k = [], A = [], j = c?.now ?? (() => /* @__PURE__ */ new Date()), M = /* @__PURE__ */ new Map(), N = (e) => e.status === "open" && e.expiresAt.getTime() <= j().getTime() ? {
33
35
  ...e,
34
36
  status: "expired",
35
37
  url: null
@@ -51,66 +53,113 @@ var g = (f) => {
51
53
  ...r,
52
54
  ...t
53
55
  }), n;
54
- }, B = (e) => typeof e == "object" && !!e && typeof e._tag == "string";
56
+ }, B = (e) => typeof e == "object" && !!e && typeof e._tag == "string", V = /* @__PURE__ */ new Map(), H = null, U = (e) => {
57
+ let t = S.get(e), n = x.get(e);
58
+ return t === void 0 || n === void 0 ? null : {
59
+ ...t,
60
+ ...n,
61
+ writeOperationId: V.get(e) ?? null,
62
+ providerObservedAt: new Date(j().getTime()),
63
+ providerPlanItemId: t.providerPlanItemId ?? "mock-item:" + e
64
+ };
65
+ }, W = (t, n, r) => h.gen(function* () {
66
+ if (n === void 0) return yield* r;
67
+ let i = U(t);
68
+ if (i === null || n.itemId !== null && n.itemId !== i.providerPlanItemId || n.expectedPriceId !== null && !i.priceIds.includes(n.expectedPriceId)) return yield* n.notDispatched(), yield* h.fail(new e({
69
+ source: "mock",
70
+ message: "Original provider subscription/item is missing.",
71
+ transient: !1
72
+ }));
73
+ if (i.writeOperationId === n.id) return yield* n.applied(i), yield* h.fail(new e({
74
+ source: "mock",
75
+ message: "Execution already observed; read current subscription.",
76
+ transient: !0
77
+ }));
78
+ let a = H;
79
+ if (H = null, a === "notDispatched") return yield* n.notDispatched(), yield* h.fail(new e({
80
+ source: "mock",
81
+ message: "The write was refused before dispatch.",
82
+ transient: !1
83
+ }));
84
+ if (yield* n.beforeDispatch().pipe(h.catch((e) => n.notDispatched().pipe(h.andThen(h.fail(e))))), a === "rejected") return yield* n.rejected("StripeInvalidRequestError (resource_missing)"), yield* h.fail(new e({
85
+ source: "mock",
86
+ message: "StripeInvalidRequestError (resource_missing)",
87
+ transient: !1
88
+ }));
89
+ if (a === "unknown") return yield* h.fail(new e({
90
+ source: "mock",
91
+ message: "The provider did not answer.",
92
+ transient: !0
93
+ }));
94
+ let o = yield* r;
95
+ V.set(t, n.id);
96
+ let s = U(t);
97
+ return s === null ? yield* h.fail(new e({
98
+ source: "mock",
99
+ message: "Provider result is unconfirmed.",
100
+ transient: !0
101
+ })) : (yield* n.applied(s), o);
102
+ });
55
103
  return {
56
104
  name: "mock",
57
- fetchAccountIdentity: () => h.succeed(t(p)),
105
+ supportsNativeSubscriptionWrites: !0,
106
+ fetchAccountIdentity: () => h.succeed(i(l)),
58
107
  fetchCustomerSnapshot: (e) => h.try({
59
108
  try: () => {
60
- let a = t(e.account);
61
- if (!i(a, p)) throw r();
62
- let o = m.get(e.providerCustomerId);
63
- if (o === void 0) throw r();
64
- return n({
65
- ...o,
109
+ let t = i(e.account);
110
+ if (!s(t, l)) throw o();
111
+ let n = u.get(e.providerCustomerId);
112
+ if (n === void 0) throw o();
113
+ return a({
114
+ ...n,
66
115
  observedAt: j()
67
116
  });
68
117
  },
69
- catch: () => r()
118
+ catch: () => o()
70
119
  }),
71
120
  setCustomerSnapshot: (e) => {
72
- let t = n(e);
73
- if (!i(t.account, p)) throw r();
74
- m.set(t.providerCustomerId, t);
121
+ let t = a(e);
122
+ if (!s(t.account, l)) throw o();
123
+ u.set(t.providerCustomerId, t);
75
124
  },
76
125
  setInvoiceHistory: (e) => {
77
- if (!Array.isArray(e) || Object.keys(e).length !== e.length) throw u("The mock invoice history must be complete and dense.");
126
+ if (!Array.isArray(e) || Object.keys(e).length !== e.length) throw p("The mock invoice history must be complete and dense.");
78
127
  let t = /* @__PURE__ */ new Set(), n = e.map((e) => {
79
- if (t.has(e.providerInvoiceId)) throw u("The mock invoice history contains duplicate identities.");
128
+ if (t.has(e.providerInvoiceId)) throw p("The mock invoice history contains duplicate identities.");
80
129
  t.add(e.providerInvoiceId);
81
- let n = c({
82
- account: p,
130
+ let n = d({
131
+ account: l,
83
132
  providerCustomerId: e.providerCustomerId,
84
133
  limit: 1
85
- }), r = l(n, {
86
- account: p,
134
+ }), r = f(n, {
135
+ account: l,
87
136
  providerCustomerId: e.providerCustomerId,
88
137
  invoices: [e],
89
138
  nextCursor: null,
90
139
  observedAt: j()
91
140
  }).invoices[0];
92
- if (r === void 0) throw u();
141
+ if (r === void 0) throw p();
93
142
  return r;
94
143
  });
95
144
  T = Object.freeze(n);
96
145
  },
97
146
  setInvoiceSnapshot: (e) => {
98
- let t = o(e);
147
+ let t = n(e);
99
148
  w.set(e.providerInvoiceId, {
100
149
  customerId: e.providerCustomerId,
101
150
  encoded: t
102
151
  });
103
152
  },
104
- fetchInvoiceSnapshot: (t) => h.try({
153
+ fetchInvoiceSnapshot: (n) => h.try({
105
154
  try: () => {
106
- let e = w.get(t.providerInvoiceId);
107
- if (e === void 0) throw s("The mock provider has no detailed invoice evidence.");
108
- if (e.customerId !== t.providerCustomerId) throw s("The invoice belongs to a different mock billing customer.");
109
- return a(e.encoded);
155
+ let e = w.get(n.providerInvoiceId);
156
+ if (e === void 0) throw r("The mock provider has no detailed invoice evidence.");
157
+ if (e.customerId !== n.providerCustomerId) throw r("The invoice belongs to a different mock billing customer.");
158
+ return t(e.encoded);
110
159
  },
111
- catch: (t) => t instanceof e ? t : s("The mock invoice observation is invalid.")
160
+ catch: (t) => t instanceof e ? t : r("The mock invoice observation is invalid.")
112
161
  }),
113
- supportsMeteredUsage: f?.supportsMeteredUsage ?? !0,
162
+ supportsMeteredUsage: c?.supportsMeteredUsage ?? !0,
114
163
  pushed: v,
115
164
  updates: y,
116
165
  fetched: b,
@@ -124,6 +173,9 @@ var g = (f) => {
124
173
  L = structuredClone(e);
125
174
  },
126
175
  undeliveredReads: () => R,
176
+ failNextWrite: (e) => {
177
+ H = e;
178
+ },
127
179
  listUndeliveredEvents: (t) => h.try({
128
180
  try: () => {
129
181
  if (R += 1, !Number.isInteger(t.limit) || t.limit < 1 || t.limit > 100) throw Error("Invalid event page size.");
@@ -143,14 +195,14 @@ var g = (f) => {
143
195
  }),
144
196
  ensureCustomer: (e) => h.sync(() => {
145
197
  let t = I.get(e.tenantId);
146
- if (t !== void 0 && m.get(t)?.deleted === !1) return t;
147
- let r = `mock_cus_${e.tenantId}`, i = t === void 0 ? r : `${r}_${++g}`, a = n({
148
- account: p,
149
- providerCustomerId: i,
198
+ if (t !== void 0 && u.get(t)?.deleted === !1) return t;
199
+ let n = `mock_cus_${e.tenantId}`, r = t === void 0 ? n : `${n}_${++g}`, i = a({
200
+ account: l,
201
+ providerCustomerId: r,
150
202
  deleted: !1,
151
203
  observedAt: j()
152
204
  });
153
- return I.set(e.tenantId, i), m.set(i, a), P.push(e.tenantId), i;
205
+ return I.set(e.tenantId, r), u.set(r, i), P.push(e.tenantId), r;
154
206
  }),
155
207
  expireOpenCheckouts: (e) => h.sync(() => {
156
208
  F.push(e.providerCustomerId);
@@ -171,18 +223,11 @@ var g = (f) => {
171
223
  setCustomerEmail: (e, t) => {
172
224
  t === null ? C.delete(e) : C.set(e, t);
173
225
  },
174
- fetchSubscriptionSnapshot: (e) => h.sync(() => {
175
- b.push(e);
176
- let t = S.get(e), n = x.get(e);
177
- return t === void 0 || n === void 0 ? null : {
178
- ...t,
179
- ...n
180
- };
181
- }),
226
+ fetchSubscriptionSnapshot: (e) => h.sync(() => (b.push(e), U(e))),
182
227
  fetchSubscription: (e) => h.sync(() => (b.push(e), x.get(e) ?? null)),
183
228
  listSubscriptions: (e) => h.sync(() => [...S.values()].filter((t) => t.status !== "canceled" && (e.providerCustomerId === void 0 || t.providerCustomerId === e.providerCustomerId))),
184
229
  prepareSubscriptionClose: () => h.sync(() => ({ cancelAt: /* @__PURE__ */ new Date(Math.ceil(j().getTime() / 1e3) * 1e3 + 6e5) })),
185
- cancelSubscription: (t) => h.try({
230
+ cancelSubscription: (t) => W(t.providerSubscriptionId, t.operation, h.try({
186
231
  try: () => {
187
232
  D.push({
188
233
  providerSubscriptionId: t.providerSubscriptionId,
@@ -203,15 +248,15 @@ var g = (f) => {
203
248
  message: "A valid retained billing close operation is required.",
204
249
  transient: !1
205
250
  })
206
- }),
207
- resumeSubscription: (e) => h.sync(() => (O.push(e), z(e, { cancelAt: null }))),
251
+ })),
252
+ resumeSubscription: (e, t) => W(e, t, h.sync(() => (O.push(e), z(e, { cancelAt: null })))),
208
253
  addSubscriptionPrices: (e) => h.sync(() => {
209
254
  k.push({
210
255
  providerSubscriptionId: e.providerSubscriptionId,
211
256
  priceIds: e.priceIds
212
257
  });
213
258
  let t = S.get(e.providerSubscriptionId);
214
- t !== void 0 && z(e.providerSubscriptionId, { priceIds: [...t.priceIds, ...e.priceIds] });
259
+ t !== void 0 && z(e.providerSubscriptionId, { priceIds: [.../* @__PURE__ */ new Set([...t.priceIds, ...e.priceIds])] });
215
260
  }),
216
261
  customerEmail: (e) => h.sync(() => C.get(e) ?? null),
217
262
  createCheckoutSession: (t) => h.try({
@@ -279,59 +324,71 @@ var g = (f) => {
279
324
  reportUsage: (e) => h.sync(() => {
280
325
  v.push(e);
281
326
  }),
282
- updateSubscription: (e) => h.sync(() => (y.push(e), {
283
- plan: e.priceId ?? "mock-plan",
284
- quantity: e.quantity ?? 1,
285
- prorationMinor: 0,
286
- currency: "usd",
287
- currentPeriodStart: null,
288
- currentPeriodEnd: null
327
+ updateSubscription: (e) => W(e.providerSubscriptionId, e.operation, h.sync(() => {
328
+ y.push(e);
329
+ let t = S.get(e.providerSubscriptionId), n = e.operation?.plan ?? e.priceId ?? x.get(e.providerSubscriptionId)?.plan ?? "mock-plan", r = e.priceId !== void 0 && t !== void 0 ? [e.priceId, ...t.priceIds.slice(1)] : t?.priceIds, i = e.meteredPriceIds === void 0 || r === void 0 ? r : [.../* @__PURE__ */ new Set([...r.filter((t) => !(e.replacesMeteredPriceIds ?? []).includes(t)), ...e.meteredPriceIds])], a = z(e.providerSubscriptionId, {
330
+ plan: n,
331
+ ...e.quantity === void 0 ? {} : { quantity: e.quantity },
332
+ ...i !== void 0 && t !== void 0 && i !== t.priceIds ? { priceIds: i } : {}
333
+ });
334
+ return {
335
+ plan: a.plan ?? n,
336
+ quantity: a.quantity,
337
+ prorationMinor: null,
338
+ currency: "usd",
339
+ currentPeriodStart: a.currentPeriodStart,
340
+ currentPeriodEnd: a.currentPeriodEnd
341
+ };
289
342
  })),
290
- previewSubscriptionChange: (e) => h.succeed({
291
- plan: e.priceId ?? "mock-plan",
292
- quantity: e.quantity ?? 1,
293
- prorationMinor: 0,
294
- currency: "usd",
295
- currentPeriodStart: null,
296
- currentPeriodEnd: null
343
+ previewSubscriptionChange: (e) => h.sync(() => {
344
+ let t = x.get(e.providerSubscriptionId);
345
+ return {
346
+ plan: e.priceId === void 0 ? t?.plan ?? "mock-plan" : c?.planForPriceId?.(e.priceId) ?? e.priceId,
347
+ quantity: e.quantity ?? t?.quantity ?? 1,
348
+ prorationMinor: 0,
349
+ currency: "usd",
350
+ currentPeriodStart: t?.currentPeriodStart ?? null,
351
+ currentPeriodEnd: t?.currentPeriodEnd ?? null
352
+ };
297
353
  }),
298
354
  listInvoiceHistory: E,
299
355
  listInvoices: (e) => E({
300
- account: p,
356
+ account: l,
301
357
  providerCustomerId: e.providerCustomerId,
302
358
  limit: e.limit ?? 20
303
- }).pipe(h.map((e) => e.invoices.map(d))),
359
+ }).pipe(h.map((e) => e.invoices.map(m))),
304
360
  normalizeEvent: (e) => h.succeed(B(e) ? e : null)
305
361
  };
306
- }, _ = /* @__PURE__ */ new Set([
362
+ }, v = /* @__PURE__ */ new Set([
307
363
  "",
308
364
  "development",
309
365
  "dev",
310
366
  "test"
311
- ]), v = (e) => !_.has((e ?? "").trim().toLowerCase()), y = (e) => {
312
- if (v(e.env.NODE_ENV)) {
313
- if (e.resolvedName === "mock" && e.providerOption === void 0) throw Error("billingPlugin: no STRIPE_SECRET_KEY in a production boot — refusing to run the MOCK billing provider, which answers every charge and subscription call successfully and reaches nobody. Set STRIPE_SECRET_KEY, or declare `billingPlugin({ provider: 'mock' })` if this deployment does not sell.");
367
+ ]), y = (e) => !v.has((e ?? "").trim().toLowerCase()), b = (e) => {
368
+ if (y(e.env.NODE_ENV)) {
369
+ if (e.resolvedName === "mock" && e.providerOption === void 0) throw g("billingPlugin: no STRIPE_SECRET_KEY in a production boot — refusing to run the MOCK billing provider, which answers every charge and subscription call successfully and reaches nobody. Set STRIPE_SECRET_KEY, or declare `billingPlugin({ provider: 'mock' })` if this deployment does not sell.");
314
370
  if (e.resolvedName === "stripe") {
315
- if (e.webhookSecret === null || e.webhookSecret.trim() === "") throw Error("billingPlugin: Stripe in a production boot needs STRIPE_WEBHOOK_SECRET — without it no provider event can be verified, so subscriptions, cancellations and payments would never reach this app.");
316
- if (e.redirectOrigins === void 0 || e.redirectOrigins.length === 0) throw Error("billingPlugin: Stripe in a production boot needs `redirectOrigins` — the origins checkout and the customer portal may send a customer back to. Without it any URL a caller names is accepted.");
371
+ if (e.webhookSecret === null || e.webhookSecret.trim() === "") throw g("billingPlugin: Stripe in a production boot needs STRIPE_WEBHOOK_SECRET — without it no provider event can be verified, so subscriptions, cancellations and payments would never reach this app.");
372
+ if (e.redirectOrigins === void 0 || e.redirectOrigins.length === 0) throw g("billingPlugin: Stripe in a production boot needs `redirectOrigins` — the origins checkout and the customer portal may send a customer back to. Without it any URL a caller names is accepted.");
317
373
  }
318
374
  }
319
- }, b = (e) => {
375
+ }, x = (e) => {
320
376
  let { provider: t, env: n } = e;
321
377
  if (t !== void 0 && typeof t == "object") return t;
322
378
  if ((t ?? (n.STRIPE_SECRET_KEY ? "stripe" : "mock")) === "stripe") {
323
379
  let t = e.apiKey ?? n.STRIPE_SECRET_KEY;
324
380
  if (!t) throw Error("billingPlugin: provider 'stripe' needs an apiKey (option or STRIPE_SECRET_KEY env)");
325
- return m({
381
+ return u({
326
382
  apiKey: t,
327
- ...e.planForPriceId ? { planForPriceId: e.planForPriceId } : {}
383
+ ...e.planForPriceId ? { planForPriceId: e.planForPriceId } : {},
384
+ ...e.seatPricingForPriceId ? { seatPricingForPriceId: e.seatPricingForPriceId } : {}
328
385
  });
329
386
  }
330
- return g();
331
- }, x = (e) => e.name === "mock" ? [] : [{
387
+ return _({ ...e.planForPriceId ? { planForPriceId: e.planForPriceId } : {} });
388
+ }, S = (e) => e.name === "mock" ? [] : [{
332
389
  destination: e.name === "stripe" ? "api.stripe.com" : `runtime:the '${e.name}' billing provider`,
333
390
  purpose: "customers, subscriptions, checkout and metered usage",
334
391
  data: ["personal", "metadata"],
335
392
  disable: "without STRIPE_SECRET_KEY the mock provider answers, and nothing leaves (production refuses to boot on it)"
336
393
  }];
337
- export { f as STRIPE_WEBHOOK_EVENTS, y as assertBillingProductionReady, x as billingEgressOf, v as isProductionBoot, g as mockProvider, p as normalizeStripeEvent, b as resolveProvider, m as stripeProvider };
394
+ export { c as STRIPE_WEBHOOK_EVENTS, b as assertBillingProductionReady, S as billingEgressOf, y as isProductionBoot, _ as mockProvider, l as normalizeStripeEvent, x as resolveProvider, u as stripeProvider };