@voltro/plugin-billing 0.85.0 → 0.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,209 @@
1
+ import { BillingError as e, DEFAULT_PLAN as t } from "./types.js";
2
+ import { Effect as n } from "effect";
3
+ import { and as r, eq as i, id as a, table as o, text as s, timestamp as c } from "@voltro/database";
4
+ //#region src/dunning.ts
5
+ var l = "_voltro_billing_dunning_notices", u = o(l, {
6
+ id: a({ prefix: "bdun" }),
7
+ tenantId: s().maxLength(191),
8
+ episode: s().maxLength(32),
9
+ stepId: s().maxLength(64),
10
+ sentAt: c()
11
+ }).unique("byBillingDunningNotice", [
12
+ "tenantId",
13
+ "episode",
14
+ "stepId"
15
+ ]), d = "locked", f = [
16
+ {
17
+ id: "payment-failed",
18
+ afterHours: 0
19
+ },
20
+ {
21
+ id: "reminder",
22
+ afterHours: 72
23
+ },
24
+ {
25
+ id: "final-warning",
26
+ afterHours: 144
27
+ }
28
+ ], p = 168, m = "hard", h = (e, t, n) => {
29
+ if (e === void 0 || e.trim() === "") return t;
30
+ let r = Number(e);
31
+ if (!Number.isFinite(r) || r < 0) throw Error(`billingPlugin: ${n} must be a non-negative number, got '${e}'`);
32
+ return r;
33
+ }, g = (e, t) => {
34
+ let n = t.VOLTRO_BILLING_DUNNING;
35
+ if (n !== void 0 && n !== "" && n !== "on" && n !== "off") throw Error(`billingPlugin: VOLTRO_BILLING_DUNNING must be 'on' or 'off', got '${n}'`);
36
+ let r = n === "off" ? !1 : n === "on" ? !0 : e?.enabled ?? !0, i = t.VOLTRO_BILLING_LOCKOUT;
37
+ if (i !== void 0 && i !== "" && i !== "hard" && i !== "soft") throw Error(`billingPlugin: VOLTRO_BILLING_LOCKOUT must be 'hard' or 'soft', got '${i}'`);
38
+ let a = i === "hard" || i === "soft" ? i : e?.lockout ?? "hard", o = h(t.VOLTRO_BILLING_GRACE_HOURS, e?.graceHours ?? 168, "VOLTRO_BILLING_GRACE_HOURS"), s = e?.steps ?? f, c = t.VOLTRO_BILLING_DUNNING_STEP_HOURS, l = s;
39
+ if (c !== void 0 && c.trim() !== "") {
40
+ let e = c.split(",").map((e) => e.trim());
41
+ if (e.length !== s.length) throw Error(`billingPlugin: VOLTRO_BILLING_DUNNING_STEP_HOURS lists ${e.length} value(s) but the sequence declares ${s.length} step(s) (${s.map((e) => e.id).join(", ")})`);
42
+ l = s.map((t, n) => ({
43
+ id: t.id,
44
+ afterHours: h(e[n], t.afterHours, "VOLTRO_BILLING_DUNNING_STEP_HOURS")
45
+ }));
46
+ }
47
+ let u = /* @__PURE__ */ new Set();
48
+ for (let e of l) {
49
+ if (e.id === "locked") throw Error(`billingPlugin: '${d}' is the reserved lockout step id`);
50
+ if (u.has(e.id)) throw Error(`billingPlugin: duplicate dunning step id '${e.id}'`);
51
+ u.add(e.id);
52
+ }
53
+ return {
54
+ enabled: r,
55
+ graceHours: o,
56
+ lockout: a,
57
+ steps: [...l].sort((e, t) => e.afterHours - t.afterHours),
58
+ ...e?.notify === void 0 ? {} : { notify: e.notify },
59
+ ...e?.resolveRecipient === void 0 ? {} : { resolveRecipient: e.resolveRecipient },
60
+ ...e?.portalReturnUrl === void 0 ? {} : { portalReturnUrl: e.portalReturnUrl }
61
+ };
62
+ }, _ = 36e5, v = (e) => String(e.getTime()), y = (e, t) => new Date(e.getTime() + t * _), b = (e, t, n) => {
63
+ let r = (n.getTime() - t.getTime()) / _;
64
+ return e.filter((e) => r >= e.afterHours);
65
+ }, x = (e, n, r, i) => {
66
+ let a = {
67
+ tenantId: e?.tenantId ?? i ?? "",
68
+ lockout: n.lockout
69
+ };
70
+ if (e === null) return {
71
+ ...a,
72
+ plan: t,
73
+ billedPlan: t,
74
+ status: "none",
75
+ entitled: !0,
76
+ inGrace: !1,
77
+ graceEndsAt: null,
78
+ lockedSince: null
79
+ };
80
+ if (e.status === "active" || e.status === "trialing") return {
81
+ ...a,
82
+ plan: e.plan,
83
+ billedPlan: e.plan,
84
+ status: e.status,
85
+ entitled: !0,
86
+ inGrace: !1,
87
+ graceEndsAt: null,
88
+ lockedSince: null
89
+ };
90
+ if (e.status === "pastDue") {
91
+ if (!n.enabled) return {
92
+ ...a,
93
+ plan: t,
94
+ billedPlan: e.plan,
95
+ status: e.status,
96
+ entitled: !0,
97
+ inGrace: !1,
98
+ graceEndsAt: null,
99
+ lockedSince: null
100
+ };
101
+ if (e.pastDueSince === null) return {
102
+ ...a,
103
+ plan: e.plan,
104
+ billedPlan: e.plan,
105
+ status: e.status,
106
+ entitled: !0,
107
+ inGrace: !0,
108
+ graceEndsAt: null,
109
+ lockedSince: null
110
+ };
111
+ let i = y(e.pastDueSince, n.graceHours), o = r.getTime() >= i.getTime();
112
+ return {
113
+ ...a,
114
+ plan: o && n.lockout === "hard" ? t : e.plan,
115
+ billedPlan: e.plan,
116
+ status: e.status,
117
+ entitled: !o,
118
+ inGrace: !o,
119
+ graceEndsAt: i,
120
+ lockedSince: o ? i : null
121
+ };
122
+ }
123
+ return {
124
+ ...a,
125
+ plan: t,
126
+ billedPlan: e.plan,
127
+ status: e.status,
128
+ entitled: !0,
129
+ inGrace: !1,
130
+ graceEndsAt: null,
131
+ lockedSince: null
132
+ };
133
+ }, S = (e) => e.toISOString().slice(0, 10), C = (e) => {
134
+ let t = e.portalUrl, n = t === null ? "<p>Please update your payment method in the billing settings.</p>" : `<p><a href="${t}">Update your payment method</a></p>`, r = t === null ? "Please update your payment method in the billing settings." : `Update your payment method: ${t}`;
135
+ if (e.locked) return {
136
+ subject: "Your subscription has been suspended",
137
+ html: `<p>We were unable to collect payment, and your subscription is now suspended.</p>${n}`,
138
+ text: `We were unable to collect payment, and your subscription is now suspended.\n\n${r}`
139
+ };
140
+ let i = S(e.graceEndsAt), a = e.stepId === "payment-failed" ? "Your last payment could not be collected." : "Your payment is still outstanding.";
141
+ return {
142
+ subject: "Action needed: your payment could not be collected",
143
+ html: `<p>${a} Your subscription stays active until ${i}.</p>${n}`,
144
+ text: `${a} Your subscription stays active until ${i}.\n\n${r}`
145
+ };
146
+ }, w = (e) => (t) => t.to === null ? n.void : e.send({
147
+ to: t.to,
148
+ subject: t.subject,
149
+ html: t.html,
150
+ text: t.text
151
+ }).pipe(n.asVoid), T = (e, t, n) => `${e}\u0000${t}\u0000${n}`, E = () => {
152
+ let e = /* @__PURE__ */ new Map();
153
+ return {
154
+ claim: (t, r, i, a) => n.sync(() => {
155
+ let n = T(t, r, i);
156
+ return !e.has(n) && (e.set(n, {
157
+ tenantId: t,
158
+ episode: r,
159
+ stepId: i,
160
+ sentAt: a
161
+ }), !0);
162
+ }),
163
+ sentSteps: (t, r) => n.sync(() => [...e.values()].filter((e) => e.tenantId === t && e.episode === r))
164
+ };
165
+ }, D = () => `bdun_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`, O = (t) => ({
166
+ claim: (r, i, a, o) => n.tryPromise({
167
+ try: async () => {
168
+ let e = D(), n = await t.insertIgnore(l, {
169
+ id: e,
170
+ tenantId: r,
171
+ episode: i,
172
+ stepId: a,
173
+ sentAt: o
174
+ }, { conflictColumns: [
175
+ "tenantId",
176
+ "episode",
177
+ "stepId"
178
+ ] });
179
+ return String(n.id) === e;
180
+ },
181
+ catch: (t) => new e({
182
+ source: "dunningNoticeStore",
183
+ message: String(t?.message ?? t),
184
+ transient: !0
185
+ })
186
+ }),
187
+ sentSteps: (a, o) => n.tryPromise({
188
+ try: async () => (await t.query({
189
+ table: l,
190
+ predicate: r(i("tenantId", a), i("episode", o)),
191
+ order: [],
192
+ take: void 0,
193
+ skip: void 0,
194
+ projection: void 0
195
+ })).map((e) => ({
196
+ tenantId: String(e.tenantId),
197
+ episode: String(e.episode),
198
+ stepId: String(e.stepId),
199
+ sentAt: e.sentAt == null ? null : new Date(e.sentAt)
200
+ })),
201
+ catch: (t) => new e({
202
+ source: "dunningNoticeStore",
203
+ message: String(t?.message ?? t),
204
+ transient: !0
205
+ })
206
+ })
207
+ });
208
+ //#endregion
209
+ export { l as BILLING_DUNNING_NOTICES_TABLE, f as DEFAULT_DUNNING_STEPS, p as DEFAULT_GRACE_HOURS, m as DEFAULT_LOCKOUT, d as DUNNING_LOCK_STEP_ID, u as billingDunningNoticesTable, O as dataStoreDunningNoticeStore, C as defaultDunningEmail, b as dueSteps, w as dunningMailNotifier, v as episodeKeyOf, x as evaluateBillingEntitlement, y as graceEndOf, E as memoryDunningNoticeStore, g as resolveDunningConfig };
@@ -0,0 +1,30 @@
1
+ import { IapProviderDefinition } from '@voltro/plugin-economy/server';
2
+
3
+ export declare interface StripeIapWebOptions {
4
+ /** Stripe secret or restricted key; `sk_test_`/`rk_test_` for sandbox, `_live_` for production. */
5
+ readonly secretKey: string;
6
+ readonly environment: 'sandbox' | 'production';
7
+ /** The economy's application ID for this provider (an identifier you choose, e.g. the app name). */
8
+ readonly applicationId: string;
9
+ /** Origins players return to after paying (`https://game.example`). */
10
+ readonly returnOrigins: readonly string[];
11
+ /** Minutes a started checkout stays open (Stripe allows 30–1440; default 30). */
12
+ readonly checkoutTtlMinutes?: number;
13
+ /** Signing secret of a Stripe webhook endpoint (`whsec_…`) pointed at the economy's notification
14
+ * route (`/_voltro/economy/iap/web`). Set: refunds and lost disputes revoke the purchase
15
+ * (`charge.refunded`, `charge.dispute.created`, `charge.dispute.closed`), and paid checkouts and
16
+ * subscription renewals arrive without the player (`checkout.session.completed`, `invoice.paid`). */
17
+ readonly webhookSecret?: string;
18
+ /** Transport for tests; defaults to global `fetch`. */
19
+ readonly fetch?: typeof fetch;
20
+ /** Clock for webhook timestamps (tests). */
21
+ readonly now?: () => number;
22
+ }
23
+
24
+ /** A Stripe Checkout provider for the economy's `web` channel. */
25
+ export declare const stripeIapWebProvider: (options: StripeIapWebOptions) => IapProviderDefinition;
26
+
27
+ /** The request ID a renewal invoice is redeemed under (economy identifiers have no `_`). */
28
+ export declare const stripeRenewalRequestId: (invoice: string) => string;
29
+
30
+ export { }
@@ -0,0 +1,266 @@
1
+ import { StripeRestError as e, stripeRest as t } from "./stripeRest.js";
2
+ import { Effect as n } from "effect";
3
+ import { createHmac as r, timingSafeEqual as i } from "node:crypto";
4
+ import { EconomyError as a, economyError as o } from "@voltro/plugin-economy/errors";
5
+ import { iapCurrentStatePort as s, iapVerificationPort as c, issueVerifiedIapNotification as l } from "@voltro/plugin-economy/server";
6
+ //#region src/economy.ts
7
+ var u = /* @__PURE__ */ new Set([
8
+ "BIF",
9
+ "CLP",
10
+ "DJF",
11
+ "GNF",
12
+ "JPY",
13
+ "KMF",
14
+ "KRW",
15
+ "MGA",
16
+ "PYG",
17
+ "RWF",
18
+ "UGX",
19
+ "VND",
20
+ "VUV",
21
+ "XAF",
22
+ "XOF",
23
+ "XPF"
24
+ ]), d = /* @__PURE__ */ new Set([
25
+ "BHD",
26
+ "JOD",
27
+ "KWD",
28
+ "OMR",
29
+ "TND"
30
+ ]), f = (e) => u.has(e) ? 0 : d.has(e) ? 3 : 2, p = /^cs_(test|live)_[A-Za-z0-9]{1,200}$/, m = /^in_[A-Za-z0-9]{1,200}$/, h = /^pi_[A-Za-z0-9]{1,200}$/, g = /^sub_[A-Za-z0-9]{1,200}$/, _ = /^cus_[A-Za-z0-9]{1,200}$/, v = (e) => "renew." + e.replace("_", "."), y = (t) => t instanceof a ? t : o(t instanceof e && t.status >= 400 && t.status < 500 && t.status !== 429 ? "forbidden" : "unavailable"), b = (e) => {
31
+ let u = /^(sk|rk)_live_/.test(e.secretKey), d = /^(sk|rk)_test_/.test(e.secretKey);
32
+ if (!u && !d || u !== (e.environment === "production")) throw o("invalid_input");
33
+ let b = e.checkoutTtlMinutes ?? 30;
34
+ if (!Number.isInteger(b) || b < 30 || b > 1440) throw o("invalid_input");
35
+ let x = t(e.secretKey, e.fetch ?? fetch), S = (e) => n.tryPromise({
36
+ try: e,
37
+ catch: y
38
+ }), C = () => S(() => x.get("/v1/checkout/sessions", { limit: 1 })).pipe(n.asVoid), w = (t, n, r) => t.voltro_account === n && t.voltro_application === e.applicationId && t.voltro_offer === r.offer.id && t.voltro_offer_version === r.offer.version, T = (e) => n.tryPromise({
39
+ try: e,
40
+ catch: (e) => e instanceof a ? e : o("unavailable")
41
+ }), E = (t) => ({
42
+ initialize: C,
43
+ start: (t) => T(async () => {
44
+ let n = new URL(t.returnUrl);
45
+ n.searchParams.set("checkout", "success");
46
+ let r = new URL(t.returnUrl);
47
+ r.searchParams.set("checkout", "cancel");
48
+ let i = {
49
+ voltro_account: t.accountToken,
50
+ voltro_offer: t.product.offer.id,
51
+ voltro_offer_version: t.product.offer.version,
52
+ voltro_application: e.applicationId
53
+ }, a = t.product.kind === "subscription", s = await x.post("/v1/checkout/sessions", {
54
+ mode: a ? "subscription" : "payment",
55
+ line_items: [{
56
+ price: t.product.storeProductId,
57
+ quantity: 1
58
+ }],
59
+ success_url: n.toString() + "&checkout_id={CHECKOUT_SESSION_ID}",
60
+ cancel_url: r.toString(),
61
+ client_reference_id: t.accountToken,
62
+ expires_at: Math.floor(t.at / 1e3) + b * 60,
63
+ metadata: {
64
+ ...i,
65
+ voltro_request: t.requestId
66
+ },
67
+ ...a ? { subscription_data: { metadata: i } } : {}
68
+ });
69
+ if (!s.url || !p.test(s.id)) throw o("invalid_record");
70
+ return {
71
+ checkoutId: s.id,
72
+ redirectUrl: s.url,
73
+ expiresAt: s.expires_at * 1e3
74
+ };
75
+ })
76
+ }), D = async (t, n, r, i) => {
77
+ let a = await x.get(`/v1/invoices/${t}`, { expand: ["payments"] }), s = a.parent?.subscription_details, c = s?.subscription ?? null, l = a.lines.data.filter((e) => e.parent?.subscription_item_details && !e.parent.subscription_item_details.proration && e.pricing?.price_details?.price === i.storeProductId), d = (a.payments?.data ?? []).find((e) => e.status === "paid" && e.payment.type === "payment_intent")?.payment.payment_intent;
78
+ if (a.id !== t || a.status !== "paid" || a.livemode !== u || c === null || !g.test(c) || n !== null && c !== n || !w(s?.metadata ?? {}, r, i) || l.length !== 1 || l[0].quantity !== 1 || !(a.amount_paid > 0) || !d || !h.test(d)) throw o("forbidden");
79
+ let p = l[0], m = a.currency.toUpperCase();
80
+ return {
81
+ invoice: a,
82
+ facts: {
83
+ channel: "web",
84
+ environment: e.environment,
85
+ applicationId: e.applicationId,
86
+ transactionId: d,
87
+ originalTransactionId: c,
88
+ storeProductId: i.storeProductId,
89
+ kind: "subscription",
90
+ quantity: 1,
91
+ purchasedAt: p.period.start * 1e3,
92
+ expiresAt: p.period.end * 1e3,
93
+ paid: {
94
+ currency: m,
95
+ units: String(a.amount_paid),
96
+ scale: f(m)
97
+ },
98
+ acknowledgement: "none",
99
+ consumption: "none"
100
+ }
101
+ };
102
+ }, O = (t) => c(t, {
103
+ initialize: C,
104
+ verify: (t) => n.suspend(() => {
105
+ let r = t.intent.receipt, i = t.product.kind === "subscription";
106
+ return i && m.test(r) ? t.intent.requestId === v(r) ? S(async () => {
107
+ let { invoice: e, facts: n } = await D(r, null, t.accountToken, t.product);
108
+ if (e.billing_reason === "subscription_create") throw o("forbidden");
109
+ return n;
110
+ }) : n.fail(o("forbidden")) : p.test(r) ? S(async () => {
111
+ let n = await x.get(`/v1/checkout/sessions/${r}`, { expand: ["line_items"] }), a = n.metadata ?? {}, s = n.line_items?.data ?? [], c = s[0];
112
+ if (n.id !== r || n.mode !== (i ? "subscription" : "payment") || n.status !== "complete" || n.payment_status !== "paid" || n.livemode !== u || !w(a, t.accountToken, t.product) || a.voltro_request !== t.intent.requestId || s.length !== 1 || c?.price?.id !== t.product.storeProductId || !c.quantity || n.currency === null || n.amount_total === null) throw o("forbidden");
113
+ if (i) {
114
+ if (!n.invoice || !m.test(n.invoice) || !n.subscription) throw o("forbidden");
115
+ return (await D(n.invoice, n.subscription, t.accountToken, t.product)).facts;
116
+ }
117
+ let l = n.currency.toUpperCase();
118
+ return {
119
+ channel: "web",
120
+ environment: e.environment,
121
+ applicationId: e.applicationId,
122
+ transactionId: n.payment_intent ?? n.id,
123
+ originalTransactionId: null,
124
+ storeProductId: c.price.id,
125
+ kind: t.product.kind,
126
+ quantity: c.quantity,
127
+ purchasedAt: n.created * 1e3,
128
+ expiresAt: null,
129
+ paid: {
130
+ currency: l,
131
+ units: String(n.amount_total),
132
+ scale: f(l)
133
+ },
134
+ acknowledgement: "none",
135
+ consumption: "none"
136
+ };
137
+ }) : n.fail(o("forbidden"));
138
+ })
139
+ }), k = e.webhookSecret, A = e.now ?? Date.now;
140
+ if (k !== void 0 && !/^whsec_[A-Za-z0-9+/=_-]{8,}$/.test(k)) throw o("invalid_input");
141
+ let j = (e) => {
142
+ let t = e.headers?.["stripe-signature"], n = /* @__PURE__ */ new Map();
143
+ for (let e of (t ?? "").split(",")) {
144
+ let [t, r] = e.split("=");
145
+ t && r && n.set(t, [...n.get(t) ?? [], r]);
146
+ }
147
+ let a = Number(n.get("t")?.[0]), s = r("sha256", k).update(`${n.get("t")?.[0]}.${e.body}`).digest();
148
+ if (!(n.get("v1") ?? []).some((e) => /^[0-9a-f]{64}$/.test(e) && i(Buffer.from(e, "hex"), s)) || !Number.isSafeInteger(a) || Math.abs(A() / 1e3 - a) > 300) throw o("forbidden");
149
+ let c = JSON.parse(e.body);
150
+ if (typeof c.id != "string" || !/^evt_[A-Za-z0-9]{1,200}$/.test(c.id) || typeof c.type != "string" || typeof c.created != "number" || c.livemode !== u) throw o("invalid_record");
151
+ return {
152
+ id: c.id,
153
+ type: c.type,
154
+ created: c.created,
155
+ object: c.data?.object ?? {}
156
+ };
157
+ }, M = (e) => e instanceof a ? e : o("invalid_record"), N = (t) => ({
158
+ initialize: () => n.void,
159
+ verify: (r) => n.try({
160
+ try: () => {
161
+ let n = j(r), i = n.object, a = typeof i.payment_intent == "string" && h.test(i.payment_intent) ? i.payment_intent : null, o = a !== null && (n.type === "charge.refunded" || n.type === "charge.dispute.created" || n.type === "charge.dispute.closed");
162
+ return l({
163
+ channel: "web",
164
+ applicationId: t.applicationId,
165
+ environment: e.environment,
166
+ noticeId: n.id,
167
+ sourceType: "web." + n.type.replace(/[^a-z._]/g, "").slice(0, 100),
168
+ kind: o ? n.type === "charge.dispute.created" ? "review" : "voided" : "test",
169
+ occurredAt: Math.min(n.created * 1e3, A()),
170
+ transactionId: o ? a : null,
171
+ originalTransactionId: null,
172
+ storeProductId: null
173
+ }, { event: {
174
+ id: n.id,
175
+ type: n.type
176
+ } });
177
+ },
178
+ catch: M
179
+ })
180
+ }), P = (e) => typeof e == "string" ? e : "";
181
+ return {
182
+ channel: "web",
183
+ environment: e.environment,
184
+ applicationId: e.applicationId,
185
+ checkoutReturnOrigins: e.returnOrigins,
186
+ create: O,
187
+ createCheckout: E,
188
+ createManagement: (t) => ({
189
+ initialize: C,
190
+ open: (t) => S(async () => {
191
+ for (let n of t.originals) {
192
+ if (!g.test(n)) continue;
193
+ let r = await x.get(`/v1/subscriptions/${n}`), i = r.metadata ?? {};
194
+ if (r.id === n && r.livemode === u && _.test(r.customer) && i.voltro_account === t.accountToken && i.voltro_application === e.applicationId) return { url: (await x.post("/v1/billing_portal/sessions", {
195
+ customer: r.customer,
196
+ return_url: t.returnUrl
197
+ })).url };
198
+ }
199
+ throw o("not_found");
200
+ })
201
+ }),
202
+ ...k === void 0 ? {} : {
203
+ createNotifications: N,
204
+ createCurrentState: (t) => s({
205
+ realMoney: !0,
206
+ channel: "web",
207
+ applicationId: t.applicationId,
208
+ environment: e.environment,
209
+ accounts: t.accounts,
210
+ now: t.now
211
+ }, {
212
+ initialize: C,
213
+ read: (e) => S(async () => {
214
+ let n = e.facts.transactionId;
215
+ if (!h.test(n)) throw o("forbidden");
216
+ let r = await x.get(`/v1/payment_intents/${n}`, { expand: ["latest_charge"] });
217
+ if (r.id !== n || r.livemode !== u || !r.latest_charge || !(r.amount_received > 0)) throw o("forbidden");
218
+ let i = r.latest_charge.dispute !== null && (await x.get(`/v1/disputes/${r.latest_charge.dispute}`)).status === "lost", a = r.amount_received, s = i ? a : Math.min(r.latest_charge.amount_refunded, a), c = (e, t) => t === 0 ? e : c(t, e % t), l = c(s, a) || 1, d = s / l, f = a / l;
219
+ f > 1e5 && (d = s === a ? 1 : Math.floor(s * 1e5 / a), f = s === a ? 1 : 1e5);
220
+ let p = t.now();
221
+ return {
222
+ orderId: e.orderId,
223
+ channel: "web",
224
+ state: d === 0 ? "active" : d === f ? "revoked" : "partially-refunded",
225
+ refundNumerator: d,
226
+ refundDenominator: f,
227
+ observedAt: p,
228
+ revokedAt: d === 0 ? null : p
229
+ };
230
+ })
231
+ }),
232
+ createDeliveries: (t) => ({
233
+ initialize: () => n.void,
234
+ read: (t) => n.try({
235
+ try: () => {
236
+ let n = j(t), r = n.object;
237
+ if (n.type === "checkout.session.completed" || n.type === "checkout.session.async_payment_succeeded") {
238
+ let t = r.metadata ?? {};
239
+ return r.payment_status !== "paid" || !p.test(P(r.id)) || t.voltro_application !== e.applicationId ? null : {
240
+ accountToken: P(t.voltro_account),
241
+ requestId: P(t.voltro_request),
242
+ offerId: P(t.voltro_offer),
243
+ offerVersion: P(t.voltro_offer_version),
244
+ receipt: P(r.id)
245
+ };
246
+ }
247
+ if (n.type === "invoice.paid") {
248
+ let t = r.parent?.subscription_details?.metadata ?? {};
249
+ return r.billing_reason === "subscription_create" || !m.test(P(r.id)) || t.voltro_application !== e.applicationId ? null : {
250
+ accountToken: P(t.voltro_account),
251
+ requestId: v(P(r.id)),
252
+ offerId: P(t.voltro_offer),
253
+ offerVersion: P(t.voltro_offer_version),
254
+ receipt: P(r.id)
255
+ };
256
+ }
257
+ return null;
258
+ },
259
+ catch: M
260
+ })
261
+ })
262
+ }
263
+ };
264
+ };
265
+ //#endregion
266
+ export { b as stripeIapWebProvider, v as stripeRenewalRequestId };
@@ -0,0 +1,41 @@
1
+ import { BillingService as e, EntitlementExceeded as t, SubscriptionLocked as n } from "./types.js";
2
+ import { Effect as r } from "effect";
3
+ //#region src/entitlement.ts
4
+ var i = (e, t, n, r) => ({
5
+ allowed: !Number.isFinite(t) || r <= 0 || n + r <= t,
6
+ entitlement: e,
7
+ limit: t,
8
+ used: n,
9
+ cost: r
10
+ }), a = (e) => e.tenantId, o = (n, i, o) => r.gen(function* () {
11
+ let s = a(n.request.subject);
12
+ if (s === null) return o <= 0 ? void 0 : yield* r.fail(new t({
13
+ entitlement: i,
14
+ limit: 0,
15
+ used: 0,
16
+ cost: o
17
+ }));
18
+ yield* (yield* e).consumeEntitlement(s, i, o);
19
+ }), s = (t) => r.gen(function* () {
20
+ let i = a(t.request.subject);
21
+ if (i === null) return;
22
+ let o = yield* (yield* e).entitlementStatus(i);
23
+ if (!o.entitled) return yield* r.fail(new n({
24
+ tenantId: i,
25
+ status: o.status,
26
+ lockedSince: (o.lockedSince ?? /* @__PURE__ */ new Date()).toISOString(),
27
+ lockout: o.lockout
28
+ }));
29
+ }), c = (e, n) => (i, a) => {
30
+ let o = e[a.tag];
31
+ if (o === void 0) return i;
32
+ let s = o.cost ?? 1, c = a.subject.tenantId;
33
+ return c === null ? s <= 0 ? i : r.fail(new t({
34
+ entitlement: o.entitlement,
35
+ limit: 0,
36
+ used: 0,
37
+ cost: s
38
+ })) : r.flatMap(n.consumeEntitlement(c, o.entitlement, s), () => i);
39
+ };
40
+ //#endregion
41
+ export { c as buildEnforceInterceptor, i as evaluateEntitlement, s as requireEntitled, o as requireEntitlement };
@@ -0,0 +1,72 @@
1
+ import { BillingError as e } from "./types.js";
2
+ import { captureProviderAccount as t, sameProviderAccount as n } from "./providerIdentity.js";
3
+ import { Effect as r, Schema as i } from "effect";
4
+ import { beginIdempotent as a, failIdempotent as o, finishIdempotent as s, holdIdempotentClaim as c, memoryIdempotencyStore as l, prepareIdempotentInput as u, systemSubject as d } from "@voltro/protocol";
5
+ //#region src/eventDelivery.ts
6
+ var f = 864e5, p = (t) => new e({
7
+ source: "billing.delivery",
8
+ message: t,
9
+ transient: !0
10
+ }), m = (m) => {
11
+ let h = l(), g, _ = d("billing.provider-delivery", []);
12
+ return (l) => r.tryPromise({
13
+ try: async () => {
14
+ let e = structuredClone(l);
15
+ if (e.rejected) throw p("The provider event could not be normalized and requires reconciliation.");
16
+ if (typeof e.id != "string" || !e.id || e.id.trim() !== e.id || e.createdAt !== null && (!(e.createdAt instanceof Date) || !Number.isFinite(e.createdAt.getTime()))) throw p("The verified provider delivery requires exact identity and time evidence.");
17
+ let d = m.receipts?.store() ?? h;
18
+ if (g === void 0) {
19
+ let e = m.provider.fetchAccountIdentity?.bind(m.provider);
20
+ if (e === void 0) throw p("Account-qualified provider delivery is unsupported.");
21
+ let i = t(await r.runPromise(e()));
22
+ if (g !== void 0 && !n(g, i)) throw p("The provider delivery account changed.");
23
+ g ??= i;
24
+ }
25
+ let v = g, y = JSON.stringify([
26
+ "voltro.billing-delivery.v2",
27
+ m.provider.name,
28
+ m.receipts?.scope ?? "standalone",
29
+ v.providerAccountId,
30
+ v.livemode
31
+ ]), b = await u(i.Unknown, e, _), x = await a(d, y, e.id, b.fingerprint, f, Date.now());
32
+ if (x.kind === "replay") {
33
+ if (x.response.status !== 204 || x.response.body !== null) throw p("The retained delivery receipt is invalid.");
34
+ return "replayed";
35
+ }
36
+ if (x.kind !== "fresh") throw p("The provider delivery is busy or its retained input needs reconciliation.");
37
+ let S = c(d, x.claim);
38
+ try {
39
+ if (!await d.renew(x.claim, Date.now())) throw p("The provider delivery claim changed before processing.");
40
+ let t = e.event, n = e.providerCustomerId ?? (t !== null && "providerCustomerId" in t ? t.providerCustomerId : null);
41
+ if (t !== null && "providerCustomerId" in t && e.providerCustomerId !== null && t.providerCustomerId !== e.providerCustomerId) throw p("The provider delivery has inconsistent customer identities.");
42
+ let i = t?._tag === "invoicePaid" || t?._tag === "invoicePaymentFailed", a = n !== null && t?._tag !== "customerUnlinked" && !i, o = [];
43
+ if (t !== null && (!a || t._tag !== "subscriptionUpserted" && t._tag !== "subscriptionCanceled" && t._tag !== "customerLinked") && o.push(await r.runPromise(m.service.applyEvent(t))), a) {
44
+ let e = await r.runPromise(m.service.syncCustomer(n, t !== null && "tenantId" in t && typeof t.tenantId == "string" ? t.tenantId : void 0));
45
+ o.push(...e.events);
46
+ }
47
+ for (let t of o) {
48
+ if (!await d.renew(x.claim, Date.now())) throw p("The provider delivery claim changed before callback dispatch.");
49
+ let n = m.onEvent?.[t._tag];
50
+ n !== void 0 && await r.runPromise(n(t, Object.freeze({
51
+ provider: m.provider.name,
52
+ providerEventId: e.id,
53
+ receiptScope: y,
54
+ ...v
55
+ })));
56
+ }
57
+ if (!await s(d, x.claim, {
58
+ status: 204,
59
+ body: null
60
+ }, Date.now())) throw p("Delivery processing finished without confirmed receipt ownership.");
61
+ return "processed";
62
+ } catch (e) {
63
+ throw await o(d, x.claim), e;
64
+ } finally {
65
+ S();
66
+ }
67
+ },
68
+ catch: (t) => t instanceof e ? t : p("Provider delivery processing failed and remains retryable.")
69
+ });
70
+ };
71
+ //#endregion
72
+ export { m as makeBillingEventDelivery };
@@ -0,0 +1,20 @@
1
+ import { id as e, table as t, text as n, timestamp as r } from "@voltro/database";
2
+ //#region src/flushClaim.ts
3
+ var i = "_voltro_billing_flush_claims", a = t(i, {
4
+ id: e({ scheme: "numeric" }),
5
+ windowKey: n(),
6
+ claimedBy: n(),
7
+ claimedAt: r().default("now")
8
+ }).unique("billingFlushClaimWindow", ["windowKey"]), o = (e, t) => `billing-flush:${Math.floor(e / Math.max(1, t))}`, s = async (e, t, n, r) => {
9
+ try {
10
+ return (await e.insertIgnore(i, {
11
+ windowKey: t,
12
+ claimedBy: n,
13
+ claimedAt: new Date(r)
14
+ }, { conflictColumns: ["windowKey"] })).claimedBy === n;
15
+ } catch {
16
+ return !0;
17
+ }
18
+ };
19
+ //#endregion
20
+ export { i as BILLING_FLUSH_CLAIMS_TABLE, a as billingFlushClaimsTable, s as claimFlushWindow, o as flushWindowKey };