@voltro/plugin-billing 0.89.2 → 0.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +1943 -0
  2. package/README.md +0 -435
  3. package/THIRD-PARTY-NOTICES.md +22 -646
  4. package/dist/catalog.js +169 -70
  5. package/dist/custodyInventory.js +101 -65
  6. package/dist/dunning.js +14 -6
  7. package/dist/eventDelivery.js +14 -5
  8. package/dist/historicalUsage.js +94 -0
  9. package/dist/index.d.ts +777 -68
  10. package/dist/index.js +354 -233
  11. package/dist/invoiceHistoryJournal.js +204 -179
  12. package/dist/invoiceHistoryProgress.js +130 -106
  13. package/dist/invoiceHistoryWork.js +188 -186
  14. package/dist/invoicePaymentEpoch.js +145 -0
  15. package/dist/invoicePaymentObservation.js +64 -0
  16. package/dist/invoiceSnapshot.js +56 -46
  17. package/dist/invoiceStore.js +124 -90
  18. package/dist/paidInvoiceCoverage.js +84 -0
  19. package/dist/plans.js +15 -2
  20. package/dist/providers.js +149 -92
  21. package/dist/provision.js +84 -73
  22. package/dist/rpc.d.ts +53 -13
  23. package/dist/rpc.js +141 -78
  24. package/dist/service.js +1208 -722
  25. package/dist/stores.js +240 -148
  26. package/dist/stripeIdentity.js +17 -17
  27. package/dist/stripeInvoiceHistory.js +21 -21
  28. package/dist/stripeInvoicePayments.js +129 -0
  29. package/dist/stripeInvoiceSnapshot.js +65 -46
  30. package/dist/stripeProvider.js +570 -201
  31. package/dist/stripeRest.js +10 -10
  32. package/dist/subscriptionObservation.js +93 -0
  33. package/dist/subscriptionWriteStore.js +325 -0
  34. package/dist/table.js +75 -66
  35. package/dist/types.d.ts +415 -27
  36. package/dist/types.js +21 -4
  37. package/dist/web/index.d.ts +93 -3
  38. package/dist/web/index.js +76 -33
  39. package/dist/web/writeRequest.js +65 -0
  40. package/package.json +9 -9
package/dist/catalog.js CHANGED
@@ -1,7 +1,18 @@
1
- import { Stripe as e } from "./stripeClient.js";
2
- import { STRIPE_WEBHOOK_EVENTS as t } from "./stripeProvider.js";
1
+ import { STRIPE_WEBHOOK_EVENTS as e } from "./stripeProvider.js";
2
+ import { STRIPE_API_VERSION as t } from "./stripeRest.js";
3
3
  // src/catalog.ts
