@voltro/plugin-billing 0.90.0 → 0.91.1

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.
package/dist/service.js CHANGED
@@ -1,13 +1,13 @@
1
- import { BillingClosurePending as e, BillingError as t, BillingService as n, EntitlementExceeded as r } from "./types.js";
2
- import { billingRequestStale as i } from "./subscriptionWriteStore.js";
3
- import { DUNNING_LOCK_STEP_ID as a, defaultDunningEmail as o, dueSteps as s, episodeKeyOf as c, evaluateBillingEntitlement as l, resolveDunningConfig as u } from "./dunning.js";
4
- import { assertInvoiceSnapshot as d, invoiceSnapshotError as f } from "./invoiceSnapshot.js";
5
- import { captureProviderAccount as p, sameProviderAccount as m } from "./providerIdentity.js";
6
- import { captureInvoiceHistoryInput as h, captureInvoiceHistoryPage as g, historyError as _ } from "./invoiceHistory.js";
7
- import { captureSubscriptionObservation as v, observeSubscriptionProvider as y, subscriptionReadbackHolds as b } from "./subscriptionObservation.js";
8
- import { evaluateEntitlement as ee } from "./entitlement.js";
9
- import { isLive as x, memoryStores as S } from "./stores.js";
10
- import { makeHistoricalUsageInvoicer as te } from "./historicalUsage.js";
1
+ import { captureSubscriptionObservation as e, observeSubscriptionProvider as t, subscriptionReadbackHolds as n } from "./subscriptionObservation.js";
2
+ import { billingRequestStale as r } from "./subscriptionWriteStore.js";
3
+ import { evaluateEntitlement as i } from "./entitlement.js";
4
+ import { assertInvoiceSnapshot as a, invoiceSnapshotError as o } from "./invoiceSnapshot.js";
5
+ import { captureProviderAccount as s, sameProviderAccount as c } from "./providerIdentity.js";
6
+ import { captureInvoiceHistoryInput as l, captureInvoiceHistoryPage as u, historyError as d } from "./invoiceHistory.js";
7
+ import { isLive as f, memoryStores as p } from "./stores.js";
8
+ import { makeHistoricalUsageInvoicer as m } from "./historicalUsage.js";
9
+ import { DUNNING_LOCK_STEP_ID as h, defaultDunningEmail as g, dueSteps as _, episodeKeyOf as v, evaluateBillingEntitlement as y, resolveDunningConfig as b } from "./dunning.js";
10
+ import { BillingClosurePending as ee, BillingError as x, BillingService as S, EntitlementExceeded as te } from "./types.js";
11
11
  import { Effect as C, Fiber as ne, Layer as w, Schedule as T } from "effect";
12
12
  import { createLogger as E } from "@voltro/logger";
13
13
  // src/service.ts
@@ -18,57 +18,57 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
18
18
  ]), ae = /* @__PURE__ */ new Set([...O, "incomplete"]), k = 6e4, A = 4, oe = (e) => e.pipe(C.retry({
19
19
  schedule: T.recurs(A),
20
20
  while: (e) => e.source === "subscriptionStore" && e.transient
21
- })), j = (e = /* @__PURE__ */ new Date()) => `${e.getUTCFullYear()}-${String(e.getUTCMonth() + 1).padStart(2, "0")}`, se = (e) => ({ stores: e ?? S() }), M = (e, t) => e.pipe(C.retry({
21
+ })), j = (e = /* @__PURE__ */ new Date()) => `${e.getUTCFullYear()}-${String(e.getUTCMonth() + 1).padStart(2, "0")}`, se = (e) => ({ stores: e ?? p() }), M = (e, t) => e.pipe(C.retry({
22
22
  schedule: T.recurs(Math.max(0, t - 1)),
23
23
  while: (e) => e.transient
24
- })), ce = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,99}$/, le = "usage key must be 1–100 characters of A–Z, a–z, 0–9, \"_\", \".\", \":\" or \"-\", starting with a letter or digit", N = (n) => {
25
- let { provider: S, plans: w } = n, T = n.attempts ?? 3, E = n.checkout, k = n.now ?? (() => /* @__PURE__ */ new Date()), A = n.invoiceHistoryHeadRescanMs ?? ie;
24
+ })), ce = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,99}$/, le = "usage key must be 1–100 characters of A–Z, a–z, 0–9, \"_\", \".\", \":\" or \"-\", starting with a letter or digit", N = (p) => {
25
+ let { provider: S, plans: w } = p, T = p.attempts ?? 3, E = p.checkout, k = p.now ?? (() => /* @__PURE__ */ new Date()), A = p.invoiceHistoryHeadRescanMs ?? ie;
26
26
  if (!Number.isSafeInteger(A) || A < 1e3 || A > 864e5) throw TypeError("Invoice-history head rescans require a whole interval from one second through one day");
27
- let N = (e, r, i) => C.gen(function* () {
28
- if (e.length === 0) return yield* C.fail(new t({
27
+ let N = (e, t, n) => C.gen(function* () {
28
+ if (e.length === 0) return yield* C.fail(new x({
29
29
  source: "billing",
30
30
  message: "no tenant on this call",
31
31
  transient: !1
32
32
  }));
33
- if (r !== "cancel" && (yield* P.stores.closures.getAccount(e)) !== null) return yield* C.fail(new t({
33
+ if (t !== "cancel" && (yield* P.stores.closures.getAccount(e)) !== null) return yield* C.fail(new x({
34
34
  source: "billing",
35
35
  message: "This billing account is closing. New paid actions are unavailable.",
36
36
  transient: !1
37
37
  }));
38
- if (r !== "cancel" && (yield* P.stores.subscriptionWrites.assertOpen(e)), n.admit !== void 0 && (yield* n.admit(e, r)), yield* R(e), i !== void 0) {
38
+ if (t !== "cancel" && (yield* P.stores.subscriptionWrites.assertOpen(e)), p.admit !== void 0 && (yield* p.admit(e, t)), yield* R(e), n !== void 0) {
39
39
  let t = yield* P.stores.customers.getByTenant(e);
40
- if (t === null || t.providerCustomerId !== i) return yield* C.fail(f("Checkout customer custody changed before dispatch or private URL replay."));
40
+ if (t === null || t.providerCustomerId !== n) return yield* C.fail(o("Checkout customer custody changed before dispatch or private URL replay."));
41
41
  }
42
- }), ue = n.redirectOrigins?.map((e) => new URL(e).origin), de = (e, n) => {
43
- let r = (e) => C.fail(new t({
42
+ }), ue = p.redirectOrigins?.map((e) => new URL(e).origin), de = (e, t) => {
43
+ let n = (e) => C.fail(new x({
44
44
  source: "billing",
45
- message: `${n} ${e}`,
45
+ message: `${t} ${e}`,
46
46
  transient: !1
47
- })), i;
47
+ })), r;
48
48
  try {
49
- i = new URL(e);
49
+ r = new URL(e);
50
50
  } catch {
51
- return r("is not an absolute URL");
51
+ return n("is not an absolute URL");
52
52
  }
53
- return i.protocol !== "https:" && i.protocol !== "http:" ? r("must be an http(s) URL") : ue !== void 0 && !ue.includes(i.origin) ? r(`must point at one of the configured redirect origins, not ${i.origin}`) : C.void;
54
- }, P = se(n.stores), F = n.dunning ?? u(void 0, {}), I, L = () => {
53
+ return r.protocol !== "https:" && r.protocol !== "http:" ? n("must be an http(s) URL") : ue !== void 0 && !ue.includes(r.origin) ? n(`must point at one of the configured redirect origins, not ${r.origin}`) : C.void;
54
+ }, P = se(p.stores), F = p.dunning ?? b(void 0, {}), I, L = () => {
55
55
  if (I !== void 0) return C.succeed(I);
56
56
  let e = S.fetchAccountIdentity?.bind(S);
57
- return e === void 0 ? C.fail(f("Account-qualified billing is unsupported by this provider.")) : e().pipe(C.flatMap((e) => C.try({
57
+ return e === void 0 ? C.fail(o("Account-qualified billing is unsupported by this provider.")) : e().pipe(C.flatMap((e) => C.try({
58
58
  try: () => {
59
59
  let t = Object.freeze({
60
60
  provider: S.name,
61
- account: p(e)
61
+ account: s(e)
62
62
  });
63
- if (I !== void 0 && !m(I.account, t.account)) throw f("The provider account changed during observation.");
63
+ if (I !== void 0 && !c(I.account, t.account)) throw o("The provider account changed during observation.");
64
64
  return I ??= t, I;
65
65
  },
66
- catch: () => f("A fixed provider account/mode is required.")
66
+ catch: () => o("A fixed provider account/mode is required.")
67
67
  })));
68
68
  }, R = (e) => L().pipe(C.flatMap((t) => P.stores.customers.assertAccount(e, t))), fe = (e) => L().pipe(C.flatMap((t) => P.stores.customers.reserveAccount(e, t))), pe = (e) => P.stores.customers.accountForTenant(e).pipe(C.flatMap((t) => t === null ? fe(e) : C.void)), z = (e) => R(e).pipe(C.andThen(P.stores.customers.getByTenant(e))), B = (e, t) => C.gen(function* () {
69
69
  let n = yield* L(), r = S.fetchCustomerSnapshot?.bind(S);
70
- if (r === void 0) return yield* C.fail(f("Positive provider customer evidence is required."));
71
- if ((yield* P.stores.customers.getByTenant(e)) === null && (yield* P.stores.subscriptions.listByTenant(e)).some((e) => x(e.status))) return yield* C.fail(f("A previous live subscription must be reconciled before customer relinking."));
70
+ if (r === void 0) return yield* C.fail(o("Positive provider customer evidence is required."));
71
+ if ((yield* P.stores.customers.getByTenant(e)) === null && (yield* P.stores.subscriptions.listByTenant(e)).some((e) => f(e.status))) return yield* C.fail(o("A previous live subscription must be reconciled before customer relinking."));
72
72
  let i = yield* M(r({
73
73
  account: n.account,
74
74
  providerCustomerId: t
@@ -78,65 +78,65 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
78
78
  tenantId: e,
79
79
  providerCustomerId: t
80
80
  }, i);
81
- }), me = (e) => P.stores.subscriptions.getByTenant(e).pipe(C.flatMap((t) => P.stores.customers.accountForTenant(e).pipe(C.flatMap((n) => t !== null && n === null ? C.fail(f("The retained subscription has no qualified billing account.")) : C.succeed(l(t, F, k(), e)))))), he = (e) => me(e).pipe(C.map((e) => e.plan)), ge = (e) => P.stores.subscriptions.getByTenant(e), _e = (e, t) => C.gen(function* () {
82
- if (n.resolveEntitlementLimit !== void 0) {
83
- let r = yield* n.resolveEntitlementLimit(e, t);
84
- if (r !== null) return r;
81
+ }), me = (e) => P.stores.subscriptions.getByTenant(e).pipe(C.flatMap((t) => P.stores.customers.accountForTenant(e).pipe(C.flatMap((n) => t !== null && n === null ? C.fail(o("The retained subscription has no qualified billing account.")) : C.succeed(y(t, F, k(), e)))))), he = (e) => me(e).pipe(C.map((e) => e.plan)), ge = (e) => P.stores.subscriptions.getByTenant(e), _e = (e, t) => C.gen(function* () {
82
+ if (p.resolveEntitlementLimit !== void 0) {
83
+ let n = yield* p.resolveEntitlementLimit(e, t);
84
+ if (n !== null) return n;
85
85
  }
86
- let r = yield* he(e);
87
- return w.entitlementLimit(r, t);
86
+ let n = yield* he(e);
87
+ return w.entitlementLimit(n, t);
88
88
  }), ve = (e, t, n) => C.gen(function* () {
89
- let r = yield* _e(e, t), i = yield* P.stores.usage.used(e, t, j(k()));
90
- return ee(t, r, i, n);
89
+ let r = yield* _e(e, t), a = yield* P.stores.usage.used(e, t, j(k()));
90
+ return i(t, r, a, n);
91
91
  }), ye = (e, t, n) => C.gen(function* () {
92
- let i = yield* _e(e, t);
93
- if (!Number.isFinite(i) || n <= 0) return;
94
- let a = j(k());
92
+ let r = yield* _e(e, t);
93
+ if (!Number.isFinite(r) || n <= 0) return;
94
+ let i = j(k());
95
95
  yield* pe(e);
96
- let o = yield* P.stores.usage.consume(e, t, a, n, i);
97
- if (!o.allowed) return yield* C.fail(new r({
96
+ let a = yield* P.stores.usage.consume(e, t, i, n, r);
97
+ if (!a.allowed) return yield* C.fail(new te({
98
98
  entitlement: t,
99
- limit: o.limit,
100
- used: o.used,
99
+ limit: a.limit,
100
+ used: a.used,
101
101
  cost: n
102
102
  }));
103
- }), be = (e, n, r) => ce.test(n) ? Number.isFinite(r) ? r <= 0 ? C.void : pe(e).pipe(C.andThen(P.stores.usage.increment(e, n, j(k()), r)), C.asVoid) : C.fail(new t({
103
+ }), be = (e, t, n) => ce.test(t) ? Number.isFinite(n) ? n <= 0 ? C.void : pe(e).pipe(C.andThen(P.stores.usage.increment(e, t, j(k()), n)), C.asVoid) : C.fail(new x({
104
104
  source: "billing",
105
- message: `usage quantity must be a finite number, got ${r}`,
105
+ message: `usage quantity must be a finite number, got ${n}`,
106
106
  transient: !1
107
- })) : C.fail(new t({
107
+ })) : C.fail(new x({
108
108
  source: "billing",
109
109
  message: le,
110
110
  transient: !1
111
111
  })), xe = (e) => C.gen(function* () {
112
- if (!ce.test(e.entitlementKey) || !(e.occurredAt instanceof Date) || !Number.isFinite(e.occurredAt.getTime()) || e.occurredAt.getTime() < 0 || !Number.isFinite(k().getTime())) return yield* C.fail(new t({
112
+ if (!ce.test(e.entitlementKey) || !(e.occurredAt instanceof Date) || !Number.isFinite(e.occurredAt.getTime()) || e.occurredAt.getTime() < 0 || !Number.isFinite(k().getTime())) return yield* C.fail(new x({
113
113
  source: "usageEvent",
114
114
  message: "Usage event requires a valid meter key and a completed occurrence timestamp.",
115
115
  transient: !1
116
116
  }));
117
- if (e.occurredAt.getTime() > k().getTime()) return yield* C.fail(new t({
117
+ if (e.occurredAt.getTime() > k().getTime()) return yield* C.fail(new x({
118
118
  source: "usageEvent",
119
119
  message: "Usage completion is ahead of this replica clock. Retry the same event after its completion time.",
120
120
  transient: !0
121
121
  }));
122
- let n = new Date(e.occurredAt);
123
- if ((yield* P.stores.customers.accountForTenant(e.tenantId)) === null) return yield* C.fail(f("Usage occurrence requires its already recorded original billing account."));
122
+ let t = new Date(e.occurredAt);
123
+ if ((yield* P.stores.customers.accountForTenant(e.tenantId)) === null) return yield* C.fail(o("Usage occurrence requires its already recorded original billing account."));
124
124
  yield* P.stores.usage.recordEvent({
125
125
  ...e,
126
- occurredAt: n,
127
- period: j(n)
126
+ occurredAt: t,
127
+ period: j(t)
128
128
  });
129
- }), V = () => new t({
129
+ }), V = () => new x({
130
130
  source: "billing",
131
131
  message: "Usage arrived after final billing dispatch was sealed. Financial reconciliation is required before account deletion.",
132
132
  transient: !1
133
- }), Se = (e) => P.stores.closures.getAccount(e).pipe(C.map((e) => e?.usageSealed === 1)), Ce = te({
133
+ }), Se = (e) => P.stores.closures.getAccount(e).pipe(C.map((e) => e?.usageSealed === 1)), Ce = m({
134
134
  provider: S,
135
135
  now: k,
136
136
  customerOf: (e) => z(e).pipe(C.map((e) => e?.providerCustomerId ?? null)),
137
- liveSubscriptionOf: (e) => P.stores.subscriptions.getByTenant(e).pipe(C.map((e) => e !== null && x(e.status) ? e.providerSubscriptionId : null)),
137
+ liveSubscriptionOf: (e) => P.stores.subscriptions.getByTenant(e).pipe(C.map((e) => e !== null && f(e.status) ? e.providerSubscriptionId : null)),
138
138
  sealed: Se
139
- }), we = (e, t) => P.stores.usage.markReported(e.tenantId, e.entitlementKey, e.period, t), H = (e) => new t({
139
+ }), we = (e, t) => P.stores.usage.markReported(e.tenantId, e.entitlementKey, e.period, t), H = (e) => new x({
140
140
  source: "billing",
141
141
  message: e,
142
142
  transient: !1
@@ -153,14 +153,14 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
153
153
  expected: n,
154
154
  from: r,
155
155
  through: e.used
156
- }), De = (e, n, r) => C.gen(function* () {
157
- if (n + 1 >= 8) return yield* C.fail(new t({
156
+ }), De = (e, t, n) => C.gen(function* () {
157
+ if (t + 1 >= 8) return yield* C.fail(new x({
158
158
  source: "billing",
159
159
  message: "Usage flush lost its dispatch claim repeatedly to concurrent flushes. Retry the flush.",
160
160
  transient: !0
161
161
  }));
162
- let i = (yield* P.stores.usage.pending()).find((t) => t.tenantId === e.tenantId && t.entitlementKey === e.entitlementKey && t.period === e.period);
163
- i !== void 0 && (yield* r(i, n + 1));
162
+ let r = (yield* P.stores.usage.pending()).find((t) => t.tenantId === e.tenantId && t.entitlementKey === e.entitlementKey && t.period === e.period);
163
+ r !== void 0 && (yield* n(r, t + 1));
164
164
  }), Oe = (e, t, n = 0) => C.gen(function* () {
165
165
  let r = e.reportedToProvider;
166
166
  if (e.meterDispatchedThrough > r && (yield* Te(e, t, r, e.meterDispatchedThrough), r = e.meterDispatchedThrough), !(e.used <= r)) {
@@ -220,250 +220,250 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
220
220
  }
221
221
  }), Me = (e) => C.gen(function* () {
222
222
  if (!S.supportsMeteredUsage) return;
223
- let n = yield* P.stores.usage.pending(), r = ke();
224
- for (let i of n) {
225
- if (e !== void 0 && i.tenantId !== e) continue;
226
- let n = i.used - i.reportedToProvider;
227
- if (n <= 0) continue;
228
- if (yield* Se(i.tenantId)) {
223
+ let t = yield* P.stores.usage.pending(), n = ke();
224
+ for (let r of t) {
225
+ if (e !== void 0 && r.tenantId !== e) continue;
226
+ let t = r.used - r.reportedToProvider;
227
+ if (t <= 0) continue;
228
+ if (yield* Se(r.tenantId)) {
229
229
  if (e !== void 0) return yield* C.fail(V());
230
- yield* C.logWarning("billing usage retained: final dispatch is sealed").pipe(C.annotateLogs({ tenantId: i.tenantId }));
230
+ yield* C.logWarning("billing usage retained: final dispatch is sealed").pipe(C.annotateLogs({ tenantId: r.tenantId }));
231
231
  continue;
232
232
  }
233
- if (i.period !== j(k())) {
233
+ if (r.period !== j(k())) {
234
234
  if (e !== void 0) {
235
- yield* je(i, r);
235
+ yield* je(r, n);
236
236
  continue;
237
237
  }
238
- yield* je(i, r).pipe(C.catch((e) => C.logWarning("billing usage of a closed month retained").pipe(C.annotateLogs({
239
- tenantId: i.tenantId,
240
- key: i.entitlementKey,
241
- period: i.period,
238
+ yield* je(r, n).pipe(C.catch((e) => C.logWarning("billing usage of a closed month retained").pipe(C.annotateLogs({
239
+ tenantId: r.tenantId,
240
+ key: r.entitlementKey,
241
+ period: r.period,
242
242
  reason: e.message
243
243
  }))));
244
244
  continue;
245
245
  }
246
- let a = yield* P.stores.customers.getByTenant(i.tenantId);
247
- if (a === null && S.usageRequiresCustomer === !0) {
248
- if (e !== void 0) return yield* C.fail(new t({
246
+ let i = yield* P.stores.customers.getByTenant(r.tenantId);
247
+ if (i === null && S.usageRequiresCustomer === !0) {
248
+ if (e !== void 0) return yield* C.fail(new x({
249
249
  source: "billing",
250
250
  message: "Final usage requires a confirmed provider customer before account closure.",
251
251
  transient: !0
252
252
  }));
253
253
  yield* C.logWarning("billing usage not flushed: no provider customer linked").pipe(C.annotateLogs({
254
- tenantId: i.tenantId,
255
- key: i.entitlementKey,
256
- pending: n
254
+ tenantId: r.tenantId,
255
+ key: r.entitlementKey,
256
+ pending: t
257
257
  }));
258
- } else yield* Oe(i, a?.providerCustomerId);
258
+ } else yield* Oe(r, i?.providerCustomerId);
259
259
  }
260
- }), Ne = () => Me(), U = (e) => C.fail(new t({
260
+ }), Ne = () => Me(), U = (e) => C.fail(new x({
261
261
  source: "billing",
262
262
  message: `tenant '${e}' already has a paying subscription — change its plan instead of checking out again`,
263
263
  transient: !1
264
- })), W = (e, t, n) => C.gen(function* () {
265
- if (!(yield* R(e))) return yield* C.fail(f("A qualified billing account is required before subscription writes."));
266
- let r = P.stores, i = yield* L(), a = yield* C.try({
267
- try: () => y({
264
+ })), W = (e, r, i) => C.gen(function* () {
265
+ if (!(yield* R(e))) return yield* C.fail(o("A qualified billing account is required before subscription writes."));
266
+ let a = P.stores, s = yield* L(), c = yield* C.try({
267
+ try: () => t({
268
268
  tenantId: e,
269
269
  provider: S.name,
270
- account: i.account,
271
- snapshot: t,
272
- expectedPriceId: t.plan === null ? null : w.priceIdFor(t.plan),
273
- expectedCurrency: w.currencyFor(t.plan ?? "free"),
270
+ account: s.account,
271
+ snapshot: r,
272
+ expectedPriceId: r.plan === null ? null : w.priceIdFor(r.plan),
273
+ expectedCurrency: w.currencyFor(r.plan ?? "free"),
274
274
  observedAt: k()
275
275
  }),
276
- catch: () => f("The current provider subscription binding could not be captured.")
276
+ catch: () => o("The current provider subscription binding could not be captured.")
277
277
  });
278
- if (a !== null) {
279
- let t = yield* r.customers.getByProviderCustomerId(a.providerCustomerId, i);
280
- if (t === null || t.tenantId !== e || P.stores !== r) return yield* C.fail(f("The provider subscription has no matching native customer custody."));
278
+ if (c !== null) {
279
+ let t = yield* a.customers.getByProviderCustomerId(c.providerCustomerId, s);
280
+ if (t === null || t.tenantId !== e || P.stores !== a) return yield* C.fail(o("The provider subscription has no matching native customer custody."));
281
281
  }
282
- if (t.status === "canceled" && t.plan === null) return yield* oe(C.gen(function* () {
283
- let n = (yield* r.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === t.providerSubscriptionId);
284
- if (n.length > 1) return yield* C.fail(f("The current subscription identity is ambiguous."));
285
- n[0] !== void 0 && (yield* r.subscriptions.patchBySubscription(e, t.providerSubscriptionId, { status: "canceled" }, n[0].statusEventAt));
282
+ if (r.status === "canceled" && r.plan === null) return yield* oe(C.gen(function* () {
283
+ let t = (yield* a.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === r.providerSubscriptionId);
284
+ if (t.length > 1) return yield* C.fail(o("The current subscription identity is ambiguous."));
285
+ t[0] !== void 0 && (yield* a.subscriptions.patchBySubscription(e, r.providerSubscriptionId, { status: "canceled" }, t[0].statusEventAt));
286
286
  }));
287
- if (yield* r.subscriptions.upsert({
287
+ if (yield* a.subscriptions.upsert({
288
288
  tenantId: e,
289
289
  provider: S.name,
290
- providerSubscriptionId: t.providerSubscriptionId,
291
- plan: t.plan ?? "free",
292
- status: t.status,
293
- quantity: t.quantity,
294
- currentPeriodStart: t.currentPeriodStart,
295
- currentPeriodEnd: t.currentPeriodEnd,
296
- cancelAt: t.cancelAt,
290
+ providerSubscriptionId: r.providerSubscriptionId,
291
+ plan: r.plan ?? "free",
292
+ status: r.status,
293
+ quantity: r.quantity,
294
+ currentPeriodStart: r.currentPeriodStart,
295
+ currentPeriodEnd: r.currentPeriodEnd,
296
+ cancelAt: r.cancelAt,
297
297
  pastDueSince: null,
298
- statusEventAt: n,
299
- providerObservation: a
300
- }), a !== null) {
301
- let i = (yield* r.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === t.providerSubscriptionId);
298
+ statusEventAt: i,
299
+ providerObservation: c
300
+ }), c !== null) {
301
+ let t = (yield* a.subscriptions.listByTenant(e)).filter((e) => e.provider === S.name && e.providerSubscriptionId === r.providerSubscriptionId);
302
302
  yield* C.try({
303
303
  try: () => {
304
- if (P.stores !== r || !b(i, a, n)) throw Error("unconfirmed");
304
+ if (P.stores !== a || !n(t, c, i)) throw Error("unconfirmed");
305
305
  },
306
- catch: () => f("The provider subscription observation was not read back exactly.", !0)
306
+ catch: () => o("The provider subscription observation was not read back exactly.", !0)
307
307
  });
308
308
  }
309
309
  }), Pe = (e) => C.gen(function* () {
310
- let { tenantId: n, plan: r, successUrl: i, cancelUrl: a } = e, o = e.authorize ?? (() => C.void), s = w.priceIdFor(r), c = e.quantity ?? w.minimumSeatsFor(r), l = (e) => C.fail(new t({
310
+ let { tenantId: t, plan: n, successUrl: r, cancelUrl: i } = e, a = e.authorize ?? (() => C.void), o = w.priceIdFor(n), s = e.quantity ?? w.minimumSeatsFor(n), c = (e) => C.fail(new x({
311
311
  source: "billing",
312
312
  message: e,
313
313
  transient: !1
314
314
  }));
315
- if (s === null) return yield* l("The selected plan has no provider checkout price.");
316
- if (!Number.isSafeInteger(c) || c < 1) return yield* l("Seat quantity must be a positive integer.");
317
- if (c < w.minimumSeatsFor(r)) return yield* l("The plan price already covers more seats than requested.");
318
- yield* N(n, "checkout"), yield* o(), yield* de(i, "successUrl"), yield* de(a, "cancelUrl");
319
- let u = yield* P.stores.subscriptions.getByTenant(n);
320
- if (u !== null && ae.has(u.status)) return yield* U(n);
321
- let d = [...new Set(w.meteredPriceIdsFor(r))].sort(), f = E?.adjustableQuantity === void 0 ? void 0 : {
315
+ if (o === null) return yield* c("The selected plan has no provider checkout price.");
316
+ if (!Number.isSafeInteger(s) || s < 1) return yield* c("Seat quantity must be a positive integer.");
317
+ if (s < w.minimumSeatsFor(n)) return yield* c("The plan price already covers more seats than requested.");
318
+ yield* N(t, "checkout"), yield* a(), yield* de(r, "successUrl"), yield* de(i, "cancelUrl");
319
+ let l = yield* P.stores.subscriptions.getByTenant(t);
320
+ if (l !== null && ae.has(l.status)) return yield* U(t);
321
+ let u = [...new Set(w.meteredPriceIdsFor(n))].sort(), d = E?.adjustableQuantity === void 0 ? void 0 : {
322
322
  min: E.adjustableQuantity.min,
323
323
  max: E.adjustableQuantity.max
324
- }, p = E?.trialDays, m = yield* C.tryPromise({
324
+ }, f = E?.trialDays, p = yield* C.tryPromise({
325
325
  try: async () => {
326
326
  let e = new TextEncoder().encode(JSON.stringify([
327
- n,
327
+ t,
328
328
  S.name,
329
- r,
329
+ n,
330
+ o,
331
+ u,
330
332
  s,
331
- d,
332
- c,
333
+ r,
333
334
  i,
334
- a,
335
- f ?? null,
336
- p ?? null
337
- ])), t = await globalThis.crypto.subtle.digest("SHA-256", e);
338
- return [...new Uint8Array(t)].map((e) => e.toString(16).padStart(2, "0")).join("");
335
+ d ?? null,
336
+ f ?? null
337
+ ])), a = await globalThis.crypto.subtle.digest("SHA-256", e);
338
+ return [...new Uint8Array(a)].map((e) => e.toString(16).padStart(2, "0")).join("");
339
339
  },
340
- catch: () => new t({
340
+ catch: () => new x({
341
341
  source: "billing",
342
342
  message: "Checkout request identity could not be established.",
343
343
  transient: !1
344
344
  })
345
345
  });
346
346
  for (let e = 0; e < 4; e++) {
347
- yield* N(n, "checkout"), yield* o(), yield* fe(n);
347
+ yield* N(t, "checkout"), yield* a(), yield* fe(t);
348
348
  let e = new Date(k());
349
- if (!Number.isFinite(e.getTime())) return yield* l("The checkout clock could not be confirmed.");
350
- let t = yield* P.stores.checkouts.reserve({
351
- tenantId: n,
349
+ if (!Number.isFinite(e.getTime())) return yield* c("The checkout clock could not be confirmed.");
350
+ let l = yield* P.stores.checkouts.reserve({
351
+ tenantId: t,
352
352
  provider: S.name,
353
- requestDigest: m,
354
- plan: r,
355
- quantity: c,
353
+ requestDigest: p,
354
+ plan: n,
355
+ quantity: s,
356
356
  createdAt: e,
357
357
  expiresAt: /* @__PURE__ */ new Date(Math.floor((e.getTime() + 36e5) / 1e3) * 1e3)
358
358
  });
359
- if (t.provider !== S.name) return yield* l("The checkout provider changed. Its previous operation needs reconciliation.");
360
- let u = t.providerCustomerId, h = yield* z(n);
361
- if (h !== null && (h.provider !== S.name || u !== null && h.providerCustomerId !== u)) return yield* l("The checkout customer binding changed. Its operation needs reconciliation.");
362
- if (t.requestDigest === m && u === null) {
363
- yield* N(n, "checkout"), yield* o(), u = h?.providerCustomerId ?? (yield* M(o().pipe(C.andThen(N(n, "checkout")), C.andThen(S.ensureCustomer({ tenantId: n }))), T));
364
- let e = yield* P.stores.checkouts.patch(t.id, { providerCustomerId: u });
365
- if (e.active !== 1 || e.providerCustomerId !== u) return yield* l("Checkout ownership changed during customer resolution.");
366
- let r = yield* z(n);
367
- if (r !== null && (r.provider !== S.name || r.providerCustomerId !== u)) return yield* l("The current customer binding requires reconciliation.");
368
- yield* o(), r === null && (yield* B(n, u));
359
+ if (l.provider !== S.name) return yield* c("The checkout provider changed. Its previous operation needs reconciliation.");
360
+ let m = l.providerCustomerId, h = yield* z(t);
361
+ if (h !== null && (h.provider !== S.name || m !== null && h.providerCustomerId !== m)) return yield* c("The checkout customer binding changed. Its operation needs reconciliation.");
362
+ if (l.requestDigest === p && m === null) {
363
+ yield* N(t, "checkout"), yield* a(), m = h?.providerCustomerId ?? (yield* M(a().pipe(C.andThen(N(t, "checkout")), C.andThen(S.ensureCustomer({ tenantId: t }))), T));
364
+ let e = yield* P.stores.checkouts.patch(l.id, { providerCustomerId: m });
365
+ if (e.active !== 1 || e.providerCustomerId !== m) return yield* c("Checkout ownership changed during customer resolution.");
366
+ let n = yield* z(t);
367
+ if (n !== null && (n.provider !== S.name || n.providerCustomerId !== m)) return yield* c("The current customer binding requires reconciliation.");
368
+ yield* a(), n === null && (yield* B(t, m));
369
369
  }
370
- if (u !== null) {
371
- let e = yield* z(n);
372
- if (e === null) yield* B(n, u);
373
- else if (e.providerCustomerId !== u) return yield* l("Checkout customer custody differs from the retained operation.");
370
+ if (m !== null) {
371
+ let e = yield* z(t);
372
+ if (e === null) yield* B(t, m);
373
+ else if (e.providerCustomerId !== m) return yield* c("Checkout customer custody differs from the retained operation.");
374
374
  }
375
375
  let g = yield* M(S.findCheckoutSession({
376
- tenantId: n,
377
- operationId: t.id,
378
- ...u === null ? {} : { providerCustomerId: u }
376
+ tenantId: t,
377
+ operationId: l.id,
378
+ ...m === null ? {} : { providerCustomerId: m }
379
379
  }), T), _ = g.receipt;
380
380
  if (_ !== null) {
381
- if (_.operationId !== t.id || _.tenantId !== n || _.providerCustomerId === null || u !== null && _.providerCustomerId !== u || _.expiresAt.getTime() !== t.expiresAt.getTime() || _.id === "") return yield* l("The provider checkout receipt does not match its retained operation.");
382
- if (u === null && (u = _.providerCustomerId, yield* P.stores.checkouts.patch(t.id, { providerCustomerId: u })), _.status === "expired") {
383
- yield* P.stores.checkouts.patch(t.id, {
381
+ if (_.operationId !== l.id || _.tenantId !== t || _.providerCustomerId === null || m !== null && _.providerCustomerId !== m || _.expiresAt.getTime() !== l.expiresAt.getTime() || _.id === "") return yield* c("The provider checkout receipt does not match its retained operation.");
382
+ if (m === null && (m = _.providerCustomerId, yield* P.stores.checkouts.patch(l.id, { providerCustomerId: m })), _.status === "expired") {
383
+ yield* P.stores.checkouts.patch(l.id, {
384
384
  phase: "expired",
385
385
  providerSessionId: _.id
386
386
  });
387
387
  continue;
388
388
  }
389
389
  if (_.status === "complete") {
390
- if (yield* P.stores.checkouts.patch(t.id, {
390
+ if (yield* P.stores.checkouts.patch(l.id, {
391
391
  phase: "completed",
392
392
  providerSessionId: _.id
393
- }), _.providerSubscriptionId === null) return yield* l("Completed checkout settlement is not yet confirmed.");
393
+ }), _.providerSubscriptionId === null) return yield* c("Completed checkout settlement is not yet confirmed.");
394
394
  if ((yield* M(S.fetchSubscription(_.providerSubscriptionId), T))?.status === "canceled") {
395
- yield* P.stores.checkouts.patch(t.id, { phase: "retired" });
395
+ yield* P.stores.checkouts.patch(l.id, { phase: "retired" });
396
396
  continue;
397
397
  }
398
- return yield* U(n);
398
+ return yield* U(t);
399
399
  }
400
- let e = yield* P.stores.checkouts.patch(t.id, {
400
+ let e = yield* P.stores.checkouts.patch(l.id, {
401
401
  phase: "ready",
402
402
  providerSessionId: _.id
403
403
  });
404
- return t.requestDigest === m ? _.url === null || g.observedAt !== null && g.observedAt.getTime() >= _.expiresAt.getTime() ? yield* l("The current checkout URL could not be confirmed.") : e.active !== 1 || e.phase !== "ready" ? yield* l("Checkout state changed before its URL could be returned.") : (yield* N(n, "checkout", u ?? void 0), { url: _.url }) : yield* l("Another checkout is still open for this organization.");
404
+ return l.requestDigest === p ? _.url === null || g.observedAt !== null && g.observedAt.getTime() >= _.expiresAt.getTime() ? yield* c("The current checkout URL could not be confirmed.") : e.active !== 1 || e.phase !== "ready" ? yield* c("Checkout state changed before its URL could be returned.") : (yield* N(t, "checkout", m ?? void 0), { url: _.url }) : yield* c("Another checkout is still open for this organization.");
405
405
  }
406
- if (g.observedAt !== null && g.observedAt.getTime() > t.expiresAt.getTime()) {
407
- yield* P.stores.checkouts.patch(t.id, { phase: "expired" });
406
+ if (g.observedAt !== null && g.observedAt.getTime() > l.expiresAt.getTime()) {
407
+ yield* P.stores.checkouts.patch(l.id, { phase: "expired" });
408
408
  continue;
409
409
  }
410
- if (t.requestDigest !== m) return yield* l("An earlier checkout request is unresolved. Check its current state first.");
411
- if (u === null || k().getTime() >= t.expiresAt.getTime()) return yield* l("The earlier checkout needs provider deadline/receipt reconciliation.");
412
- let v = (yield* M(S.listSubscriptions({ providerCustomerId: u }), T)).filter((e) => ae.has(e.status));
410
+ if (l.requestDigest !== p) return yield* c("An earlier checkout request is unresolved. Check its current state first.");
411
+ if (m === null || k().getTime() >= l.expiresAt.getTime()) return yield* c("The earlier checkout needs provider deadline/receipt reconciliation.");
412
+ let v = (yield* M(S.listSubscriptions({ providerCustomerId: m }), T)).filter((e) => ae.has(e.status));
413
413
  if (v.length > 0) {
414
- for (let e of v) yield* W(n, e, k());
415
- return yield* U(n);
414
+ for (let e of v) yield* W(t, e, k());
415
+ return yield* U(t);
416
416
  }
417
- let y = yield* P.stores.checkouts.patch(t.id, { phase: "creating" });
418
- if (y.active !== 1 || y.phase === "completed") return yield* l("Checkout state changed before provider dispatch.");
419
- yield* N(n, "checkout", u ?? void 0), yield* o(), yield* M(o().pipe(C.andThen(N(n, "checkout", u ?? void 0)), C.andThen(S.expireOpenCheckouts({
420
- providerCustomerId: u,
421
- exceptOperationId: t.id
422
- }))), T), yield* N(n, "checkout", u ?? void 0), yield* o();
423
- let b = yield* M(o().pipe(C.andThen(N(n, "checkout", u ?? void 0)), C.andThen(S.createCheckoutSession({
424
- tenantId: n,
425
- priceId: s,
426
- meteredPriceIds: d,
427
- successUrl: i,
428
- cancelUrl: a,
429
- quantity: c,
430
- providerCustomerId: u,
431
- idempotencyKey: t.id,
432
- expiresAt: t.expiresAt,
433
- ...f === void 0 ? {} : { adjustableQuantity: f },
434
- ...p === void 0 ? {} : { trialDays: p }
417
+ let y = yield* P.stores.checkouts.patch(l.id, { phase: "creating" });
418
+ if (y.active !== 1 || y.phase === "completed") return yield* c("Checkout state changed before provider dispatch.");
419
+ yield* N(t, "checkout", m ?? void 0), yield* a(), yield* M(a().pipe(C.andThen(N(t, "checkout", m ?? void 0)), C.andThen(S.expireOpenCheckouts({
420
+ providerCustomerId: m,
421
+ exceptOperationId: l.id
422
+ }))), T), yield* N(t, "checkout", m ?? void 0), yield* a();
423
+ let b = yield* M(a().pipe(C.andThen(N(t, "checkout", m ?? void 0)), C.andThen(S.createCheckoutSession({
424
+ tenantId: t,
425
+ priceId: o,
426
+ meteredPriceIds: u,
427
+ successUrl: r,
428
+ cancelUrl: i,
429
+ quantity: s,
430
+ providerCustomerId: m,
431
+ idempotencyKey: l.id,
432
+ expiresAt: l.expiresAt,
433
+ ...d === void 0 ? {} : { adjustableQuantity: d },
434
+ ...f === void 0 ? {} : { trialDays: f }
435
435
  }))), T);
436
- if (b.operationId !== t.id || b.tenantId !== n || b.providerCustomerId !== u || b.expiresAt.getTime() !== t.expiresAt.getTime() || !b.id) return yield* l("Checkout creation returned an inconsistent provider receipt.");
436
+ if (b.operationId !== l.id || b.tenantId !== t || b.providerCustomerId !== m || b.expiresAt.getTime() !== l.expiresAt.getTime() || !b.id) return yield* c("Checkout creation returned an inconsistent provider receipt.");
437
437
  if (b.status === "expired") {
438
- yield* P.stores.checkouts.patch(t.id, {
438
+ yield* P.stores.checkouts.patch(l.id, {
439
439
  phase: "expired",
440
440
  providerSessionId: b.id
441
441
  });
442
442
  continue;
443
443
  }
444
- if (b.status === "complete") return yield* P.stores.checkouts.patch(t.id, {
444
+ if (b.status === "complete") return yield* P.stores.checkouts.patch(l.id, {
445
445
  phase: "completed",
446
446
  providerSessionId: b.id
447
- }), yield* U(n);
448
- if (b.url === null) return yield* l("Checkout creation returned no confirmed URL.");
449
- let ee = yield* P.stores.checkouts.patch(t.id, {
447
+ }), yield* U(t);
448
+ if (b.url === null) return yield* c("Checkout creation returned no confirmed URL.");
449
+ let ee = yield* P.stores.checkouts.patch(l.id, {
450
450
  phase: "ready",
451
451
  providerSessionId: b.id
452
452
  });
453
- return ee.active !== 1 || ee.phase !== "ready" ? yield* l("Checkout state changed before its URL could be returned.") : (yield* N(n, "checkout", u ?? void 0), { url: b.url });
453
+ return ee.active !== 1 || ee.phase !== "ready" ? yield* c("Checkout state changed before its URL could be returned.") : (yield* N(t, "checkout", m ?? void 0), { url: b.url });
454
454
  }
455
- return yield* l("Checkout operations changed concurrently. Check current billing state before retrying.");
456
- }), Fe = (e, n) => C.gen(function* () {
457
- yield* N(e, "portal"), yield* de(n, "returnUrl");
458
- let r = yield* z(e);
459
- return r === null ? yield* C.fail(new t({
455
+ return yield* c("Checkout operations changed concurrently. Check current billing state before retrying.");
456
+ }), Fe = (e, t) => C.gen(function* () {
457
+ yield* N(e, "portal"), yield* de(t, "returnUrl");
458
+ let n = yield* z(e);
459
+ return n === null ? yield* C.fail(new x({
460
460
  source: "billing",
461
461
  message: `no provider customer linked for tenant '${e}'`,
462
462
  transient: !1
463
463
  })) : yield* M(S.createPortalSession({
464
464
  tenantId: e,
465
- providerCustomerId: r.providerCustomerId,
466
- returnUrl: n
465
+ providerCustomerId: n.providerCustomerId,
466
+ returnUrl: t
467
467
  }), T);
468
468
  }), Ie = (e) => C.gen(function* () {
469
469
  if (F.resolveRecipient !== void 0) {
@@ -474,22 +474,22 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
474
474
  let t = yield* z(e);
475
475
  return t === null ? null : yield* S.customerEmail(t.providerCustomerId);
476
476
  }), Le = (e) => {
477
- let n = F.portalReturnUrl;
478
- return n === void 0 ? C.succeed(null) : C.try({
479
- try: () => typeof n == "string" ? n : n(e),
480
- catch: (e) => new t({
477
+ let t = F.portalReturnUrl;
478
+ return t === void 0 ? C.succeed(null) : C.try({
479
+ try: () => typeof t == "string" ? t : t(e),
480
+ catch: (e) => new x({
481
481
  source: "dunning",
482
482
  message: String(e?.message ?? e),
483
483
  transient: !1
484
484
  })
485
485
  }).pipe(C.flatMap((t) => Fe(e, t)), C.map((e) => e.url), C.catch(() => C.succeed(null)));
486
486
  }, Re = (e, t, n, r, i) => C.gen(function* () {
487
- let a = yield* Ie(e.tenantId).pipe(C.catch(() => C.succeed(null))), s = yield* Le(e.tenantId), c = t.lockedSince !== null, l = o({
487
+ let a = yield* Ie(e.tenantId).pipe(C.catch(() => C.succeed(null))), o = yield* Le(e.tenantId), s = t.lockedSince !== null, c = g({
488
488
  stepId: n,
489
- locked: c,
489
+ locked: s,
490
490
  graceEndsAt: i,
491
- portalUrl: s
492
- }), u = {
491
+ portalUrl: o
492
+ }), l = {
493
493
  stepId: n,
494
494
  tenantId: e.tenantId,
495
495
  to: a,
@@ -497,20 +497,20 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
497
497
  status: e.status,
498
498
  pastDueSince: r,
499
499
  graceEndsAt: i,
500
- locked: c,
500
+ locked: s,
501
501
  lockout: F.lockout,
502
- portalUrl: s,
503
- ...l
502
+ portalUrl: o,
503
+ ...c
504
504
  };
505
505
  D.info("billing dunning notice", {
506
506
  tenant: e.tenantId,
507
507
  step: n,
508
- locked: c,
508
+ locked: s,
509
509
  graceEndsAt: i.toISOString(),
510
510
  delivered: F.notify !== void 0 && a !== null
511
511
  });
512
- let d = F.notify;
513
- d !== void 0 && (yield* d(u).pipe(C.catchCause((t) => C.sync(() => {
512
+ let u = F.notify;
513
+ u !== void 0 && (yield* u(l).pipe(C.catchCause((t) => C.sync(() => {
514
514
  D.warn("billing dunning notify failed", {
515
515
  tenant: e.tenantId,
516
516
  step: n,
@@ -525,7 +525,7 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
525
525
  source: t.source,
526
526
  message: t.message
527
527
  }), null))));
528
- if (P.stores !== t) return yield* C.fail(f("Billing storage changed during observation.", !0));
528
+ if (P.stores !== t) return yield* C.fail(o("Billing storage changed during observation.", !0));
529
529
  let i = n;
530
530
  if (r !== null) {
531
531
  let a = k(), o = r.status === "pastDue" ? n.status === "pastDue" && n.pastDueSince !== null ? n.pastDueSince : a : null;
@@ -551,14 +551,14 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
551
551
  return i;
552
552
  }), G = (e) => C.gen(function* () {
553
553
  let t = P.stores;
554
- if (yield* R(e), P.stores !== t) return yield* C.fail(f("Billing storage changed during observation.", !0));
554
+ if (yield* R(e), P.stores !== t) return yield* C.fail(o("Billing storage changed during observation.", !0));
555
555
  let n = yield* oe(ze(e, t));
556
- if (n === null) return l(null, F, k(), e);
557
- let r = l(n, F, k(), e);
556
+ if (n === null) return y(null, F, k(), e);
557
+ let r = y(n, F, k(), e);
558
558
  if (!F.enabled || n.status !== "pastDue" || n.pastDueSince === null) return r;
559
- let i = n.pastDueSince, o = c(i), u = r.graceEndsAt ?? i, d = s(F.steps, i, k()).map((e) => e.id);
560
- r.lockedSince !== null && d.push(a);
561
- for (let t of d) (yield* P.stores.dunningNotices.claim(e, o, t, k())) && (yield* Re(n, r, t, i, u));
559
+ let i = n.pastDueSince, a = v(i), s = r.graceEndsAt ?? i, c = _(F.steps, i, k()).map((e) => e.id);
560
+ r.lockedSince !== null && c.push(h);
561
+ for (let t of c) (yield* P.stores.dunningNotices.claim(e, a, t, k())) && (yield* Re(n, r, t, i, s));
562
562
  return r;
563
563
  }), Be = () => C.gen(function* () {
564
564
  let e = yield* P.stores.subscriptions.listByStatus("pastDue"), t = 0;
@@ -596,32 +596,32 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
596
596
  }, He = (e) => C.gen(function* () {
597
597
  let t = yield* C.try({
598
598
  try: () => {
599
- let t = p(e);
600
- if (![e.providerCustomerId, e.providerEventId].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) throw f("Exact verified customer and correction identities are required.");
599
+ let t = s(e);
600
+ if (![e.providerCustomerId, e.providerEventId].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) throw o("Exact verified customer and correction identities are required.");
601
601
  return Object.freeze({
602
602
  ...t,
603
603
  providerCustomerId: e.providerCustomerId,
604
604
  providerEventId: e.providerEventId
605
605
  });
606
606
  },
607
- catch: () => f("The verified payment correction identity is invalid.")
607
+ catch: () => o("The verified payment correction identity is invalid.")
608
608
  }), n = P.stores, r = yield* L();
609
- if (!m(t, r.account)) return yield* C.fail(f("The correction belongs to another provider account or mode."));
609
+ if (!c(t, r.account)) return yield* C.fail(o("The correction belongs to another provider account or mode."));
610
610
  let i = yield* n.customers.getByProviderCustomerId(t.providerCustomerId, r);
611
- if (i === null || i.provider !== S.name) return yield* C.fail(f("Retained native customer custody is required before payment correction."));
612
- if (P.stores !== n) return yield* C.fail(f("Billing stores changed before payment correction.", !0));
611
+ if (i === null || i.provider !== S.name) return yield* C.fail(o("Retained native customer custody is required before payment correction."));
612
+ if (P.stores !== n) return yield* C.fail(o("Billing stores changed before payment correction.", !0));
613
613
  yield* n.invoices.invalidatePayments({
614
614
  tenantId: i.tenantId,
615
615
  provider: r.provider,
616
616
  ...r.account,
617
617
  providerCustomerId: i.providerCustomerId
618
618
  }, t.providerEventId);
619
- let a = yield* st(i), o = yield* n.customers.getByProviderCustomerId(t.providerCustomerId, r), s = yield* L();
620
- return P.stores !== n || !m(s.account, t) || o === null || o.id !== i.id || o.tenantId !== i.tenantId ? yield* C.fail(f("Native customer or provider custody changed during payment correction.", !0)) : a;
619
+ let a = yield* st(i), l = yield* n.customers.getByProviderCustomerId(t.providerCustomerId, r), u = yield* L();
620
+ return P.stores !== n || !c(u.account, t) || l === null || l.id !== i.id || l.tenantId !== i.tenantId ? yield* C.fail(o("Native customer or provider custody changed during payment correction.", !0)) : a;
621
621
  }), Ue = (e) => {
622
622
  if (e._tag === "customerUnlinked") return C.gen(function* () {
623
623
  let t = yield* L(), n = S.fetchCustomerSnapshot?.bind(S);
624
- if (n === void 0) return yield* C.fail(f("Positive customer deletion evidence is required."));
624
+ if (n === void 0) return yield* C.fail(o("Positive customer deletion evidence is required."));
625
625
  let r = yield* n({
626
626
  account: t.account,
627
627
  providerCustomerId: e.providerCustomerId
@@ -631,17 +631,17 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
631
631
  tenantId: i?.tenantId ?? null
632
632
  };
633
633
  });
634
- if (e._tag !== "invoicePaid" && e._tag !== "invoicePaymentFailed") return (e._tag === "customerLinked" ? C.void : z(e.tenantId).pipe(C.flatMap((e) => e === null ? C.fail(f("A qualified current customer is required before subscription events.")) : C.void))).pipe(C.andThen(Ve(e)), C.andThen(K(e)), C.as(e));
634
+ if (e._tag !== "invoicePaid" && e._tag !== "invoicePaymentFailed") return (e._tag === "customerLinked" ? C.void : z(e.tenantId).pipe(C.flatMap((e) => e === null ? C.fail(o("A qualified current customer is required before subscription events.")) : C.void))).pipe(C.andThen(Ve(e)), C.andThen(K(e)), C.as(e));
635
635
  let t = {
636
636
  ...e,
637
637
  occurredAt: e.occurredAt === null ? null : new Date(e.occurredAt)
638
638
  };
639
639
  return C.gen(function* () {
640
640
  let e = t.providerCustomerId;
641
- if (typeof e != "string" || e.length === 0 || e.trim() !== e) return yield* C.fail(f("An exact provider customer identity is required."));
641
+ if (typeof e != "string" || e.length === 0 || e.trim() !== e) return yield* C.fail(o("An exact provider customer identity is required."));
642
642
  let n = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
643
- if (n === null) return yield* C.fail(f("The invoice customer must be linked before reconciliation.", !0));
644
- if (n.provider !== S.name) return yield* C.fail(f("The invoice customer belongs to a different provider."));
643
+ if (n === null) return yield* C.fail(o("The invoice customer must be linked before reconciliation.", !0));
644
+ if (n.provider !== S.name) return yield* C.fail(o("The invoice customer belongs to a different provider."));
645
645
  let r = n.tenantId;
646
646
  yield* Y(r, t.providerInvoiceId, e);
647
647
  let i = {
@@ -654,142 +654,142 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
654
654
  }, a = yield* P.stores.customers.getByTenant(r);
655
655
  return n.retiredAt === null && a?.id === n.id && (yield* K(i)), i;
656
656
  });
657
- }, q = (e, n, r) => C.gen(function* () {
658
- let i = P.stores;
659
- if (S.supportsNativeSubscriptionWrites !== !0) return yield* C.fail(new t({
657
+ }, q = (n, r, i) => C.gen(function* () {
658
+ let a = P.stores;
659
+ if (S.supportsNativeSubscriptionWrites !== !0) return yield* C.fail(new x({
660
660
  source: "billing",
661
661
  message: "This provider does not support native single-dispatch subscription operations.",
662
662
  transient: !1
663
663
  }));
664
- let a = null;
665
- yield* r(), yield* N(e, n);
666
- let o = yield* i.subscriptions.getByTenant(e), s = yield* z(e), c = S.fetchSubscriptionSnapshot?.bind(S), l = () => new t({
664
+ let o = null;
665
+ yield* i(), yield* N(n, r);
666
+ let s = yield* a.subscriptions.getByTenant(n), l = yield* z(n), u = S.fetchSubscriptionSnapshot?.bind(S), d = () => new x({
667
667
  source: "billing",
668
668
  message: "The current owned subscription must be reconciled before this change can be confirmed.",
669
669
  transient: !0
670
670
  });
671
- if (o === null || s === null || c === void 0 || o.tenantId !== e || o.provider !== S.name || s.provider !== S.name) return yield* C.fail(l());
672
- let u = () => C.gen(function* () {
673
- if (yield* r(), P.stores !== i || (yield* i.closures.getAccount(e)) !== null) return yield* C.fail(l());
674
- yield* N(e, n, s.providerCustomerId);
675
- let t = yield* i.customers.getByTenant(e), a = yield* i.subscriptions.getByTenant(e);
676
- if (P.stores !== i || t === null || t.id !== s.id || t.provider !== s.provider || t.providerCustomerId !== s.providerCustomerId || !m(t.account, s.account) || a === null || a.provider !== o.provider || a.providerSubscriptionId !== o.providerSubscriptionId) return yield* C.fail(l());
677
- yield* r();
678
- }), d = (e, t) => e === null || t === null ? e === t : e instanceof Date && t instanceof Date && Number.isFinite(e.getTime()) && Number.isFinite(t.getTime()) && e.getTime() === t.getTime(), f = () => C.gen(function* () {
679
- yield* u();
680
- let t = yield* X(o.providerSubscriptionId, s), n = yield* C.try({
671
+ if (s === null || l === null || u === void 0 || s.tenantId !== n || s.provider !== S.name || l.provider !== S.name) return yield* C.fail(d());
672
+ let f = () => C.gen(function* () {
673
+ if (yield* i(), P.stores !== a || (yield* a.closures.getAccount(n)) !== null) return yield* C.fail(d());
674
+ yield* N(n, r, l.providerCustomerId);
675
+ let e = yield* a.customers.getByTenant(n), t = yield* a.subscriptions.getByTenant(n);
676
+ if (P.stores !== a || e === null || e.id !== l.id || e.provider !== l.provider || e.providerCustomerId !== l.providerCustomerId || !c(e.account, l.account) || t === null || t.provider !== s.provider || t.providerSubscriptionId !== s.providerSubscriptionId) return yield* C.fail(d());
677
+ yield* i();
678
+ }), p = (e, t) => e === null || t === null ? e === t : e instanceof Date && t instanceof Date && Number.isFinite(e.getTime()) && Number.isFinite(t.getTime()) && e.getTime() === t.getTime(), m = () => C.gen(function* () {
679
+ yield* f();
680
+ let r = yield* X(s.providerSubscriptionId, l), i = yield* C.try({
681
681
  try: () => {
682
- let n = (e) => e === null || e instanceof Date && Number.isFinite(e.getTime()), r = t?.plan == null ? null : w.priceIdFor(t.plan);
683
- if (t === null || t.providerSubscriptionId !== o.providerSubscriptionId || t.providerCustomerId !== s.providerCustomerId || t.tenantId !== null && t.tenantId !== e || t.plan === null || !w.has(t.plan) || !Number.isSafeInteger(t.quantity) || t.quantity < 1 || !Array.isArray(t.priceIds) || t.priceIds.some((e) => typeof e != "string" || e.length === 0) || r !== null && !t.priceIds.includes(r) || ![
682
+ let e = (e) => e === null || e instanceof Date && Number.isFinite(e.getTime()), i = r?.plan == null ? null : w.priceIdFor(r.plan);
683
+ if (r === null || r.providerSubscriptionId !== s.providerSubscriptionId || r.providerCustomerId !== l.providerCustomerId || r.tenantId !== null && r.tenantId !== n || r.plan === null || !w.has(r.plan) || !Number.isSafeInteger(r.quantity) || r.quantity < 1 || !Array.isArray(r.priceIds) || r.priceIds.some((e) => typeof e != "string" || e.length === 0) || i !== null && !r.priceIds.includes(i) || ![
684
684
  "active",
685
685
  "trialing",
686
686
  "pastDue",
687
687
  "incomplete",
688
688
  "canceled"
689
- ].includes(t.status) || !n(t.currentPeriodStart) || !n(t.currentPeriodEnd) || !n(t.cancelAt) || t.currentPeriodStart !== null && t.currentPeriodEnd !== null && t.currentPeriodStart.getTime() > t.currentPeriodEnd.getTime()) throw l();
690
- let i = k();
691
- if (!(i instanceof Date) || !Number.isFinite(i.getTime())) throw l();
692
- return a = {
693
- ...t,
694
- priceIds: [...t.priceIds],
695
- providerObservedAt: t.providerObservedAt instanceof Date ? new Date(t.providerObservedAt.getTime()) : null
689
+ ].includes(r.status) || !e(r.currentPeriodStart) || !e(r.currentPeriodEnd) || !e(r.cancelAt) || r.currentPeriodStart !== null && r.currentPeriodEnd !== null && r.currentPeriodStart.getTime() > r.currentPeriodEnd.getTime()) throw d();
690
+ let a = k();
691
+ if (!(a instanceof Date) || !Number.isFinite(a.getTime())) throw d();
692
+ return o = {
693
+ ...r,
694
+ priceIds: [...r.priceIds],
695
+ providerObservedAt: r.providerObservedAt instanceof Date ? new Date(r.providerObservedAt.getTime()) : null
696
696
  }, {
697
- tenantId: e,
697
+ tenantId: n,
698
698
  provider: S.name,
699
- providerSubscriptionId: o.providerSubscriptionId,
700
- plan: t.plan,
701
- status: t.status,
702
- quantity: t.quantity,
703
- currentPeriodStart: t.currentPeriodStart === null ? null : new Date(t.currentPeriodStart.getTime()),
704
- currentPeriodEnd: t.currentPeriodEnd === null ? null : new Date(t.currentPeriodEnd.getTime()),
705
- cancelAt: t.cancelAt === null ? null : new Date(t.cancelAt.getTime()),
706
- providerObservation: y({
707
- tenantId: e,
699
+ providerSubscriptionId: s.providerSubscriptionId,
700
+ plan: r.plan,
701
+ status: r.status,
702
+ quantity: r.quantity,
703
+ currentPeriodStart: r.currentPeriodStart === null ? null : new Date(r.currentPeriodStart.getTime()),
704
+ currentPeriodEnd: r.currentPeriodEnd === null ? null : new Date(r.currentPeriodEnd.getTime()),
705
+ cancelAt: r.cancelAt === null ? null : new Date(r.cancelAt.getTime()),
706
+ providerObservation: t({
707
+ tenantId: n,
708
708
  provider: S.name,
709
- account: s.account,
710
- snapshot: t,
711
- expectedPriceId: r,
712
- expectedCurrency: w.currencyFor(t.plan),
713
- observedAt: i
709
+ account: l.account,
710
+ snapshot: r,
711
+ expectedPriceId: i,
712
+ expectedCurrency: w.currencyFor(r.plan),
713
+ observedAt: a
714
714
  }),
715
- pastDueSince: o.pastDueSince,
716
- statusEventAt: new Date(i.getTime())
715
+ pastDueSince: s.pastDueSince,
716
+ statusEventAt: new Date(a.getTime())
717
717
  };
718
718
  },
719
- catch: l
719
+ catch: d
720
720
  });
721
- yield* u();
722
- let r = yield* i.subscriptions.getByTenant(e);
723
- yield* i.subscriptions.upsert(n);
724
- let c = n.status === "pastDue" ? r?.status === "pastDue" && r.pastDueSince !== null ? r.pastDueSince : n.statusEventAt : null;
725
- yield* i.subscriptions.patchBySubscription(e, n.providerSubscriptionId, { pastDueSince: c }, n.statusEventAt);
726
- let f = yield* i.subscriptions.getByTenant(e);
727
- return f === null || f.providerSubscriptionId !== n.providerSubscriptionId || f.plan !== n.plan || f.status !== n.status || f.quantity !== n.quantity || !d(f.currentPeriodStart, n.currentPeriodStart) || !d(f.currentPeriodEnd, n.currentPeriodEnd) || !d(f.cancelAt, n.cancelAt) ? yield* C.fail(l()) : (yield* u(), yield* C.try({
721
+ yield* f();
722
+ let c = yield* a.subscriptions.getByTenant(n);
723
+ yield* a.subscriptions.upsert(i);
724
+ let u = i.status === "pastDue" ? c?.status === "pastDue" && c.pastDueSince !== null ? c.pastDueSince : i.statusEventAt : null;
725
+ yield* a.subscriptions.patchBySubscription(n, i.providerSubscriptionId, { pastDueSince: u }, i.statusEventAt);
726
+ let m = yield* a.subscriptions.getByTenant(n);
727
+ return m === null || m.providerSubscriptionId !== i.providerSubscriptionId || m.plan !== i.plan || m.status !== i.status || m.quantity !== i.quantity || !p(m.currentPeriodStart, i.currentPeriodStart) || !p(m.currentPeriodEnd, i.currentPeriodEnd) || !p(m.cancelAt, i.cancelAt) ? yield* C.fail(d()) : (yield* f(), yield* C.try({
728
728
  try: () => {
729
- if (JSON.stringify(v(f.providerObservation, f)) !== JSON.stringify(v(n.providerObservation, n))) throw l();
729
+ if (JSON.stringify(e(m.providerObservation, m)) !== JSON.stringify(e(i.providerObservation, i))) throw d();
730
730
  },
731
- catch: l
732
- }), yield* Z([Q(e, n, n.statusEventAt ?? k())]), yield* u(), f);
733
- }), p = () => oe(f());
731
+ catch: d
732
+ }), yield* Z([Q(n, i, i.statusEventAt ?? k())]), yield* f(), m);
733
+ }), h = () => oe(m());
734
734
  return {
735
- sub: yield* p(),
736
- customer: s,
737
- stores: i,
738
- check: u,
739
- observe: p,
740
- sameDate: d,
741
- refuse: l,
742
- getObservation: () => a
735
+ sub: yield* h(),
736
+ customer: l,
737
+ stores: a,
738
+ check: f,
739
+ observe: h,
740
+ sameDate: p,
741
+ refuse: d,
742
+ getObservation: () => o
743
743
  };
744
744
  }), We = (e, t, n) => C.gen(function* () {
745
745
  if (yield* e.check(), n.providerSubscriptionId !== e.sub.providerSubscriptionId || n.providerCustomerId !== e.customer.providerCustomerId || n.tenantId !== null && n.tenantId !== e.sub.tenantId || n.writeOperationId !== t || !(n.providerObservedAt instanceof Date) || !Number.isFinite(n.providerObservedAt.getTime())) return yield* C.fail(e.refuse());
746
746
  yield* e.stores.subscriptionWrites.acknowledge(t, n.providerObservedAt);
747
- }), Ge = (e, n, r, a) => C.gen(function* () {
748
- if (n === void 0 || !/^[A-Za-z0-9_-]{8,128}$/.test(n)) return yield* C.fail(new t({
747
+ }), Ge = (e, t, n, i) => C.gen(function* () {
748
+ if (t === void 0 || !/^[A-Za-z0-9_-]{8,128}$/.test(t)) return yield* C.fail(new x({
749
749
  source: "billing",
750
750
  message: "A durable requestId is required. Keep it unchanged when checking or retrying this operation.",
751
751
  transient: !1
752
752
  }));
753
- let o = e.getObservation(), s = {
754
- ...r,
753
+ let a = e.getObservation(), o = {
754
+ ...n,
755
755
  provider: S.name,
756
756
  providerAccountId: e.customer.account.providerAccountId,
757
757
  livemode: e.customer.account.livemode,
758
758
  customerId: e.customer.providerCustomerId,
759
759
  subscriptionId: e.sub.providerSubscriptionId,
760
- itemId: r.kind === "cancel" ? null : o?.providerPlanItemId ?? null,
761
- expectedPriceId: r.kind === "cancel" ? null : w.priceIdFor(e.sub.plan)
760
+ itemId: n.kind === "cancel" ? null : a?.providerPlanItemId ?? null,
761
+ expectedPriceId: n.kind === "cancel" ? null : w.priceIdFor(e.sub.plan)
762
762
  };
763
- if (r.kind !== "cancel" && (s.itemId === null || s.expectedPriceId === null)) return yield* C.fail(e.refuse());
764
- let c = e.stores.subscriptionWrites, l = yield* c.reserve(e.sub.tenantId, n, s), u = null;
765
- if (l.phase === "prepared" || l.phase === "claimed") {
766
- if (!x(e.sub.status)) return yield* C.fail(e.refuse());
763
+ if (n.kind !== "cancel" && (o.itemId === null || o.expectedPriceId === null)) return yield* C.fail(e.refuse());
764
+ let s = e.stores.subscriptionWrites, c = yield* s.reserve(e.sub.tenantId, t, o), l = null;
765
+ if (c.phase === "prepared" || c.phase === "claimed") {
766
+ if (!f(e.sub.status)) return yield* C.fail(e.refuse());
767
767
  yield* e.check();
768
768
  let t = globalThis.crypto.randomUUID();
769
- if (l = yield* c.claim(l.id, t), l.phase === "claimed" && l.claimId === t) {
770
- let n = l;
771
- yield* a({
769
+ if (c = yield* s.claim(c.id, t), c.phase === "claimed" && c.claimId === t) {
770
+ let n = c;
771
+ yield* i({
772
772
  id: n.id,
773
773
  itemId: n.intent.itemId,
774
774
  plan: n.intent.plan,
775
775
  expectedPriceId: n.intent.expectedPriceId,
776
- beforeDispatch: () => e.check().pipe(C.andThen(c.dispatch(n.id, t))),
777
- notDispatched: () => c.notDispatched(n.id, t),
778
- rejected: (e) => c.reject(n.id, t, e).pipe(C.asVoid),
776
+ beforeDispatch: () => e.check().pipe(C.andThen(s.dispatch(n.id, t))),
777
+ notDispatched: () => s.notDispatched(n.id, t),
778
+ rejected: (e) => s.reject(n.id, t, e).pipe(C.asVoid),
779
779
  applied: (t) => We(e, n.id, t)
780
780
  }, n.intent).pipe(C.catch((e) => C.sync(() => {
781
- u = e;
781
+ l = e;
782
782
  })));
783
783
  }
784
784
  }
785
- let d = yield* e.observe(), f = e.getObservation();
786
- f?.writeOperationId === l.id && (yield* We(e, l.id, f));
787
- let p = yield* c.getRequest(e.sub.tenantId, n);
788
- if (p === null || p.id !== l.id) return yield* C.fail(e.refuse());
789
- if (p.phase === "acknowledged") yield* c.complete(p.id);
790
- else if (p.phase === "withdrawn" || p.phase === "rejected") return yield* C.fail(u ?? i(n, p.phase));
791
- else if (p.phase !== "completed") return yield* C.fail(u ?? e.refuse());
792
- return yield* e.check(), d;
785
+ let u = yield* e.observe(), d = e.getObservation();
786
+ d?.writeOperationId === c.id && (yield* We(e, c.id, d));
787
+ let p = yield* s.getRequest(e.sub.tenantId, t);
788
+ if (p === null || p.id !== c.id) return yield* C.fail(e.refuse());
789
+ if (p.phase === "acknowledged") yield* s.complete(p.id);
790
+ else if (p.phase === "withdrawn" || p.phase === "rejected") return yield* C.fail(l ?? r(t, p.phase));
791
+ else if (p.phase !== "completed") return yield* C.fail(l ?? e.refuse());
792
+ return yield* e.check(), u;
793
793
  }), Ke = (e, t = () => C.void) => C.gen(function* () {
794
794
  let n = yield* P.stores.subscriptionWrites.getActive(e);
795
795
  if (n === null) return "none";
@@ -825,24 +825,24 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
825
825
  meteredPriceIds: [...new Set(w.meteredPriceIdsFor(e))],
826
826
  replacesMeteredPriceIds: t
827
827
  };
828
- }, Ye = (e, n, r = () => C.void, i) => C.gen(function* () {
829
- let a = n.plan === void 0 ? void 0 : w.priceIdFor(n.plan);
830
- if (n.plan !== void 0 && (!w.has(n.plan) || a === null) || n.quantity !== void 0 && (!Number.isSafeInteger(n.quantity) || n.quantity < 1)) return yield* C.fail(new t({
828
+ }, Ye = (e, t, n = () => C.void, r) => C.gen(function* () {
829
+ let i = t.plan === void 0 ? void 0 : w.priceIdFor(t.plan);
830
+ if (t.plan !== void 0 && (!w.has(t.plan) || i === null) || t.quantity !== void 0 && (!Number.isSafeInteger(t.quantity) || t.quantity < 1)) return yield* C.fail(new x({
831
831
  source: "billing",
832
832
  message: "Choose a self-service plan and a positive safe whole seat quantity.",
833
833
  transient: !1
834
834
  }));
835
- let o = yield* q(e, "change", r);
836
- if (n.quantity !== void 0 && n.quantity < w.minimumSeatsFor(n.plan ?? o.sub.plan)) return yield* C.fail(new t({
835
+ let a = yield* q(e, "change", n);
836
+ if (t.quantity !== void 0 && t.quantity < w.minimumSeatsFor(t.plan ?? a.sub.plan)) return yield* C.fail(new x({
837
837
  source: "billing",
838
838
  message: "The plan price already covers more seats than requested.",
839
839
  transient: !1
840
840
  }));
841
- let s = yield* Ge(o, i, {
841
+ let o = yield* Ge(a, r, {
842
842
  kind: "change",
843
- plan: n.plan ?? null,
844
- priceId: a ?? null,
845
- quantity: n.quantity ?? null
843
+ plan: t.plan ?? null,
844
+ priceId: i ?? null,
845
+ quantity: t.quantity ?? null
846
846
  }, (e, t) => S.updateSubscription({
847
847
  providerSubscriptionId: t.subscriptionId,
848
848
  operation: e,
@@ -853,132 +853,132 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
853
853
  }));
854
854
  return {
855
855
  tenantId: e,
856
- plan: s.plan,
857
- quantity: s.quantity,
856
+ plan: o.plan,
857
+ quantity: o.quantity,
858
858
  prorationMinor: null,
859
- currency: w.currencyFor(s.plan)
859
+ currency: w.currencyFor(o.plan)
860
860
  };
861
- }), Xe = (e, n) => C.gen(function* () {
862
- let r = yield* P.stores.subscriptions.getByTenant(e);
863
- if (r === null) return yield* C.fail(new t({
861
+ }), Xe = (e, t) => C.gen(function* () {
862
+ let n = yield* P.stores.subscriptions.getByTenant(e);
863
+ if (n === null) return yield* C.fail(new x({
864
864
  source: "billing",
865
865
  message: `no subscription for tenant '${e}' to preview`,
866
866
  transient: !1
867
867
  }));
868
- let i = n.plan ?? r.plan, a = n.plan === void 0 ? void 0 : w.priceIdFor(i);
869
- if (!w.has(i) || a === null || n.quantity !== void 0 && (!Number.isSafeInteger(n.quantity) || n.quantity < 1)) return yield* C.fail(new t({
868
+ let r = t.plan ?? n.plan, i = t.plan === void 0 ? void 0 : w.priceIdFor(r);
869
+ if (!w.has(r) || i === null || t.quantity !== void 0 && (!Number.isSafeInteger(t.quantity) || t.quantity < 1)) return yield* C.fail(new x({
870
870
  source: "billing",
871
871
  message: "Choose a self-service plan and a positive safe whole seat quantity.",
872
872
  transient: !1
873
873
  }));
874
- if (n.quantity !== void 0 && n.quantity < w.minimumSeatsFor(i)) return yield* C.fail(new t({
874
+ if (t.quantity !== void 0 && t.quantity < w.minimumSeatsFor(r)) return yield* C.fail(new x({
875
875
  source: "billing",
876
876
  message: "The plan price already covers more seats than requested.",
877
877
  transient: !1
878
878
  }));
879
- let o = yield* M(S.previewSubscriptionChange({
880
- providerSubscriptionId: r.providerSubscriptionId,
881
- ...a === void 0 ? {} : { priceId: a },
882
- ...Je(n.plan ?? null),
883
- ...n.quantity === void 0 ? {} : { quantity: n.quantity },
879
+ let a = yield* M(S.previewSubscriptionChange({
880
+ providerSubscriptionId: n.providerSubscriptionId,
881
+ ...i === void 0 ? {} : { priceId: i },
882
+ ...Je(t.plan ?? null),
883
+ ...t.quantity === void 0 ? {} : { quantity: t.quantity },
884
884
  proration: "prorate"
885
885
  }), T);
886
- return o.plan !== i || !w.has(o.plan) || n.quantity !== void 0 && o.quantity !== n.quantity || !Number.isSafeInteger(o.quantity) || o.quantity < 1 || !Number.isSafeInteger(o.prorationMinor) || o.currency !== w.currencyFor(o.plan) ? yield* C.fail(new t({
886
+ return a.plan !== r || !w.has(a.plan) || t.quantity !== void 0 && a.quantity !== t.quantity || !Number.isSafeInteger(a.quantity) || a.quantity < 1 || !Number.isSafeInteger(a.prorationMinor) || a.currency !== w.currencyFor(a.plan) ? yield* C.fail(new x({
887
887
  source: "billing",
888
888
  message: "The provider preview could not be confirmed. Refresh billing before retrying.",
889
889
  transient: !0
890
890
  })) : {
891
891
  tenantId: e,
892
- plan: o.plan,
893
- quantity: o.quantity,
894
- prorationMinor: o.prorationMinor,
895
- currency: o.currency
892
+ plan: a.plan,
893
+ quantity: a.quantity,
894
+ prorationMinor: a.prorationMinor,
895
+ currency: a.currency
896
896
  };
897
897
  }), Ze = (e) => C.gen(function* () {
898
898
  let t = yield* z(e);
899
899
  return t === null ? [] : yield* M(S.listInvoices({ providerCustomerId: t.providerCustomerId }), T);
900
- }), Qe = (e, n, r = P.stores) => C.gen(function* () {
901
- let i = S.fetchInvoiceSnapshot?.bind(S), a = S.fetchAccountIdentity?.bind(S);
902
- if (i === void 0 || a === void 0) return yield* C.fail(f("Complete account-owned invoice evidence is unsupported."));
903
- if (P.stores !== r) return yield* C.fail(f("Billing stores changed before invoice observation.", !0));
904
- let o = yield* L();
905
- if (o.provider !== e.provider || !m(o.account, e.account)) return yield* C.fail(f("The invoice account differs from retained custody."));
906
- let s = yield* a();
907
- if (!m(s, e.account)) return yield* C.fail(f("The provider account changed before invoice observation."));
908
- let c = yield* M(i({
900
+ }), Qe = (e, t, n = P.stores) => C.gen(function* () {
901
+ let r = S.fetchInvoiceSnapshot?.bind(S), i = S.fetchAccountIdentity?.bind(S);
902
+ if (r === void 0 || i === void 0) return yield* C.fail(o("Complete account-owned invoice evidence is unsupported."));
903
+ if (P.stores !== n) return yield* C.fail(o("Billing stores changed before invoice observation.", !0));
904
+ let s = yield* L();
905
+ if (s.provider !== e.provider || !c(s.account, e.account)) return yield* C.fail(o("The invoice account differs from retained custody."));
906
+ let l = yield* i();
907
+ if (!c(l, e.account)) return yield* C.fail(o("The provider account changed before invoice observation."));
908
+ let u = yield* M(r({
909
909
  providerCustomerId: e.providerCustomerId,
910
- providerInvoiceId: n
910
+ providerInvoiceId: t
911
911
  }), T);
912
912
  yield* C.try({
913
913
  try: () => {
914
- if (d(c), c.providerInvoiceId !== n || c.providerCustomerId !== e.providerCustomerId || c.livemode !== e.account.livemode) throw f("The invoice does not match retained account/customer custody.");
914
+ if (a(u), u.providerInvoiceId !== t || u.providerCustomerId !== e.providerCustomerId || u.livemode !== e.account.livemode) throw o("The invoice does not match retained account/customer custody.");
915
915
  },
916
- catch: (e) => e instanceof t ? e : f("The provider invoice could not be confirmed.")
916
+ catch: (e) => e instanceof x ? e : o("The provider invoice could not be confirmed.")
917
917
  });
918
- let l = yield* a(), u = yield* r.customers.getByProviderCustomerId(e.providerCustomerId, o);
919
- return P.stores !== r || !m(l, e.account) || u === null || u.id !== e.id || u.tenantId !== e.tenantId ? yield* C.fail(f("Invoice account/customer custody changed during observation.", !0)) : c;
920
- }), J = (e, n, r) => C.gen(function* () {
921
- let i = P.stores;
922
- if (!e || e.trim() !== e) return yield* C.fail(_("Exact tenant/customer identities are required."));
923
- let a = yield* C.try({
918
+ let d = yield* i(), f = yield* n.customers.getByProviderCustomerId(e.providerCustomerId, s);
919
+ return P.stores !== n || !c(d, e.account) || f === null || f.id !== e.id || f.tenantId !== e.tenantId ? yield* C.fail(o("Invoice account/customer custody changed during observation.", !0)) : u;
920
+ }), J = (e, t, n) => C.gen(function* () {
921
+ let r = P.stores;
922
+ if (!e || e.trim() !== e) return yield* C.fail(d("Exact tenant/customer identities are required."));
923
+ let i = yield* C.try({
924
924
  try: () => {
925
- let e = r?.cursor, t = e === void 0 ? void 0 : Object.freeze({
926
- ...p(e),
925
+ let e = n?.cursor, t = e === void 0 ? void 0 : Object.freeze({
926
+ ...s(e),
927
927
  providerCustomerId: e.providerCustomerId,
928
928
  afterInvoiceId: e.afterInvoiceId
929
- }), n = r?.limit;
929
+ }), r = n?.limit;
930
930
  return Object.freeze({
931
931
  ...t === void 0 ? {} : { cursor: t },
932
- ...n === void 0 ? {} : { limit: n }
932
+ ...r === void 0 ? {} : { limit: r }
933
933
  });
934
934
  },
935
- catch: (e) => e instanceof t ? e : _()
936
- }), o = yield* L(), s = yield* C.try({
937
- try: () => h({
938
- account: o.account,
939
- providerCustomerId: n,
940
- ...a
935
+ catch: (e) => e instanceof x ? e : d()
936
+ }), a = yield* L(), o = yield* C.try({
937
+ try: () => l({
938
+ account: a.account,
939
+ providerCustomerId: t,
940
+ ...i
941
941
  }),
942
- catch: (e) => e instanceof t ? e : _()
943
- }), c = yield* i.customers.getByProviderCustomerId(s.providerCustomerId, o);
944
- if (c === null || c.tenantId !== e || c.provider !== S.name) return yield* C.fail(_("Positive current or retained customer custody is required."));
945
- let l = S.listInvoiceHistory?.bind(S), u = S.fetchAccountIdentity?.bind(S);
946
- if (l === void 0 || u === void 0) return yield* C.fail(_("Complete account-owned invoice history is unsupported."));
947
- let d = yield* u();
948
- if (!m(d, c.account)) return yield* C.fail(_("The provider account differs before invoice history access."));
949
- let f = yield* M(l(s), T), v = yield* C.try({
950
- try: () => g(s, f),
951
- catch: (e) => e instanceof t ? e : _()
952
- }), y = yield* u(), b = yield* i.customers.getByProviderCustomerId(s.providerCustomerId, o);
953
- return P.stores !== i || !m(y, c.account) || b === null || b.id !== c.id || b.tenantId !== e ? yield* C.fail(_("Invoice history account/customer custody changed during observation.", !0)) : v;
942
+ catch: (e) => e instanceof x ? e : d()
943
+ }), f = yield* r.customers.getByProviderCustomerId(o.providerCustomerId, a);
944
+ if (f === null || f.tenantId !== e || f.provider !== S.name) return yield* C.fail(d("Positive current or retained customer custody is required."));
945
+ let p = S.listInvoiceHistory?.bind(S), m = S.fetchAccountIdentity?.bind(S);
946
+ if (p === void 0 || m === void 0) return yield* C.fail(d("Complete account-owned invoice history is unsupported."));
947
+ let h = yield* m();
948
+ if (!c(h, f.account)) return yield* C.fail(d("The provider account differs before invoice history access."));
949
+ let g = yield* M(p(o), T), _ = yield* C.try({
950
+ try: () => u(o, g),
951
+ catch: (e) => e instanceof x ? e : d()
952
+ }), v = yield* m(), y = yield* r.customers.getByProviderCustomerId(o.providerCustomerId, a);
953
+ return P.stores !== r || !c(v, f.account) || y === null || y.id !== f.id || y.tenantId !== e ? yield* C.fail(d("Invoice history account/customer custody changed during observation.", !0)) : _;
954
954
  }), $e = (e, t) => C.gen(function* () {
955
- if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(f("Exact tenant/invoice identities are required."));
955
+ if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(o("Exact tenant/invoice identities are required."));
956
956
  let n = yield* z(e);
957
- return n === null ? yield* C.fail(f("A qualified current customer is required.")) : yield* Qe(n, t);
957
+ return n === null ? yield* C.fail(o("A qualified current customer is required.")) : yield* Qe(n, t);
958
958
  }), Y = (e, t, n) => C.gen(function* () {
959
959
  let r = P.stores;
960
- if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(f("Exact tenant/invoice identities are required."));
960
+ if (!e || e.trim() !== e || !t || t.trim() !== t) return yield* C.fail(o("Exact tenant/invoice identities are required."));
961
961
  let i = yield* L();
962
962
  for (let a = 0; a < 3; a++) {
963
- if (P.stores !== r) return yield* C.fail(f("Billing stores changed during invoice reconciliation.", !0));
963
+ if (P.stores !== r) return yield* C.fail(o("Billing stores changed during invoice reconciliation.", !0));
964
964
  let a = n === void 0 ? yield* z(e) : yield* r.customers.getByProviderCustomerId(n, i);
965
- if (a === null || a.tenantId !== e) return yield* C.fail(f("Positive current or retained customer custody is required.", !0));
966
- let o = Object.freeze({
965
+ if (a === null || a.tenantId !== e) return yield* C.fail(o("Positive current or retained customer custody is required.", !0));
966
+ let s = Object.freeze({
967
967
  tenantId: e,
968
968
  provider: i.provider,
969
969
  ...i.account,
970
970
  providerCustomerId: a.providerCustomerId,
971
971
  providerInvoiceId: t
972
- }), s = yield* r.invoices.capturePaymentEpoch(o), c = yield* r.invoices.get(o), l = yield* Qe(a, t, r);
973
- if (P.stores !== r) return yield* C.fail(f("Billing stores changed before native invoice persistence.", !0));
974
- if (!(yield* r.invoices.complete(o, c, l, s))) continue;
975
- let u = yield* r.invoices.get(o);
976
- return u === null || u.revision <= (c?.revision ?? 0) ? yield* C.fail(f("Invoice persistence could not be confirmed.", !0)) : u;
972
+ }), c = yield* r.invoices.capturePaymentEpoch(s), l = yield* r.invoices.get(s), u = yield* Qe(a, t, r);
973
+ if (P.stores !== r) return yield* C.fail(o("Billing stores changed before native invoice persistence.", !0));
974
+ if (!(yield* r.invoices.complete(s, l, u, c))) continue;
975
+ let d = yield* r.invoices.get(s);
976
+ return d === null || d.revision <= (l?.revision ?? 0) ? yield* C.fail(o("Invoice persistence could not be confirmed.", !0)) : d;
977
977
  }
978
- return yield* C.fail(f("Concurrent invoice observation requires retry.", !0));
979
- }), et = (e, n, r, i = () => C.void, a) => C.gen(function* () {
980
- if (n === "free") {
981
- let t = yield* tt(e, i, a);
978
+ return yield* C.fail(o("Concurrent invoice observation requires retry.", !0));
979
+ }), et = (e, t, n, r = () => C.void, i) => C.gen(function* () {
980
+ if (t === "free") {
981
+ let t = yield* tt(e, r, i);
982
982
  return {
983
983
  tenantId: e,
984
984
  plan: t.plan,
@@ -987,11 +987,11 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
987
987
  currency: w.currencyFor(t.plan)
988
988
  };
989
989
  }
990
- return w.has(n) && w.priceIdFor(n) === null ? yield* C.fail(new t({
990
+ return w.has(t) && w.priceIdFor(t) === null ? yield* C.fail(new x({
991
991
  source: "billing",
992
- message: `plan '${n}' has no provider price — it is not a self-serve plan`,
992
+ message: `plan '${t}' has no provider price — it is not a self-serve plan`,
993
993
  transient: !1
994
- })) : yield* Ye(e, { plan: n }, i, a);
994
+ })) : yield* Ye(e, { plan: t }, r, i);
995
995
  }), tt = (e, t = () => C.void, n) => C.gen(function* () {
996
996
  let r = yield* q(e, "cancel", t);
997
997
  return yield* Ge(r, n, {
@@ -1012,162 +1012,162 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1012
1012
  priceId: null,
1013
1013
  quantity: null
1014
1014
  }, (e, t) => S.resumeSubscription(t.subscriptionId, e));
1015
- }), rt = (n) => C.gen(function* () {
1016
- yield* R(n), yield* fe(n);
1017
- let r = () => new t({
1015
+ }), rt = (e) => C.gen(function* () {
1016
+ yield* R(e), yield* fe(e);
1017
+ let t = () => new x({
1018
1018
  source: "billing",
1019
1019
  message: "Billing closure is pending provider confirmation. Retry reconciliation before completing account deletion.",
1020
1020
  transient: !0
1021
1021
  });
1022
- if (n.length === 0) return yield* C.fail(r());
1023
- yield* Ke(n), yield* P.stores.subscriptionWrites.seal(n), yield* P.stores.closures.reserveAccount(n, S.name, k());
1024
- let i = yield* z(n), a = yield* P.stores.checkouts.getActive(n);
1025
- if (i !== null && i.provider !== S.name || a !== null && a.provider !== S.name || i !== null && a?.providerCustomerId !== null && a?.providerCustomerId !== void 0 && i.providerCustomerId !== a.providerCustomerId) return yield* C.fail(r());
1026
- let o = /* @__PURE__ */ new Set();
1027
- i !== null && o.add(i.providerCustomerId), a?.providerCustomerId && o.add(a.providerCustomerId);
1028
- for (let e of o) yield* M(S.expireOpenCheckouts({ providerCustomerId: e }), T);
1029
- let s = null;
1030
- if (a !== null) {
1031
- let e = yield* M(S.findCheckoutSession({
1032
- tenantId: n,
1033
- operationId: a.id,
1034
- ...a.providerCustomerId === null ? {} : { providerCustomerId: a.providerCustomerId }
1035
- }), T), t = e.receipt;
1036
- if (t === null) {
1037
- if (e.observedAt === null || !Number.isFinite(e.observedAt.getTime()) || e.observedAt.getTime() < a.expiresAt.getTime()) return yield* C.fail(r());
1038
- yield* P.stores.checkouts.patch(a.id, { phase: "expired" });
1022
+ if (e.length === 0) return yield* C.fail(t());
1023
+ yield* Ke(e), yield* P.stores.subscriptionWrites.seal(e), yield* P.stores.closures.reserveAccount(e, S.name, k());
1024
+ let n = yield* z(e), r = yield* P.stores.checkouts.getActive(e);
1025
+ if (n !== null && n.provider !== S.name || r !== null && r.provider !== S.name || n !== null && r?.providerCustomerId !== null && r?.providerCustomerId !== void 0 && n.providerCustomerId !== r.providerCustomerId) return yield* C.fail(t());
1026
+ let i = /* @__PURE__ */ new Set();
1027
+ n !== null && i.add(n.providerCustomerId), r?.providerCustomerId && i.add(r.providerCustomerId);
1028
+ for (let e of i) yield* M(S.expireOpenCheckouts({ providerCustomerId: e }), T);
1029
+ let a = null;
1030
+ if (r !== null) {
1031
+ let n = yield* M(S.findCheckoutSession({
1032
+ tenantId: e,
1033
+ operationId: r.id,
1034
+ ...r.providerCustomerId === null ? {} : { providerCustomerId: r.providerCustomerId }
1035
+ }), T), o = n.receipt;
1036
+ if (o === null) {
1037
+ if (n.observedAt === null || !Number.isFinite(n.observedAt.getTime()) || n.observedAt.getTime() < r.expiresAt.getTime()) return yield* C.fail(t());
1038
+ yield* P.stores.checkouts.patch(r.id, { phase: "expired" });
1039
1039
  } else {
1040
- if (t.operationId !== a.id || t.tenantId !== n || !t.id || t.providerCustomerId === null || t.expiresAt.getTime() !== a.expiresAt.getTime() || a.providerCustomerId !== null && t.providerCustomerId !== a.providerCustomerId || a.providerSessionId !== null && t.id !== a.providerSessionId) return yield* C.fail(r());
1041
- if (o.add(t.providerCustomerId), yield* P.stores.checkouts.patch(a.id, {
1042
- providerCustomerId: t.providerCustomerId,
1043
- providerSessionId: t.id
1044
- }), t.status === "open") return yield* M(S.expireOpenCheckouts({ providerCustomerId: t.providerCustomerId }), T), yield* C.fail(r());
1045
- if (t.status === "expired") yield* P.stores.checkouts.patch(a.id, { phase: "expired" });
1040
+ if (o.operationId !== r.id || o.tenantId !== e || !o.id || o.providerCustomerId === null || o.expiresAt.getTime() !== r.expiresAt.getTime() || r.providerCustomerId !== null && o.providerCustomerId !== r.providerCustomerId || r.providerSessionId !== null && o.id !== r.providerSessionId) return yield* C.fail(t());
1041
+ if (i.add(o.providerCustomerId), yield* P.stores.checkouts.patch(r.id, {
1042
+ providerCustomerId: o.providerCustomerId,
1043
+ providerSessionId: o.id
1044
+ }), o.status === "open") return yield* M(S.expireOpenCheckouts({ providerCustomerId: o.providerCustomerId }), T), yield* C.fail(t());
1045
+ if (o.status === "expired") yield* P.stores.checkouts.patch(r.id, { phase: "expired" });
1046
1046
  else {
1047
- if (t.providerSubscriptionId === null) return yield* C.fail(r());
1048
- s = t.providerSubscriptionId, yield* P.stores.checkouts.patch(a.id, { phase: "completed" });
1047
+ if (o.providerSubscriptionId === null) return yield* C.fail(t());
1048
+ a = o.providerSubscriptionId, yield* P.stores.checkouts.patch(r.id, { phase: "completed" });
1049
1049
  }
1050
1050
  }
1051
1051
  }
1052
- yield* Me(n), yield* P.stores.closures.sealUsage(n);
1053
- let c = yield* P.stores.usage.pending();
1054
- if (S.supportsMeteredUsage && c.some((e) => e.tenantId === n && e.used > e.reportedToProvider)) return yield* C.fail(V());
1055
- let l = yield* P.stores.subscriptions.listByTenant(n), u = new Set(l.filter((e) => x(e.status)).map((e) => e.providerSubscriptionId));
1056
- s !== null && u.add(s);
1057
- for (let e of o) {
1052
+ yield* Me(e), yield* P.stores.closures.sealUsage(e);
1053
+ let o = yield* P.stores.usage.pending();
1054
+ if (S.supportsMeteredUsage && o.some((t) => t.tenantId === e && t.used > t.reportedToProvider)) return yield* C.fail(V());
1055
+ let s = yield* P.stores.subscriptions.listByTenant(e), c = new Set(s.filter((e) => f(e.status)).map((e) => e.providerSubscriptionId));
1056
+ a !== null && c.add(a);
1057
+ for (let e of i) {
1058
1058
  let t = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
1059
- for (let e of t) u.add(e.providerSubscriptionId);
1059
+ for (let e of t) c.add(e.providerSubscriptionId);
1060
1060
  }
1061
- let d = [], f = /* @__PURE__ */ new Set(), p = !1;
1062
- for (let e of u) {
1063
- let t = yield* M(S.fetchSubscription(e), T);
1064
- if (t === null) {
1065
- p = !0;
1061
+ let l = [], u = /* @__PURE__ */ new Set(), d = !1;
1062
+ for (let n of c) {
1063
+ let r = yield* M(S.fetchSubscription(n), T);
1064
+ if (r === null) {
1065
+ d = !0;
1066
1066
  continue;
1067
1067
  }
1068
- let i = t;
1069
- if (t.status !== "canceled") {
1070
- let t = yield* P.stores.closures.getSubscription(n, e);
1071
- if (t === null) {
1072
- let r = yield* M(S.prepareSubscriptionClose(e), T);
1073
- t = yield* P.stores.closures.reserveSubscription({
1074
- tenantId: n,
1068
+ let i = r;
1069
+ if (r.status !== "canceled") {
1070
+ let r = yield* P.stores.closures.getSubscription(e, n);
1071
+ if (r === null) {
1072
+ let t = yield* M(S.prepareSubscriptionClose(n), T);
1073
+ r = yield* P.stores.closures.reserveSubscription({
1074
+ tenantId: e,
1075
1075
  provider: S.name,
1076
- providerSubscriptionId: e,
1077
- cancelAt: r.cancelAt,
1076
+ providerSubscriptionId: n,
1077
+ cancelAt: t.cancelAt,
1078
1078
  createdAt: k()
1079
1079
  });
1080
1080
  }
1081
- if (t.provider !== S.name || t.providerSubscriptionId !== e || t.cancelAt === null) return yield* C.fail(r());
1081
+ if (r.provider !== S.name || r.providerSubscriptionId !== n || r.cancelAt === null) return yield* C.fail(t());
1082
1082
  i = yield* M(S.cancelSubscription({
1083
- providerSubscriptionId: e,
1083
+ providerSubscriptionId: n,
1084
1084
  mode: "close",
1085
1085
  closeOperation: {
1086
- id: t.id,
1087
- cancelAt: t.cancelAt
1086
+ id: r.id,
1087
+ cancelAt: r.cancelAt
1088
1088
  }
1089
1089
  }), T);
1090
1090
  }
1091
- yield* W(n, {
1091
+ yield* W(e, {
1092
1092
  ...i,
1093
- providerSubscriptionId: e
1094
- }, k()), i.status === "canceled" ? d.push(e) : f.add(e);
1093
+ providerSubscriptionId: n
1094
+ }, k()), i.status === "canceled" ? l.push(n) : u.add(n);
1095
1095
  }
1096
- for (let e of o) (yield* M(S.listSubscriptions({ providerCustomerId: e }), T)).some((e) => e.status !== "canceled" && !f.has(e.providerSubscriptionId)) && (p = !0);
1097
- if (p) return yield* C.fail(r());
1098
- if (f.size > 0) return yield* C.fail(new e({
1099
- tenantId: n,
1096
+ for (let e of i) (yield* M(S.listSubscriptions({ providerCustomerId: e }), T)).some((e) => e.status !== "canceled" && !u.has(e.providerSubscriptionId)) && (d = !0);
1097
+ if (d) return yield* C.fail(t());
1098
+ if (u.size > 0) return yield* C.fail(new ee({
1099
+ tenantId: e,
1100
1100
  reason: "cancellation-settling",
1101
1101
  providerInvoiceIds: [],
1102
1102
  message: "Billing closure is pending provider confirmation: subscriptions end after the meter settlement window."
1103
1103
  }));
1104
- let m = yield* P.stores.usage.pending();
1105
- if (S.supportsMeteredUsage && m.some((e) => e.tenantId === n && e.used > e.reportedToProvider)) return yield* C.fail(V());
1106
- a !== null && s !== null && (yield* P.stores.checkouts.patch(a.id, { phase: "retired" }));
1107
- let h = /* @__PURE__ */ new Set([...d, ...l.filter((e) => e.provider === S.name).map((e) => e.providerSubscriptionId)]), g = yield* it(n, [...h], i, r);
1104
+ let p = yield* P.stores.usage.pending();
1105
+ if (S.supportsMeteredUsage && p.some((t) => t.tenantId === e && t.used > t.reportedToProvider)) return yield* C.fail(V());
1106
+ r !== null && a !== null && (yield* P.stores.checkouts.patch(r.id, { phase: "retired" }));
1107
+ let m = /* @__PURE__ */ new Set([...l, ...s.filter((e) => e.provider === S.name).map((e) => e.providerSubscriptionId)]), h = yield* it(e, [...m], n, t);
1108
1108
  return D.info("billing account closed", {
1109
- tenant: n,
1110
- canceled: d.length,
1111
- finalInvoices: g.length
1109
+ tenant: e,
1110
+ canceled: l.length,
1111
+ finalInvoices: h.length
1112
1112
  }), {
1113
- tenantId: n,
1114
- canceled: d,
1115
- finalInvoices: g
1113
+ tenantId: e,
1114
+ canceled: l,
1115
+ finalInvoices: h
1116
1116
  };
1117
- }), it = (t, n, r, i) => C.gen(function* () {
1118
- let a = /* @__PURE__ */ new Set();
1119
- for (let e of n) {
1120
- let t = yield* X(e, r ?? void 0);
1121
- if (t.status !== "canceled") return yield* C.fail(i());
1122
- t.providerLatestInvoiceId && a.add(t.providerLatestInvoiceId);
1117
+ }), it = (e, t, n, r) => C.gen(function* () {
1118
+ let i = /* @__PURE__ */ new Set();
1119
+ for (let e of t) {
1120
+ let t = yield* X(e, n ?? void 0);
1121
+ if (t.status !== "canceled") return yield* C.fail(r());
1122
+ t.providerLatestInvoiceId && i.add(t.providerLatestInvoiceId);
1123
1123
  }
1124
- if (a.size === 0) return [];
1125
- if (r === null) return yield* C.fail(i());
1126
- let o = (n, r) => new e({
1127
- tenantId: t,
1128
- reason: n,
1129
- providerInvoiceIds: [...r],
1130
- message: n === "final-invoice-draft" ? "Billing closure waits for the provider to finalize the final invoice." : "Billing closure waits until the final invoice is paid, uncollectible or void."
1131
- }), s = yield* J(t, r.providerCustomerId, { limit: 100 }), c = [];
1132
- for (let e of a) {
1133
- let t = s.invoices.find((t) => t.providerInvoiceId === e);
1134
- if (t === void 0) return yield* C.fail(i());
1135
- t.status === "draft" && c.push(e);
1124
+ if (i.size === 0) return [];
1125
+ if (n === null) return yield* C.fail(r());
1126
+ let a = (t, n) => new ee({
1127
+ tenantId: e,
1128
+ reason: t,
1129
+ providerInvoiceIds: [...n],
1130
+ message: t === "final-invoice-draft" ? "Billing closure waits for the provider to finalize the final invoice." : "Billing closure waits until the final invoice is paid, uncollectible or void."
1131
+ }), o = yield* J(e, n.providerCustomerId, { limit: 100 }), s = [];
1132
+ for (let e of i) {
1133
+ let t = o.invoices.find((t) => t.providerInvoiceId === e);
1134
+ if (t === void 0) return yield* C.fail(r());
1135
+ t.status === "draft" && s.push(e);
1136
1136
  }
1137
- if (c.length > 0) return yield* C.fail(o("final-invoice-draft", c));
1138
- let l = [], u = [];
1139
- for (let e of a) {
1140
- let n = (yield* Y(t, e, r.providerCustomerId)).snapshot.status;
1141
- n === "open" ? u.push(e) : l.push({
1142
- providerInvoiceId: e,
1143
- status: n
1137
+ if (s.length > 0) return yield* C.fail(a("final-invoice-draft", s));
1138
+ let c = [], l = [];
1139
+ for (let t of i) {
1140
+ let r = (yield* Y(e, t, n.providerCustomerId)).snapshot.status;
1141
+ r === "open" ? l.push(t) : c.push({
1142
+ providerInvoiceId: t,
1143
+ status: r
1144
1144
  });
1145
1145
  }
1146
- return u.length > 0 ? yield* C.fail(o("final-invoice-open", u)) : l;
1146
+ return l.length > 0 ? yield* C.fail(a("final-invoice-open", l)) : c;
1147
1147
  }), at = (e) => C.gen(function* () {
1148
- return (yield* P.stores.closures.getAccount(e)) === null ? n.isTenantClosed === void 0 ? !1 : yield* n.isTenantClosed(e) : !0;
1148
+ return (yield* P.stores.closures.getAccount(e)) === null ? p.isTenantClosed === void 0 ? !1 : yield* p.isTenantClosed(e) : !0;
1149
1149
  }), ot = (e) => at(e).pipe(C.catch((t) => C.sync(() => (D.warn("billing: could not tell whether a tenant is closed — leaving it", {
1150
1150
  tenant: e,
1151
1151
  message: t.message
1152
1152
  }), !1)))), X = (e, t) => C.gen(function* () {
1153
1153
  let n = S.fetchSubscriptionSnapshot;
1154
- if (n === void 0) return yield* C.fail(f("Customer-qualified subscription observations are required."));
1154
+ if (n === void 0) return yield* C.fail(o("Customer-qualified subscription observations are required."));
1155
1155
  let r = yield* L(), i = S.fetchAccountIdentity;
1156
- if (i === void 0) return yield* C.fail(f("Provider account observations are required."));
1156
+ if (i === void 0) return yield* C.fail(o("Provider account observations are required."));
1157
1157
  let a = yield* i();
1158
- if (!m(a, r.account)) return yield* C.fail(f("The provider account changed before subscription observation."));
1159
- let o = P.stores, s = t === void 0 ? null : yield* o.customers.getByProviderCustomerId(t.providerCustomerId, r);
1160
- if (t !== void 0 && (s === null || s.id !== t.id || s.tenantId !== t.tenantId)) return yield* C.fail(f("Native subscription customer custody changed."));
1161
- let c = t === void 0 ? null : yield* o.invoices.capturePaymentEpoch({
1158
+ if (!c(a, r.account)) return yield* C.fail(o("The provider account changed before subscription observation."));
1159
+ let l = P.stores, u = t === void 0 ? null : yield* l.customers.getByProviderCustomerId(t.providerCustomerId, r);
1160
+ if (t !== void 0 && (u === null || u.id !== t.id || u.tenantId !== t.tenantId)) return yield* C.fail(o("Native subscription customer custody changed."));
1161
+ let d = t === void 0 ? null : yield* l.invoices.capturePaymentEpoch({
1162
1162
  tenantId: t.tenantId,
1163
1163
  provider: r.provider,
1164
1164
  ...r.account,
1165
1165
  providerCustomerId: t.providerCustomerId
1166
- }), l = yield* M(n(e), T), u = yield* i();
1167
- return !m(u, r.account) || l === null || l.providerSubscriptionId !== e || l.providerCustomerId === null || t !== void 0 && l.providerCustomerId !== t.providerCustomerId || P.stores !== o ? yield* C.fail(f("A complete subscription observation in the retained provider account is required.")) : {
1168
- ...l,
1169
- providerAccount: p(r.account),
1170
- paymentEpoch: c
1166
+ }), f = yield* M(n(e), T), p = yield* i();
1167
+ return !c(p, r.account) || f === null || f.providerSubscriptionId !== e || f.providerCustomerId === null || t !== void 0 && f.providerCustomerId !== t.providerCustomerId || P.stores !== l ? yield* C.fail(o("A complete subscription observation in the retained provider account is required.")) : {
1168
+ ...f,
1169
+ providerAccount: s(r.account),
1170
+ paymentEpoch: d
1171
1171
  };
1172
1172
  }), st = (e, t = !1) => C.gen(function* () {
1173
1173
  let n = P.stores, r = () => t ? n.closures.getAccount(e.tenantId).pipe(C.map((e) => e !== null)) : C.succeed(!1);
@@ -1176,85 +1176,85 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1176
1176
  if (i === null || i.id !== e.id) return [];
1177
1177
  let a = yield* n.subscriptions.getByTenant(e.tenantId);
1178
1178
  if (a === null || a.provider !== S.name) return [];
1179
- let o = yield* X(a.providerSubscriptionId, e);
1180
- if (P.stores !== n) return yield* C.fail(f("Billing stores changed during current subscription refresh.", !0));
1179
+ let s = yield* X(a.providerSubscriptionId, e);
1180
+ if (P.stores !== n) return yield* C.fail(o("Billing stores changed during current subscription refresh.", !0));
1181
1181
  if (yield* r()) return [];
1182
- let s = k();
1183
- yield* W(e.tenantId, o, s);
1184
- let c = Q(e.tenantId, o, s);
1185
- return yield* K(c), [c];
1186
- }), ct = (e, n) => C.gen(function* () {
1187
- let r = k(), i = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1188
- if (i !== null && i.retiredAt !== null) {
1182
+ let c = k();
1183
+ yield* W(e.tenantId, s, c);
1184
+ let l = Q(e.tenantId, s, c);
1185
+ return yield* K(l), [l];
1186
+ }), ct = (e, t) => C.gen(function* () {
1187
+ let n = k(), r = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1188
+ if (r !== null && r.retiredAt !== null) {
1189
1189
  let t = [];
1190
- for (let n of yield* P.stores.subscriptions.listByTenant(i.tenantId)) {
1191
- let a = yield* X(n.providerSubscriptionId, i);
1190
+ for (let i of yield* P.stores.subscriptions.listByTenant(r.tenantId)) {
1191
+ let a = yield* X(i.providerSubscriptionId, r);
1192
1192
  if (a.providerCustomerId !== e) continue;
1193
- if (a.status !== "canceled") return yield* C.fail(f("A retired customer still has an unsettled provider subscription."));
1194
- let o = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1195
- if (o === null || o.id !== i.id || o.tenantId !== i.tenantId || o.retiredAt === null) return yield* C.fail(f("Retired customer custody changed during reconciliation."));
1196
- yield* W(i.tenantId, a, r), t.push(Q(i.tenantId, a, r));
1193
+ if (a.status !== "canceled") return yield* C.fail(o("A retired customer still has an unsettled provider subscription."));
1194
+ let s = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1195
+ if (s === null || s.id !== r.id || s.tenantId !== r.tenantId || s.retiredAt === null) return yield* C.fail(o("Retired customer custody changed during reconciliation."));
1196
+ yield* W(r.tenantId, a, n), t.push(Q(r.tenantId, a, n));
1197
1197
  }
1198
1198
  for (let e of t) yield* K(e);
1199
1199
  return {
1200
- tenantId: i.tenantId,
1200
+ tenantId: r.tenantId,
1201
1201
  events: t
1202
1202
  };
1203
1203
  }
1204
- let a = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
1205
- if (a.some((t) => t.providerCustomerId !== e)) return yield* C.fail(f("The subscription listing names another customer."));
1206
- let o = i?.tenantId ?? n ?? a.find((e) => e.tenantId !== null)?.tenantId ?? null;
1207
- if (o === null) return D.warn("billing sync: customer names no tenant — nothing to attribute it to", { customer: e }), {
1204
+ let i = yield* M(S.listSubscriptions({ providerCustomerId: e }), T);
1205
+ if (i.some((t) => t.providerCustomerId !== e)) return yield* C.fail(o("The subscription listing names another customer."));
1206
+ let a = r?.tenantId ?? t ?? i.find((e) => e.tenantId !== null)?.tenantId ?? null;
1207
+ if (a === null) return D.warn("billing sync: customer names no tenant — nothing to attribute it to", { customer: e }), {
1208
1208
  tenantId: null,
1209
1209
  events: []
1210
1210
  };
1211
- let s = [], c = yield* z(o);
1212
- if (i !== null && i.provider !== S.name || c !== null && (c.provider !== S.name || c.providerCustomerId !== e)) return yield* C.fail(new t({
1211
+ let s = [], c = yield* z(a);
1212
+ if (r !== null && r.provider !== S.name || c !== null && (c.provider !== S.name || c.providerCustomerId !== e)) return yield* C.fail(new x({
1213
1213
  source: "billing.syncCustomer",
1214
1214
  message: "Customer discovery cannot replace existing native billing custody.",
1215
1215
  transient: !1
1216
1216
  }));
1217
- if (i === null) {
1218
- if (yield* at(o)) return yield* C.fail(f("Closed tenant customer custody requires reconciliation."));
1219
- yield* B(o, e), s.push({
1217
+ if (r === null) {
1218
+ if (yield* at(a)) return yield* C.fail(o("Closed tenant customer custody requires reconciliation."));
1219
+ yield* B(a, e), s.push({
1220
1220
  _tag: "customerLinked",
1221
- tenantId: o,
1221
+ tenantId: a,
1222
1222
  providerCustomerId: e,
1223
- occurredAt: r
1223
+ occurredAt: n
1224
1224
  });
1225
1225
  }
1226
- a.some((e) => O.has(e.status) && e.cancelAt === null) && (yield* ot(o)) && (D.error("billing sync: a closed tenant still has a paying subscription — closing it", { tenant: o }), yield* rt(o).pipe(C.catchTag("BillingClosurePending", (e) => C.fail(new t({
1226
+ i.some((e) => O.has(e.status) && e.cancelAt === null) && (yield* ot(a)) && (D.error("billing sync: a closed tenant still has a paying subscription — closing it", { tenant: a }), yield* rt(a).pipe(C.catchTag("BillingClosurePending", (e) => C.fail(new x({
1227
1227
  source: "billing",
1228
1228
  message: e.message,
1229
1229
  transient: !0
1230
- })))), a = yield* M(S.listSubscriptions({ providerCustomerId: e }), T));
1230
+ })))), i = yield* M(S.listSubscriptions({ providerCustomerId: e }), T));
1231
1231
  let l = yield* P.stores.customers.getByProviderCustomerId(e, yield* L());
1232
- if (l === null || l.tenantId !== o) return yield* C.fail(f("Current native customer custody is required."));
1233
- for (let t of a) {
1234
- let n = yield* X(t.providerSubscriptionId, l);
1235
- if (n.providerCustomerId !== e) return yield* C.fail(f("The current subscription belongs to another customer."));
1236
- if (yield* W(o, n, r), s.push(Q(o, n, r)), n.plan !== null && O.has(n.status)) {
1237
- let e = w.meteredPriceIdsFor(n.plan).filter((e) => !n.priceIds.includes(e));
1232
+ if (l === null || l.tenantId !== a) return yield* C.fail(o("Current native customer custody is required."));
1233
+ for (let t of i) {
1234
+ let r = yield* X(t.providerSubscriptionId, l);
1235
+ if (r.providerCustomerId !== e) return yield* C.fail(o("The current subscription belongs to another customer."));
1236
+ if (yield* W(a, r, n), s.push(Q(a, r, n)), r.plan !== null && O.has(r.status)) {
1237
+ let e = w.meteredPriceIdsFor(r.plan).filter((e) => !r.priceIds.includes(e));
1238
1238
  e.length > 0 && (yield* M(S.addSubscriptionPrices({
1239
- providerSubscriptionId: n.providerSubscriptionId,
1239
+ providerSubscriptionId: r.providerSubscriptionId,
1240
1240
  priceIds: e
1241
1241
  }), T));
1242
1242
  }
1243
1243
  }
1244
- let u = new Set(a.map((e) => e.providerSubscriptionId));
1245
- for (let t of yield* P.stores.subscriptions.listByTenant(o)) {
1246
- if (!x(t.status) || u.has(t.providerSubscriptionId)) continue;
1247
- let n = yield* X(t.providerSubscriptionId, l);
1248
- if (n.providerCustomerId !== e) return yield* C.fail(f("The subscription belongs to another customer."));
1249
- yield* W(o, n, r), s.push(Q(o, n, r));
1244
+ let u = new Set(i.map((e) => e.providerSubscriptionId));
1245
+ for (let t of yield* P.stores.subscriptions.listByTenant(a)) {
1246
+ if (!f(t.status) || u.has(t.providerSubscriptionId)) continue;
1247
+ let r = yield* X(t.providerSubscriptionId, l);
1248
+ if (r.providerCustomerId !== e) return yield* C.fail(o("The subscription belongs to another customer."));
1249
+ yield* W(a, r, n), s.push(Q(a, r, n));
1250
1250
  }
1251
1251
  for (let e of s) yield* K(e);
1252
1252
  return {
1253
- tenantId: o,
1253
+ tenantId: a,
1254
1254
  events: s
1255
1255
  };
1256
1256
  }), Z = (e) => C.forEach(e, (e) => {
1257
- let t = n.onEvent?.[e._tag];
1257
+ let t = p.onEvent?.[e._tag];
1258
1258
  return t === void 0 ? C.void : t(e).pipe(C.catchCause((t) => C.sync(() => {
1259
1259
  D.error("billing: onEvent failed for a correction — the next sync of this tenant retries it", {
1260
1260
  event: e._tag,
@@ -1397,9 +1397,9 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1397
1397
  e,
1398
1398
  t,
1399
1399
  n
1400
- ].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) return yield* C.fail(_("Exact owned invoice reference identities are required."));
1400
+ ].every((e) => typeof e == "string" && e.length > 0 && e.length <= 191 && e.trim() === e && e.isWellFormed())) return yield* C.fail(d("Exact owned invoice reference identities are required."));
1401
1401
  let r = P.stores, i = yield* L(), a = yield* r.customers.getByProviderCustomerId(t, i);
1402
- if (a === null || a.tenantId !== e || a.provider !== S.name) return yield* C.fail(_("Positive current or retained customer custody is required."));
1402
+ if (a === null || a.tenantId !== e || a.provider !== S.name) return yield* C.fail(d("Positive current or retained customer custody is required."));
1403
1403
  let o = yield* r.historyWork.claim(a, n, k());
1404
1404
  if (o.kind !== "claimed") return {
1405
1405
  kind: o.kind,
@@ -1407,20 +1407,20 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1407
1407
  };
1408
1408
  let s = o.attempt, c = r.historyWork.hold(s, () => k().getTime());
1409
1409
  return yield* C.gen(function* () {
1410
- if (P.stores !== r) return yield* C.fail(_("Billing stores changed before invoice reference dispatch.", !0));
1410
+ if (P.stores !== r) return yield* C.fail(d("Billing stores changed before invoice reference dispatch.", !0));
1411
1411
  let n = yield* Y(e, o.work.providerInvoiceId, t).pipe(C.timeout("5 minutes"));
1412
- if (P.stores !== r) return yield* C.fail(_("Billing stores changed during invoice reference observation.", !0));
1412
+ if (P.stores !== r) return yield* C.fail(d("Billing stores changed during invoice reference observation.", !0));
1413
1413
  let i = yield* r.historyWork.observed(a, s, n, k());
1414
- return i === null || i.state !== "observed" && i.state !== "deferred" ? yield* C.fail(_("Invoice reference acknowledgement no longer owns its attempt.", !0)) : {
1414
+ return i === null || i.state !== "observed" && i.state !== "deferred" ? yield* C.fail(d("Invoice reference acknowledgement no longer owns its attempt.", !0)) : {
1415
1415
  kind: i.state === "observed" ? "observed" : "deferred",
1416
1416
  work: i
1417
1417
  };
1418
1418
  }).pipe(C.catch(() => C.gen(function* () {
1419
- return yield* r.historyWork.failed(a, s, k()), yield* C.fail(_("The invoice reference remains unconfirmed and retryable.", !0));
1419
+ return yield* r.historyWork.failed(a, s, k()), yield* C.fail(d("The invoice reference remains unconfirmed and retryable.", !0));
1420
1420
  })), C.ensuring(C.sync(c)));
1421
1421
  }), mt = () => C.gen(function* () {
1422
- let e = P.stores, t = () => P.stores === e ? C.void : C.fail(_("Billing stores changed during the invoice-history pass.", !0));
1423
- if (S.listInvoiceHistory === void 0 || S.fetchInvoiceSnapshot === void 0) return yield* C.fail(_("Complete account-owned invoice history and observations are required."));
1422
+ let e = P.stores, t = () => P.stores === e ? C.void : C.fail(d("Billing stores changed during the invoice-history pass.", !0));
1423
+ if (S.listInvoiceHistory === void 0 || S.fetchInvoiceSnapshot === void 0) return yield* C.fail(d("Complete account-owned invoice history and observations are required."));
1424
1424
  let n = yield* L(), r = yield* e.historyProgress.account(n, k());
1425
1425
  yield* t();
1426
1426
  let i = yield* e.customers.inventory(n, {
@@ -1506,16 +1506,16 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1506
1506
  customerCustodyId: o.id,
1507
1507
  ...s
1508
1508
  };
1509
- }).pipe(C.timeout("2 minutes"), C.mapError((e) => e instanceof t ? e : _("The bounded invoice-history pass timed out and remains retryable.", !0))), ht = (e, t) => C.gen(function* () {
1509
+ }).pipe(C.timeout("2 minutes"), C.mapError((e) => e instanceof x ? e : d("The bounded invoice-history pass timed out and remains retryable.", !0))), ht = (e, t) => C.gen(function* () {
1510
1510
  let n = P.stores;
1511
1511
  yield* R(e);
1512
1512
  let r = yield* n.subscriptionWrites.getRequest(e, t), i = yield* L();
1513
- return P.stores !== n || r !== null && (r.intent.provider !== S.name || r.intent.providerAccountId !== i.account.providerAccountId || r.intent.livemode !== i.account.livemode) ? yield* C.fail(f("Original billing operation custody requires reconciliation.")) : { phase: r?.phase ?? "not-found" };
1513
+ return P.stores !== n || r !== null && (r.intent.provider !== S.name || r.intent.providerAccountId !== i.account.providerAccountId || r.intent.livemode !== i.account.livemode) ? yield* C.fail(o("Original billing operation custody requires reconciliation.")) : { phase: r?.phase ?? "not-found" };
1514
1514
  }), gt = (e) => C.gen(function* () {
1515
1515
  let t = P.stores;
1516
1516
  yield* R(e);
1517
1517
  let n = yield* t.subscriptionWrites.getActive(e), r = yield* L();
1518
- if (P.stores !== t || n !== null && (n.intent.provider !== S.name || n.intent.providerAccountId !== r.account.providerAccountId || n.intent.livemode !== r.account.livemode)) return yield* C.fail(f("Original billing operation custody requires reconciliation."));
1518
+ if (P.stores !== t || n !== null && (n.intent.provider !== S.name || n.intent.providerAccountId !== r.account.providerAccountId || n.intent.livemode !== r.account.livemode)) return yield* C.fail(o("Original billing operation custody requires reconciliation."));
1519
1519
  if (n === null) return null;
1520
1520
  let i = n.phase;
1521
1521
  return i !== "prepared" && i !== "claimed" && i !== "dispatched" && i !== "acknowledged" ? null : {
@@ -1529,34 +1529,34 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1529
1529
  return {
1530
1530
  service: {
1531
1531
  prices: (e) => C.gen(function* () {
1532
- let n = S.fetchPrices;
1533
- if (n === void 0) return yield* C.fail(new t({
1532
+ let t = S.fetchPrices;
1533
+ if (t === void 0) return yield* C.fail(new x({
1534
1534
  source: "billing",
1535
1535
  message: `Billing provider "${S.name}" cannot read prices.`,
1536
1536
  transient: !1
1537
1537
  }));
1538
- let r = Date.now(), i = [...new Set(e)], a = i.filter((e) => {
1538
+ let n = Date.now(), r = [...new Set(e)], i = r.filter((e) => {
1539
1539
  let t = _t.get(e);
1540
- return t === void 0 || r - t.at > 6e4;
1541
- }), o = a.filter((e) => !$.has(e)), s = [];
1542
- if (o.length > 0) {
1540
+ return t === void 0 || n - t.at > 6e4;
1541
+ }), a = i.filter((e) => !$.has(e)), o = [];
1542
+ if (a.length > 0) {
1543
1543
  let e = { fiber: null };
1544
- for (let t of o) $.set(t, e);
1545
- let t = yield* C.forkDetach(n(o).pipe(C.tap((e) => C.sync(() => {
1546
- for (let t of o) _t.set(t, {
1547
- at: r,
1544
+ for (let t of a) $.set(t, e);
1545
+ let r = yield* C.forkDetach(t(a).pipe(C.tap((e) => C.sync(() => {
1546
+ for (let t of a) _t.set(t, {
1547
+ at: n,
1548
1548
  price: e.find((e) => e.id === t) ?? null
1549
1549
  });
1550
1550
  })), C.asVoid, C.ensuring(C.sync(() => {
1551
- for (let t of o) $.get(t) === e && $.delete(t);
1551
+ for (let t of a) $.get(t) === e && $.delete(t);
1552
1552
  }))));
1553
- e.fiber = t, s.push(t);
1553
+ e.fiber = r, o.push(r);
1554
1554
  }
1555
- for (let e of a) {
1555
+ for (let e of i) {
1556
1556
  let t = $.get(e)?.fiber;
1557
- t != null && !s.includes(t) && s.push(t);
1557
+ t != null && !o.includes(t) && o.push(t);
1558
1558
  }
1559
- return yield* C.forEach(s, (e) => ne.join(e), { discard: !0 }), i.flatMap((e) => {
1559
+ return yield* C.forEach(o, (e) => ne.join(e), { discard: !0 }), r.flatMap((e) => {
1560
1560
  let t = _t.get(e)?.price;
1561
1561
  return t ? [t] : [];
1562
1562
  });
@@ -1597,5 +1597,5 @@ var D = E({ scope: "@voltro/plugin-billing" }), re = 3, ie = 9e5, O = /* @__PURE
1597
1597
  },
1598
1598
  holder: P
1599
1599
  };
1600
- }, ue = (e) => w.succeed(n, e);
1600
+ }, ue = (e) => w.succeed(S, e);
1601
1601
  export { k as PRICE_CACHE_TTL_MS, ce as USAGE_KEY, le as USAGE_KEY_RULE, ue as billingServiceLayer, N as buildBillingService, se as makeStoreHolder, j as periodKey };