4
- var n = e.API_VERSION, r = [
4
+ var n = (e) => {
5
+ let t = e.retired ?? {}, n = {
6
+ prices: new Set(e.products.map((e) => e.price.lookupKey)),
7
+ products: new Set(e.products.map((e) => e.key)),
8
+ meters: new Set(e.meters.map((e) => e.eventName))
9
+ };
10
+ return [
11
+ "prices",
12
+ "products",
13
+ "meters"
14
+ ].flatMap((e) => (t[e] ?? []).filter((t) => n[e].has(t)).map((t) => `${e.slice(0, -1)} ${t}`));
15
+ }, r = [
5
16
  "Checkout → \"Limit customers to one subscription\" (with the customer portal login link enabled) — Stripe's own refusal of a second subscription",
6
17
  "Smart Retries + failed-payment emails (Billing → Revenue recovery)",
7
18
  "invoice branding and email settings",
@@ -96,13 +107,33 @@ var n = e.API_VERSION, r = [
96
107
  },
97
108
  id: null
98
109
  };
99
- }, c = (e, t, n, r) => {
110
+ }, c = (e) => e.upTo === "inf" ? null : e.upTo, l = /^(?:0|[1-9][0-9]*)(?:\.[0-9]{1,12})?$/, u = (e, t) => e !== null && l.test(e) && l.test(t) && d(e) === d(t), d = (e) => {
111
+ let [t = "0", n = ""] = e.split("."), r = n.replace(/0+$/, "");
112
+ return r.length === 0 ? t : `${t}.${r}`;
113
+ }, f = (e) => e.tiers.some((e) => e.unitAmount !== void 0 && e.unitAmountDecimal !== void 0 || e.unitAmountDecimal !== void 0 && !l.test(e.unitAmountDecimal)), p = (e, t) => {
114
+ let n = [];
115
+ (t.billing_scheme ?? "per_unit") !== "tiered" && n.push("billing_scheme"), (t.tiers_mode ?? null) !== e.mode && n.push("tiers_mode");
116
+ let r = t.tiers ?? [];
117
+ return r.length === e.tiers.length ? (e.tiers.forEach((e, t) => {
118
+ let i = r[t];
119
+ i.up_to !== c(e) && n.push(`tiers[${t}].up_to`), e.unitAmount !== void 0 && i.unit_amount !== e.unitAmount && n.push(`tiers[${t}].unit_amount`), e.unitAmountDecimal !== void 0 && !u(i.unit_amount_decimal ?? (i.unit_amount === null ? null : String(i.unit_amount)), e.unitAmountDecimal) && n.push(`tiers[${t}].unit_amount_decimal`), e.flatAmount !== void 0 && i.flat_amount !== e.flatAmount && n.push(`tiers[${t}].flat_amount`);
120
+ }), n) : (n.push("tiers"), n);
121
+ }, m = (e) => e.tiers.length > 0 && e.tiers.at(-1).upTo === "inf" && e.tiers.every((e) => e.unitAmount !== void 0 || e.unitAmountDecimal !== void 0 || e.flatAmount !== void 0), h = (e, t, n, r) => {
100
122
  let i = [];
101
- return r.product !== t && i.push("product"), r.currency !== e.currency && i.push("currency"), r.unit_amount !== e.unitAmount && i.push("unit_amount"), r.recurring?.interval !== e.interval && i.push("interval"), r.recurring?.usage_type !== e.usageType && i.push("usage_type"), e.usageType === "metered" && r.recurring?.meter !== n && i.push("meter"), r.tax_behavior !== e.taxBehavior && i.push("tax_behavior"), i;
102
- }, l = (e, t, n, r) => ({
123
+ return r.product !== t && i.push("product"), r.currency !== e.currency && i.push("currency"), e.tiers === void 0 ? (r.billing_scheme ?? "per_unit") !== "per_unit" && i.push("billing_scheme") : i.push(...p(e.tiers, r)), e.unitAmount !== void 0 && r.unit_amount !== e.unitAmount && i.push("unit_amount"), r.recurring?.interval !== e.interval && i.push("interval"), r.recurring?.usage_type !== e.usageType && i.push("usage_type"), e.usageType === "metered" && r.recurring?.meter !== n && i.push("meter"), r.tax_behavior !== e.taxBehavior && i.push("tax_behavior"), i;
124
+ }, g = (e) => ({
125
+ billing_scheme: "tiered",
126
+ tiers_mode: e.mode,
127
+ tiers: e.tiers.map((e) => ({
128
+ up_to: e.upTo,
129
+ ...e.unitAmount === void 0 ? {} : { unit_amount: e.unitAmount },
130
+ ...e.unitAmountDecimal === void 0 ? {} : { unit_amount_decimal: e.unitAmountDecimal },
131
+ ...e.flatAmount === void 0 ? {} : { flat_amount: e.flatAmount }
132
+ }))
133
+ }), _ = (e, t, n, r, i) => ({
103
134
  product: t,
104
135
  currency: e.currency,
105
- unit_amount: e.unitAmount,
136
+ ...i,
106
137
  recurring: {
107
138
  interval: e.interval,
108
139
  usage_type: e.usageType,
@@ -112,7 +143,7 @@ var n = e.API_VERSION, r = [
112
143
  lookup_key: e.lookupKey,
113
144
  ...r ? { transfer_lookup_key: !0 } : {},
114
145
  metadata: { voltro_key: e.lookupKey }
115
- }), u = (e, t, n, r, i, a) => {
146
+ }), v = (e, t, n, r, i, a) => {
116
147
  let o = `price ${e.lookupKey}`;
117
148
  if (t === null) return {
118
149
  finding: {
@@ -130,20 +161,46 @@ var n = e.API_VERSION, r = [
130
161
  },
131
162
  id: null
132
163
  };
164
+ if (e.tiers !== void 0 && e.unitAmount !== void 0) return {
165
+ finding: {
166
+ kind: "manual",
167
+ object: o,
168
+ detail: "declares both a flat unitAmount and tiers — a price is one or the other"
169
+ },
170
+ id: null
171
+ };
172
+ if (e.tiers !== void 0 && f(e.tiers)) return {
173
+ finding: {
174
+ kind: "manual",
175
+ object: o,
176
+ detail: "a tier declares both unitAmount and unitAmountDecimal, or a decimal amount Stripe does not accept (at most 12 decimal places)"
177
+ },
178
+ id: null
179
+ };
180
+ let s = e.tiers === void 0 ? e.unitAmount === void 0 ? null : { unit_amount: e.unitAmount } : m(e.tiers) ? g(e.tiers) : null;
133
181
  if (r !== null) {
134
- let i = c(e, t, n, r);
182
+ let i = h(e, t, n, r);
135
183
  if (i.length > 0) {
136
- let s = {
184
+ let c = s ?? (e.tiers === void 0 && r.unit_amount !== null ? { unit_amount: r.unit_amount } : null);
185
+ if (c === null) return {
186
+ finding: {
187
+ kind: "manual",
188
+ object: o,
189
+ detail: `${i.join(", ")} differ and the catalog cannot rebuild the amounts — replace it in the Dashboard`
190
+ },
191
+ id: r.id
192
+ };
193
+ let l = {
137
194
  method: "POST",
138
195
  path: "/v1/prices",
139
- params: l(e, t, n, !0)
196
+ params: _(e, t, n, !0, c)
140
197
  };
141
198
  return a ? {
142
199
  finding: {
143
200
  kind: "drift",
144
201
  object: o,
145
202
  detail: `replaced (${i.join(", ")}); existing subscriptions keep the old price`,
146
- apply: s
203
+ apply: l
147
204
  },
148
205
  id: null
149
206
  } : {
@@ -175,16 +232,23 @@ var n = e.API_VERSION, r = [
175
232
  id: r.id
176
233
  };
177
234
  }
178
- let s = i.filter((r) => r.active && r.lookup_key === null && c(e, t, n, r).length === 0)[0];
179
- return s === void 0 ? {
235
+ let c = i.filter((r) => r.active && r.lookup_key === null && h(e, t, n, r).length === 0)[0];
236
+ return c === void 0 ? s === null ? {
237
+ finding: {
238
+ kind: "manual",
239
+ object: o,
240
+ detail: `create a ${e.currency} / ${e.interval} ${e.usageType}${e.tiers === void 0 ? "" : ` ${e.tiers.mode} tiered`} price on this product in the Stripe Dashboard with lookup key ${e.lookupKey}; amounts are kept in Stripe`
241
+ },
242
+ id: null
243
+ } : {
180
244
  finding: {
181
245
  kind: "create",
182
246
  object: o,
183
- detail: `${e.unitAmount} ${e.currency} / ${e.interval}`,
247
+ detail: "unit_amount" in s ? `${s.unit_amount} ${e.currency} / ${e.interval}` : `${s.tiers_mode} tiers ${e.tiers.tiers.map((e) => `${e.upTo}:${e.unitAmountDecimal ?? e.unitAmount ?? 0}${e.flatAmount === void 0 ? "" : `+${e.flatAmount}`}`).join(" ")} ${e.currency} / ${e.interval}`,
184
248
  apply: {
185
249
  method: "POST",
186
250
  path: "/v1/prices",
187
- params: l(e, t, n, !1)
251
+ params: _(e, t, n, !1, s)
188
252
  }
189
253
  },
190
254
  id: null
@@ -195,16 +259,16 @@ var n = e.API_VERSION, r = [
195
259
  detail: "existing price gets the lookup key",
196
260
  apply: {
197
261
  method: "POST",
198
- path: `/v1/prices/${s.id}`,
262
+ path: `/v1/prices/${c.id}`,
199
263
  params: {
200
264
  lookup_key: e.lookupKey,
201
265
  metadata: { voltro_key: e.lookupKey }
202
266
  }
203
267
  }
204
268
  },
205
- id: s.id
269
+ id: c.id
206
270
  };
207
- }, d = (e, t) => {
271
+ }, y = (e, t) => {
208
272
  let n = `meter ${e.eventName}`, r = t.find((t) => t.event_name === e.eventName);
209
273
  if (r === void 0) return {
210
274
  finding: {
@@ -267,7 +331,60 @@ var n = e.API_VERSION, r = [
267
331
  },
268
332
  id: r.id
269
333
  };
270
- }, f = (e, t) => {
334
+ }, b = (e, t) => {
335
+ let n = `retired price ${e}`, r = t.filter((t) => t.active && t.lookup_key === e);
336
+ return r.length === 0 ? {
337
+ kind: "ok",
338
+ object: n
339
+ } : r.length > 1 ? {
340
+ kind: "manual",
341
+ object: n,
342
+ detail: `${r.length} active prices carry this lookup key`
343
+ } : {
344
+ kind: "update",
345
+ object: n,
346
+ detail: "deactivate",
347
+ apply: {
348
+ method: "POST",
349
+ path: `/v1/prices/${r[0].id}`,
350
+ params: { active: !1 }
351
+ }
352
+ };
353
+ }, x = (e, t) => {
354
+ let n = `retired product ${e}`, r = t.filter((t) => t.active && t.metadata.voltro_key === e);
355
+ return r.length === 0 ? {
356
+ kind: "ok",
357
+ object: n
358
+ } : r.length > 1 ? {
359
+ kind: "manual",
360
+ object: n,
361
+ detail: `${r.length} active products carry this key`
362
+ } : {
363
+ kind: "update",
364
+ object: n,
365
+ detail: "archive",
366
+ apply: {
367
+ method: "POST",
368
+ path: `/v1/products/${r[0].id}`,
369
+ params: { active: !1 }
370
+ }
371
+ };
372
+ }, S = (e, t) => {
373
+ let n = `retired meter ${e}`, r = t.find((t) => t.event_name === e);
374
+ return r === void 0 || r.status !== "active" ? {
375
+ kind: "ok",
376
+ object: n
377
+ } : {
378
+ kind: "update",
379
+ object: n,
380
+ detail: "deactivate",
381
+ apply: {
382
+ method: "POST",
383
+ path: `/v1/billing/meters/${r.id}/deactivate`,
384
+ params: {}
385
+ }
386
+ };
387
+ }, C = (e, t) => {
271
388
  let n = "tax settings", r = t.head_office?.address ?? {}, i = [];
272
389
  for (let [t, n] of Object.entries(e.headOffice)) r[t] !== n && i.push(`head_office.${t}`);
273
390
  return t.defaults.tax_code !== e.defaultTaxCode && i.push("defaults.tax_code"), t.defaults.tax_behavior !== e.defaultTaxBehavior && i.push("defaults.tax_behavior"), i.length === 0 ? t.status === "active" ? {
@@ -293,7 +410,7 @@ var n = e.API_VERSION, r = [
293
410
  }
294
411
  }
295
412
  };
296
- }, p = (e, t, n) => ({
413
+ }, w = (e, t) => ({
297
414
  business_profile: {
298
415
  headline: e.headline,
299
416
  privacy_policy_url: e.privacyPolicyUrl,
@@ -316,18 +433,10 @@ var n = e.API_VERSION, r = [
316
433
  enabled: !0,
317
434
  mode: "at_period_end"
318
435
  },
319
- subscription_update: {
320
- enabled: !0,
321
- default_allowed_updates: ["price", "quantity"],
322
- proration_behavior: "create_prorations",
323
- products: n.map((e) => ({
324
- product: e.productId,
325
- prices: [e.priceId]
326
- }))
327
- }
436
+ subscription_update: { enabled: !1 }
328
437
  },
329
438
  metadata: { voltro_key: e.key }
330
- }), m = (e) => JSON.stringify([...e ?? []].sort()), h = (e, t) => {
439
+ }), T = (e) => JSON.stringify([...e ?? []].sort()), E = (e, t) => {
331
440
  let n = [], r = t.features, i = e.features;
332
441
  t.default_return_url !== e.default_return_url && n.push("default_return_url");
333
442
  let a = e.business_profile;
@@ -338,69 +447,59 @@ var n = e.API_VERSION, r = [
338
447
  "payment_method_update",
339
448
  "subscription_cancel"
340
449
  ]) r[e]?.enabled !== !0 && n.push(`${e}.enabled`);
341
- m(r.customer_update?.allowed_updates) !== m(i.customer_update.allowed_updates) && n.push("customer_update.allowed_updates"), r.subscription_cancel?.mode !== "at_period_end" && n.push("subscription_cancel.mode");
342
- let o = r.subscription_update ?? {}, s = i.subscription_update;
343
- o.enabled !== !0 && n.push("subscription_update.enabled"), o.proration_behavior !== s.proration_behavior && n.push("subscription_update.proration_behavior");
344
- let c = (e) => JSON.stringify((e ?? []).map((e) => `${e.product}:${[...e.prices].sort().join("|")}`).sort());
345
- return c(o.products) !== c(s.products) && n.push("subscription_update.products"), m(o.default_allowed_updates) !== m(s.default_allowed_updates) && n.push("subscription_update.default_allowed_updates"), n;
346
- }, g = (e, t, n, r) => {
347
- let i = "customer portal";
348
- if (n === null) return [{
349
- kind: "manual",
350
- object: i,
351
- detail: "its plan prices are unresolved"
352
- }];
353
- let a = p(e, t, n), o = r.find((t) => t.metadata.voltro_key === e.key) ?? r.find((t) => t.active && t.name === e.name);
354
- if (o === void 0) return [{
450
+ return T(r.customer_update?.allowed_updates) !== T(i.customer_update.allowed_updates) && n.push("customer_update.allowed_updates"), r.subscription_cancel?.mode !== "at_period_end" && n.push("subscription_cancel.mode"), r.subscription_update?.enabled !== !1 && n.push("subscription_update.enabled"), n;
451
+ }, D = (e, t, n) => {
452
+ let r = "customer portal", i = w(e, t), a = n.find((t) => t.metadata.voltro_key === e.key) ?? n.find((t) => t.active && t.name === e.name);
453
+ if (a === void 0) return [{
355
454
  kind: "create",
356
- object: i,
455
+ object: r,
357
456
  detail: "self-service configuration",
358
457
  apply: {
359
458
  method: "POST",
360
459
  path: "/v1/billing_portal/configurations",
361
460
  params: {
362
- ...a,
461
+ ...i,
363
462
  name: e.name
364
463
  }
365
464
  }
366
- }, ...r.some((e) => e.is_default) ? [{
465
+ }, ...n.some((e) => e.is_default) ? [{
367
466
  kind: "manual",
368
- object: i,
467
+ object: r,
369
468
  detail: "another configuration is the default — make this one the default in the Dashboard"
370
469
  }] : []];
371
- let s = [], c = h(a, o), l = o.metadata.voltro_key !== e.key;
372
- return c.length > 0 || l || !o.active ? s.push({
373
- kind: l ? "adopt" : "update",
374
- object: i,
375
- detail: [...c, ...o.active ? [] : ["active"]].join(", ") || "catalog key",
470
+ let o = [], s = E(i, a), c = a.metadata.voltro_key !== e.key;
471
+ return s.length > 0 || c || !a.active ? o.push({
472
+ kind: c ? "adopt" : "update",
473
+ object: r,
474
+ detail: [...s, ...a.active ? [] : ["active"]].join(", ") || "catalog key",
376
475
  apply: {
377
476
  method: "POST",
378
- path: `/v1/billing_portal/configurations/${o.id}`,
477
+ path: `/v1/billing_portal/configurations/${a.id}`,
379
478
  params: {
380
- ...a,
479
+ ...i,
381
480
  active: !0
382
481
  }
383
482
  }
384
- }) : s.push({
483
+ }) : o.push({
385
484
  kind: "ok",
386
- object: i
387
- }), o.is_default || s.push({
485
+ object: r
486
+ }), a.is_default || o.push({
388
487
  kind: "manual",
389
- object: i,
488
+ object: r,
390
489
  detail: "not the account default — portal sessions would use another configuration"
391
- }), s;
392
- }, _ = (e, r) => {
393
- if (e.webhookUrl === null) return {
490
+ }), o;
491
+ }, O = (n, r) => {
492
+ if (n.webhookUrl === null) return {
394
493
  kind: "ok",
395
494
  object: "webhook endpoint (none: stripe listen forwards locally)"
396
495
  };
397
- let i = `webhook endpoint ${e.webhookUrl}`, a = r.filter((t) => t.url === e.webhookUrl);
496
+ let i = `webhook endpoint ${n.webhookUrl}`, a = r.filter((e) => e.url === n.webhookUrl);
398
497
  if (a.length > 1) return {
399
498
  kind: "manual",
400
499
  object: i,
401
500
  detail: `${a.length} endpoints for this url — delete all but one`
402
501
  };
403
- let o = a[0], s = [...t].sort();
502
+ let o = a[0], s = [...e].sort();
404
503
  return o === void 0 ? {
405
504
  kind: "create",
406
505
  object: i,
@@ -409,13 +508,13 @@ var n = e.API_VERSION, r = [
409
508
  method: "POST",
410
509
  path: "/v1/webhook_endpoints",
411
510
  params: {
412
- url: e.webhookUrl,
511
+ url: n.webhookUrl,
413
512
  enabled_events: s,
414
- api_version: n,
513
+ api_version: t,
415
514
  description: "Voltro billing"
416
515
  }
417
516
  }
418
- } : o.api_version !== null && o.api_version !== n ? {
517
+ } : o.api_version !== null && o.api_version !== t ? {
419
518
  kind: "drift",
420
519
  object: i,
421
520
  detail: `api version ${o.api_version} — payloads would not match the SDK; recreate it (and rotate STRIPE_WEBHOOK_SECRET)`
@@ -435,7 +534,7 @@ var n = e.API_VERSION, r = [
435
534
  kind: "ok",
436
535
  object: i
437
536
  };
438
- }, v = (e) => {
537
+ }, k = (e) => {
439
538
  let t = [];
440
539
  for (let n of e.catalog.tax.registrationCountries) e.activeRegistrations.includes(n) || t.push({
441
540
  kind: "manual",
@@ -467,4 +566,4 @@ var n = e.API_VERSION, r = [
467
566
  });
468
567
  return t;
469
568
  };
470
- export { n as STRIPE_API_VERSION, r as STRIPE_DASHBOARD_REMINDERS, d as diffMeter, g as diffPortal, u as diffPrice, s as diffProduct, f as diffTaxSettings, _ as diffWebhook, p as portalParams, v as sellingReadiness };
569
+ export { t as STRIPE_API_VERSION, r as STRIPE_DASHBOARD_REMINDERS, y as diffMeter, D as diffPortal, v as diffPrice, s as diffProduct, S as diffRetiredMeter, b as diffRetiredPrice, x as diffRetiredProduct, C as diffTaxSettings, O as diffWebhook, w as portalParams, n as retiredConflicts, k as sellingReadiness };
@@ -1,9 +1,9 @@
1
1
  import { BillingError as e } from "./types.js";
2
2
  import { exactProviderIdentifier as t } from "./providerIdentity.js";
3
3
  import { Effect as n } from "effect";
4
- import { canonicalJson as r } from "@voltro/protocol";
5
- import { and as i, eq as a, gt as o } from "@voltro/database";
6
- import { createHash as s } from "node:crypto";
4
+ import { and as r, eq as i, gt as a } from "@voltro/database";
5
+ import { createHash as o } from "node:crypto";
6
+ import { canonicalJson as s } from "@voltro/protocol";
7
7
  // src/custodyInventory.ts
8
8
  var c = Object.freeze([
9
9
  "_voltro_billing_customer_accounts",
@@ -22,40 +22,74 @@ var c = Object.freeze([
22
22
  "_voltro_billing_usage_events",
23
23
  "_voltro_billing_checkout_operations",
24
24
  "_voltro_billing_close_operations",
25
- "_voltro_billing_dunning_notices"
26
- ]), l = (r, i) => n.tryPromise({
25
+ "_voltro_billing_dunning_notices",
26
+ "_voltro_billing_subscription_write_heads",
27
+ "_voltro_billing_subscription_writes",
28
+ "_voltro_billing_invoice_payment_heads"
29
+ ]), l = Object.freeze(["_voltro_billing_invoice_history_scan_accounts"]), u = (r, i) => n.tryPromise({
27
30
  try: async () => {
28
31
  let e = i.tenantId, n = i.pageSize ?? 200, a = i.maxRowsPerTable ?? 5e3;
29
- if (!t(e) || e.length > 191 || !e.isWellFormed() || !Number.isSafeInteger(n) || n < 1 || n > 500 || !Number.isSafeInteger(a) || a < 1 || a > 5e4) throw v("Inventory tenant and bounds must be valid.", !1);
30
- if (r.integrityQuery === void 0) throw v("Complete native integrity reads are required.", !1);
32
+ if (!t(e) || e.length > 191 || !e.isWellFormed() || !Number.isSafeInteger(n) || n < 1 || n > 500 || !Number.isSafeInteger(a) || a < 1 || a > 5e4) throw x("Inventory tenant and bounds must be valid.", !1);
33
+ if (r.integrityQuery === void 0) throw x("Complete native integrity reads are required.", !1);
31
34
  let o = {
32
35
  format: "voltro.billing-custody-inventory.v1",
33
36
  tenantId: e,
34
37
  tables: await r.transactional(async (t) => {
35
- if (t.integrityQuery === void 0) throw v("Transactional native integrity reads are required.", !1);
36
- let r = await u(t, e, n, a), i = await u(t, e, n, a);
37
- if (g(r) !== g(i)) throw v("Billing state changed during inventory. Quiesce writers and retry.", !0);
38
+ if (t.integrityQuery === void 0) throw x("Transactional native integrity reads are required.", !1);
39
+ let r = await p(t, c, f(e), n, a), i = await p(t, c, f(e), n, a);
40
+ if (y(r) !== y(i)) throw x("Billing state changed during inventory. Quiesce writers and retry.", !0);
38
41
  return i;
39
42
  })
40
43
  };
41
44
  return Object.freeze({
42
45
  ...o,
43
- digest: g(o),
46
+ digest: y(o),
44
47
  observedAt: /* @__PURE__ */ new Date(),
45
48
  purpose: "review-only"
46
49
  });
47
50
  },
48
- catch: (t) => t instanceof e ? t : v("The native billing inventory could not be completed.", !0)
49
- }), u = async (e, n, s, l) => {
50
- let u = e.integrityQuery;
51
- if (u === void 0) throw v("Complete native integrity reads are required.", !1);
52
- let y = [], b = 0;
53
- for (let x of c) {
54
- let c = [], S = /* @__PURE__ */ new Set(), C;
51
+ catch: (t) => t instanceof e ? t : x("The native billing inventory could not be completed.", !0)
52
+ }), d = (a, o) => n.tryPromise({
53
+ try: async () => {
54
+ let e = o.provider, n = o.providerAccountId, s = o.livemode, c = o.pageSize ?? 200, u = o.maxRowsPerTable ?? 5e3;
55
+ if (!t(e) || e.length > 64 || !e.isWellFormed() || !t(n) || n.length > 191 || !n.isWellFormed() || typeof s != "boolean" || !Number.isSafeInteger(c) || c < 1 || c > 500 || !Number.isSafeInteger(u) || u < 1 || u > 5e4) throw x("Inventory account and bounds must be valid.", !1);
56
+ if (a.integrityQuery === void 0) throw x("Complete native integrity reads are required.", !1);
57
+ let d = {
58
+ predicate: r(i("provider", e), i("providerAccountId", n), i("livemode", +!!s)),
59
+ owns: (t) => t.provider === e && t.providerAccountId === n && t.livemode === +!!s
60
+ }, f = {
61
+ format: "voltro.billing-account-custody-inventory.v1",
62
+ provider: e,
63
+ providerAccountId: n,
64
+ livemode: s,
65
+ tables: await a.transactional(async (e) => {
66
+ if (e.integrityQuery === void 0) throw x("Transactional native integrity reads are required.", !1);
67
+ let t = await p(e, l, d, c, u), n = await p(e, l, d, c, u);
68
+ if (y(t) !== y(n)) throw x("Billing state changed during inventory. Quiesce writers and retry.", !0);
69
+ return n;
70
+ })
71
+ };
72
+ return Object.freeze({
73
+ ...f,
74
+ digest: y(f),
75
+ observedAt: /* @__PURE__ */ new Date(),
76
+ purpose: "review-only"
77
+ });
78
+ },
79
+ catch: (t) => t instanceof e ? t : x("The native billing account inventory could not be completed.", !0)
80
+ }), f = (e) => ({
81
+ predicate: i("tenantId", e),
82
+ owns: (t) => t.tenantId === e
83
+ }), p = async (e, n, i, o, c) => {
84
+ let l = e.integrityQuery;
85
+ if (l === void 0) throw x("Complete native integrity reads are required.", !1);
86
+ let u = [], d = 0;
87
+ for (let f of n) {
88
+ let n = [], p = /* @__PURE__ */ new Set(), S;
55
89
  for (;;) {
56
- let g = Math.min(s, l - c.length + 1), y = {
57
- table: x,
58
- predicate: C === void 0 ? a("tenantId", n) : i(a("tenantId", n), o("id", C)),
90
+ let u = Math.min(o, c - n.length + 1), y = {
91
+ table: f,
92
+ predicate: S === void 0 ? i.predicate : r(i.predicate, a("id", S)),
59
93
  crossTenant: !0,
60
94
  includeDeleted: !0,
61
95
  includeExpired: !0,
@@ -63,92 +97,94 @@ var c = Object.freeze([
63
97
  column: "id",
64
98
  direction: "asc"
65
99
  }],
66
- take: g,
100
+ take: u,
67
101
  skip: void 0,
68
102
  projection: void 0
69
- }, w = await u.call(e, y);
70
- if (!Array.isArray(w) || w.length > g) throw v(`Invalid inventory page for ${x}.`, !1);
71
- for (let e of w) {
72
- let i = h(e);
73
- if (!m(i)) throw v(`Invalid inventory row for ${x}.`, !1);
74
- let a = i.id;
75
- if (!t(a) || i.tenantId !== n || S.has(a)) throw v(`Invalid inventory identity for ${x}.`, !1);
76
- if (c.length === l) throw v(`Inventory bound exceeded for ${x}; no partial inventory is returned.`, !1);
77
- S.add(a);
103
+ }, C = await l.call(e, y);
104
+ if (!Array.isArray(C) || C.length > u) throw x(`Invalid inventory page for ${f}.`, !1);
105
+ for (let e of C) {
106
+ let r = v(e);
107
+ if (!_(r)) throw x(`Invalid inventory row for ${f}.`, !1);
108
+ let a = r.id;
109
+ if (!t(a) || !i.owns(r) || p.has(a)) throw x(`Invalid inventory identity for ${f}.`, !1);
110
+ if (n.length === c) throw x(`Inventory bound exceeded for ${f}; no partial inventory is returned.`, !1);
111
+ p.add(a);
78
112
  let o = {};
79
- for (let e of d) {
80
- let n = i[e];
113
+ for (let e of m) {
114
+ let n = r[e];
81
115
  if (n != null) {
82
- if (!t(n)) throw v(`Invalid inventory reference for ${x}.`, !1);
116
+ if (!t(n)) throw x(`Invalid inventory reference for ${f}.`, !1);
83
117
  o[e] = n;
84
118
  }
85
119
  }
86
- let s = r(i), u = Buffer.byteLength(s, "utf8");
87
- if (b += u, u > f || b > p) throw v("Native billing inventory byte bound exceeded; no partial inventory is returned.", !1);
88
- c.push(Object.freeze({
120
+ let l = s(r), u = Buffer.byteLength(l, "utf8");
121
+ if (d += u, u > h || d > g) throw x("Native billing inventory byte bound exceeded; no partial inventory is returned.", !1);
122
+ n.push(Object.freeze({
89
123
  id: a,
90
- digest: _(s),
124
+ digest: b(l),
91
125
  references: Object.freeze(o)
92
- })), C = a;
126
+ })), S = a;
93
127
  }
94
- if (w.length < g) break;
128
+ if (C.length < u) break;
95
129
  }
96
- c.sort((e, t) => e.id < t.id ? -1 : +(e.id > t.id)), y.push(Object.freeze({
97
- tableName: x,
98
- rowCount: c.length,
99
- digest: g(c),
100
- rows: Object.freeze(c)
130
+ n.sort((e, t) => e.id < t.id ? -1 : +(e.id > t.id)), u.push(Object.freeze({
131
+ tableName: f,
132
+ rowCount: n.length,
133
+ digest: y(n),
134
+ rows: Object.freeze(n)
101
135
  }));
102
136
  }
103
- return Object.freeze(y);
104
- }, d = [
137
+ return Object.freeze(u);
138
+ }, m = [
105
139
  "provider",
106
140
  "providerAccountId",
107
141
  "providerCustomerId",
108
142
  "providerSubscriptionId",
109
- "providerInvoiceId"
110
- ], f = 4194304, p = 67108864, m = (e) => typeof e == "object" && !!e && !Array.isArray(e), h = (e, t = /* @__PURE__ */ new Set(), n = 0) => {
111
- if (n > 64) throw v("Native inventory value exceeds supported depth.", !1);
143
+ "providerInvoiceId",
144
+ "afterCustodyId",
145
+ "cycleEndCustodyId"
146
+ ], h = 4194304, g = 67108864, _ = (e) => typeof e == "object" && !!e && !Array.isArray(e), v = (e, t = /* @__PURE__ */ new Set(), n = 0) => {
147
+ if (n > 64) throw x("Native inventory value exceeds supported depth.", !1);
112
148
  if (e === null || typeof e == "boolean") return e;
113
149
  if (typeof e == "string") {
114
- if (!e.isWellFormed()) throw v("Native inventory contains malformed text.", !1);
150
+ if (!e.isWellFormed()) throw x("Native inventory contains malformed text.", !1);
115
151
  return e;
116
152
  }
117
153
  if (typeof e == "number") {
118
- if (!Number.isFinite(e) || !Number.isSafeInteger(e) && Math.abs(e) > 2 ** 53 - 1 || Object.is(e, -0)) throw v("Native inventory numeric evidence cannot be encoded exactly.", !1);
154
+ if (!Number.isFinite(e) || !Number.isSafeInteger(e) && Math.abs(e) > 2 ** 53 - 1 || Object.is(e, -0)) throw x("Native inventory numeric evidence cannot be encoded exactly.", !1);
119
155
  return e;
120
156
  }
121
157
  if (e instanceof Date) {
122
- if (!Number.isFinite(e.getTime())) throw v("Native inventory contains an invalid date.", !1);
158
+ if (!Number.isFinite(e.getTime())) throw x("Native inventory contains an invalid date.", !1);
123
159
  return e.toISOString();
124
160
  }
125
- if (typeof e != "object" || t.has(e)) throw v("Native inventory contains a non-JSON value.", !1);
161
+ if (typeof e != "object" || t.has(e)) throw x("Native inventory contains a non-JSON value.", !1);
126
162
  let r = Object.getPrototypeOf(e);
127
- if (!Array.isArray(e) && r !== Object.prototype && r !== null) throw v("Native inventory value has an unsupported prototype.", !1);
128
- if (Object.getOwnPropertySymbols(e).length !== 0) throw v("Native inventory contains unsupported symbol fields.", !1);
163
+ if (!Array.isArray(e) && r !== Object.prototype && r !== null) throw x("Native inventory value has an unsupported prototype.", !1);
164
+ if (Object.getOwnPropertySymbols(e).length !== 0) throw x("Native inventory contains unsupported symbol fields.", !1);
129
165
  t.add(e);
130
166
  try {
131
167
  if (Array.isArray(e)) {
132
- if (Object.keys(e).length !== e.length || Object.getOwnPropertyNames(e).length !== e.length + 1) throw v("Native inventory contains a sparse or extended array.", !1);
168
+ if (Object.keys(e).length !== e.length || Object.getOwnPropertyNames(e).length !== e.length + 1) throw x("Native inventory contains a sparse or extended array.", !1);
133
169
  return Array.from({ length: e.length }, (r, i) => {
134
170
  let a = Object.getOwnPropertyDescriptor(e, String(i));
135
- if (a === void 0 || !("value" in a)) throw v("Native inventory contains a sparse or accessor array.", !1);
136
- return h(a.value, t, n + 1);
171
+ if (a === void 0 || !("value" in a)) throw x("Native inventory contains a sparse or accessor array.", !1);
172
+ return v(a.value, t, n + 1);
137
173
  });
138
174
  }
139
- if (Object.getOwnPropertyNames(e).length !== Object.keys(e).length) throw v("Native inventory contains non-enumerable fields.", !1);
175
+ if (Object.getOwnPropertyNames(e).length !== Object.keys(e).length) throw x("Native inventory contains non-enumerable fields.", !1);
140
176
  return Object.fromEntries(Object.keys(e).map((r) => {
141
- if (!r.isWellFormed()) throw v("Native inventory contains a malformed field.", !1);
177
+ if (!r.isWellFormed()) throw x("Native inventory contains a malformed field.", !1);
142
178
  let i = Object.getOwnPropertyDescriptor(e, r);
143
- if (i === void 0 || !("value" in i)) throw v("Native inventory contains an accessor field.", !1);
144
- return [r, h(i.value, t, n + 1)];
179
+ if (i === void 0 || !("value" in i)) throw x("Native inventory contains an accessor field.", !1);
180
+ return [r, v(i.value, t, n + 1)];
145
181
  }));
146
182
  } finally {
147
183
  t.delete(e);
148
184
  }
149
- }, g = (e) => _(r(e)), _ = (e) => s("sha256").update(e, "utf8").digest("hex"), v = (t, n) => new e({
185
+ }, y = (e) => b(s(e)), b = (e) => o("sha256").update(e, "utf8").digest("hex"), x = (t, n) => new e({
150
186
  source: "billingCustodyInventory",
151
187
  message: t,
152
188
  transient: n
153
189
  });
154
- export { c as BILLING_CUSTODY_INVENTORY_TABLES, l as inspectBillingCustody };
190
+ export { l as BILLING_ACCOUNT_CUSTODY_INVENTORY_TABLES, c as BILLING_CUSTODY_INVENTORY_TABLES, d as inspectBillingAccountCustody, u as inspectBillingCustody };
package/dist/dunning.js CHANGED
@@ -143,12 +143,20 @@ var l = "_voltro_billing_dunning_notices", u = o(l, {
143
143
  html: `<p>${a} Your subscription stays active until ${i}.</p>${n}`,
144
144
  text: `${a} Your subscription stays active until ${i}.\n\n${r}`
145
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 = () => {
146
+ }, w = (e, t = {}) => (r) => {
147
+ let i = r.to;
148
+ return i === null ? n.void : (t.compose === void 0 ? n.succeed({
149
+ subject: r.subject,
150
+ html: r.html,
151
+ text: r.text
152
+ }) : t.compose(r)).pipe(n.flatMap((n) => e.send({
153
+ to: i,
154
+ subject: n.subject,
155
+ html: n.html,
156
+ text: n.text,
157
+ ...t.tags === void 0 ? {} : { tags: t.tags }
158
+ })), n.asVoid);
159
+ }, T = (e, t, n) => `${e}\u0000${t}\u0000${n}`, E = () => {
152
160
  let e = /* @__PURE__ */ new Map();
153
161
  return {
154
162
  claim: (t, r, i, a) => n.sync(() => {