@tinkerlandai/longplay-sdk 0.10.64 → 0.10.66

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 (92) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +14 -1
  3. package/README.zh-CN.md +1 -1
  4. package/dist/check-response-WOTPYNDN.js +1 -0
  5. package/dist/{chunk-EB7MIZ4T.js → chunk-3Q3DZEP3.js} +1 -1
  6. package/dist/{chunk-R4CYPCBI.js → chunk-45MWDZ42.js} +1 -1
  7. package/dist/{chunk-TK3WOD2O.js → chunk-46USIMCJ.js} +1 -1
  8. package/dist/{chunk-ZCJEXNJD.js → chunk-47FCHF3Y.js} +1 -1
  9. package/dist/{chunk-ZRGL2CAP.js → chunk-56YCOGQZ.js} +1 -1
  10. package/dist/{chunk-S5RM3VO6.js → chunk-5WFI36LF.js} +1 -1
  11. package/dist/{chunk-77O2O552.js → chunk-74T76RE4.js} +1 -1
  12. package/dist/{chunk-5ZD3BY5R.js → chunk-7D5462NE.js} +1 -1
  13. package/dist/{chunk-HUYKZH3H.js → chunk-7EENIOSJ.js} +1 -1
  14. package/dist/chunk-7NKBMAOB.js +1 -0
  15. package/dist/{chunk-FQMZY5VP.js → chunk-7OJIW75D.js} +1 -1
  16. package/dist/{chunk-QXDLOPZK.js → chunk-A22QPPNY.js} +1 -1
  17. package/dist/{chunk-EKUDMQXT.js → chunk-AD35L6BX.js} +1 -1
  18. package/dist/{chunk-KOJI7IH6.js → chunk-C5FSL4XH.js} +2 -2
  19. package/dist/{chunk-PGLBFTRK.js → chunk-DCMA7W7N.js} +1 -1
  20. package/dist/{chunk-C3HZCZVJ.js → chunk-E3FUZSTM.js} +1 -1
  21. package/dist/{chunk-FDWFBCXV.js → chunk-EYTP23EK.js} +1 -1
  22. package/dist/{chunk-32AEJKJW.js → chunk-FUP5JVDE.js} +1 -1
  23. package/dist/{chunk-EE6QNOCL.js → chunk-G2OLUFYT.js} +1 -1
  24. package/dist/{chunk-PJHTN5NJ.js → chunk-GE6RSO2C.js} +1 -1
  25. package/dist/{chunk-7N765ZES.js → chunk-HT5SLWWG.js} +1 -1
  26. package/dist/{chunk-7STWC4L4.js → chunk-IGE2UMXG.js} +1 -1
  27. package/dist/{chunk-5LNX7MHO.js → chunk-JBN6ADWQ.js} +1 -1
  28. package/dist/{chunk-IM5OXTEH.js → chunk-K675GO7R.js} +1 -1
  29. package/dist/{chunk-NDNHTG5B.js → chunk-KVLOMX2G.js} +1 -1
  30. package/dist/{chunk-LFEFSEK3.js → chunk-M6MXJHJ5.js} +1 -1
  31. package/dist/{chunk-DBYRJ4QV.js → chunk-MNICOIQ6.js} +1 -1
  32. package/dist/chunk-MUCDKWMP.js +1 -0
  33. package/dist/{chunk-R7CH2XLH.js → chunk-MUP7FNNY.js} +1 -1
  34. package/dist/{chunk-JBSJ3JU2.js → chunk-N5HX3K5J.js} +1 -1
  35. package/dist/{chunk-KTWKDR5L.js → chunk-O5YYORDW.js} +1 -1
  36. package/dist/{chunk-ZYSMQMC5.js → chunk-OFG3SGEX.js} +1 -1
  37. package/dist/{chunk-XCFAKO23.js → chunk-OKPWZZZW.js} +1 -1
  38. package/dist/{chunk-NA6IYWSB.js → chunk-OT55LG4U.js} +1 -1
  39. package/dist/{chunk-JEDRJAJ5.js → chunk-PNX7Y2K3.js} +1 -1
  40. package/dist/{chunk-2KM537QH.js → chunk-PQ4ISW55.js} +1 -1
  41. package/dist/{chunk-VXDVMAS6.js → chunk-Q523TPZM.js} +1 -1
  42. package/dist/{chunk-NAFHQVSX.js → chunk-QPVA644N.js} +1 -1
  43. package/dist/{chunk-YVTXJWTS.js → chunk-RHILCVPZ.js} +1 -1
  44. package/dist/{chunk-2RFI2DEV.js → chunk-RNCUAYLQ.js} +1 -1
  45. package/dist/{chunk-4SI4SQ3C.js → chunk-SAPICYY3.js} +1 -1
  46. package/dist/{chunk-BJW4AXFL.js → chunk-TXVLJFZG.js} +1 -1
  47. package/dist/{chunk-RIEWU4MN.js → chunk-XIBJF5E6.js} +1 -1
  48. package/dist/{chunk-7HJQJG6Z.js → chunk-YA5YKHDE.js} +1 -1
  49. package/dist/{chunk-VNYUL3PV.js → chunk-YUL23NAW.js} +1 -1
  50. package/dist/chunk-ZLSZBGJG.js +1 -0
  51. package/dist/{chunk-4OODZM64.js → chunk-ZWNWVMCH.js} +1 -1
  52. package/dist/{content-N4FPQMWG.js → content-WWME7E27.js} +1 -1
  53. package/dist/funnel-host-purchase-XIGJ7P7M.js +1 -0
  54. package/dist/{funnel-host-recovery-paywall-OJROCEFE.js → funnel-host-recovery-paywall-POMEY6I2.js} +1 -1
  55. package/dist/{funnel-paywall-copies-U3JIYQJ5.js → funnel-paywall-copies-DUZ3YX67.js} +1 -1
  56. package/dist/funnel-paywall-prerender-5NU457SR.js +1 -0
  57. package/dist/funnel-route-prediction-EW3HVH46.js +1 -0
  58. package/dist/funnel-route-source-YVFAFCVG.js +1 -0
  59. package/dist/funnel-runtime-host-J2HWW5IN.js +1 -0
  60. package/dist/index.d.ts +12 -6
  61. package/dist/index.js +1 -1
  62. package/dist/merchant-bridge-contracts-PNRVNTCN.js +1 -0
  63. package/dist/native-shell.js +1 -1
  64. package/dist/openrouter.js +1 -1
  65. package/dist/operation-contracts-6ORJSGYH.js +1 -0
  66. package/dist/page.js +1 -1
  67. package/dist/paywall-YRB7LQUS.js +1 -0
  68. package/dist/paywall-content-QLJIOFR3.js +1 -0
  69. package/dist/paywall-session-Q6ZYXUOU.js +1 -0
  70. package/dist/popup.js +1 -1
  71. package/dist/react-native.js +1 -1
  72. package/dist/screen-renderer-P6U5UBFX.js +1 -0
  73. package/dist/server.js +1 -1
  74. package/dist/visual.js +1 -1
  75. package/package.json +1 -1
  76. package/dist/check-response-K56UEZ6E.js +0 -1
  77. package/dist/chunk-6AHZAXQE.js +0 -1
  78. package/dist/chunk-D4CK3DCQ.js +0 -1
  79. package/dist/chunk-GKNN4T3B.js +0 -1
  80. package/dist/funnel-host-purchase-YWSXBNT6.js +0 -1
  81. package/dist/funnel-paywall-prerender-EMEIQRIH.js +0 -1
  82. package/dist/funnel-route-prediction-XYWNKGQZ.js +0 -1
  83. package/dist/funnel-route-source-4ZVBFNYV.js +0 -1
  84. package/dist/funnel-runtime-host-JUGVP64Q.js +0 -1
  85. package/dist/merchant-bridge-contracts-IZ7ARRRO.js +0 -1
  86. package/dist/operation-contracts-6RQ33K66.js +0 -1
  87. package/dist/paywall-KJ44JWLV.js +0 -1
  88. package/dist/paywall-content-Y5L3WMDS.js +0 -1
  89. package/dist/paywall-session-I6XT22TL.js +0 -1
  90. package/dist/screen-renderer-3YO6EUWD.js +0 -1
  91. /package/dist/{chunk-KOJI7IH6.js.LEGAL.txt → chunk-C5FSL4XH.js.LEGAL.txt} +0 -0
  92. /package/dist/{chunk-PZTWDJHN.js → chunk-YLH3AYCK.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.66
4
+
5
+ - A Paywall can prepare the Customer's membership read while it is visible, through the new `prepareSubscriptionChange(signal)` option, so a purchase click no longer waits for that read before quoting. The read is used for the Paywall state it was made in and is discarded when the Paywall's plans change or the page is hidden; a click during a running read waits for it. `resolveSubscriptionChange` receives the prepared read as its optional second argument
6
+
7
+ ## 0.10.65
8
+
9
+ - A purchase started from a Paywall button says its progress in that button: it spins and reads "Preparing your price…", "Processing…" or "Confirming payment…" in place, for hosted Checkout as well as in-page Checkout, and the footer no longer opens a status bar above the content. The status region keeps the text for assistive technology. Returning to an unpaid original purchase and a purchase handed to `onPurchaseIntent` also name their button
10
+
3
11
  ## 0.10.64
4
12
 
5
13
  - A pre-render's kept copy follows the Run: when a click's Run presents another Paywall or Version than the copy (for example a Version its Funnel pins, or another Paywall its server-side route chooses for a subscriber), that one becomes the entry's kept copy, so the next opening shows what the Run takes over instead of replacing it. It is kept even when the click came before the copy was ready, and the copy's own later reads and refusals no longer replace it. Fresh reads of a kept copy refresh the Version shown, not the Paywall's current one
package/README.md CHANGED
@@ -274,6 +274,16 @@ Set `parameters.commerce.intent: "subscription_change"` (or a standalone Paywall
274
274
  membership. Without this optional intent, availability retains new-purchase semantics. An
275
275
  explicit change intent without a selected membership is refused rather than attached.
276
276
 
277
+ For a visible Paywall, `prepareSubscriptionChange(signal)` can read the Customer's current
278
+ subscription and membership data ahead of the purchase button. Return a function that derives
279
+ the change from the eventual selection using those reads. The SDK uses a read for the Paywall
280
+ state it was made in: a change of the Paywall's plans or the page being hidden discards it, and
281
+ a new one starts when the Paywall is visible again. A click while the read is still running
282
+ waits for it instead of reading again. The SDK supplies the optional read as the second argument
283
+ to `resolveSubscriptionChange`; that callback can fall back to current reads when the prepared
284
+ read is unavailable. The returned function must check that its Customer is
285
+ still current. Quote creation, offer claims and Checkout wait for the purchase action.
286
+
277
287
  The selected target remains pinned to the Paywall's allowed Products. Plan changes retain
278
288
  prepaid `featureQuantities` in the command, quote, operation and recovery selection (at most
279
289
  100 Feature UUIDs, integer quantities from 0 to 10000). Unsupported provider/timing combinations
@@ -289,7 +299,10 @@ published Paywall or provider checkout. Set `purchaseConfirmation: "paywall"` ex
289
299
  an SDK quote review is wanted; it displays the merchant's frozen credit, charge, amount due,
290
300
  renewal terms and required consents. The option is shared by standalone, Funnel and prerendered
291
301
  Paywalls. Opening or refreshing a restored quote never confirms it: only a click on its original
292
- plan continues that same operation.
302
+ plan continues that same operation. While a purchase started from a button is in flight, that
303
+ button spins and says its progress ("Preparing your price…", "Processing…", "Confirming
304
+ payment…") in place, with hosted or in-page Checkout; the Paywall opens no status bar above its
305
+ content, and its status region keeps the text for assistive technology.
293
306
  The accepted change stays in the same Funnel Run, receipt and operation through cancellation,
294
307
  lost responses and reopening. Public `PaywallQuote` and `PaywallOperation` are attach/update
295
308
  unions; use `isPaywallUpdateQuote` / `isPaywallUpdateOperation` to distinguish them.
package/README.zh-CN.md CHANGED
@@ -214,7 +214,7 @@ SDK 在首次派发前保存原 Start 请求 ID 和完整输入;同一未决
214
214
 
215
215
  已订阅用户的 Web 套餐变更通过 `showPaywall`、`showFunnelRun` 或 `showFunnelPurchase` 的 `resolveSubscriptionChange` 选择原 membership。回调收到同样的 action、Product Version 和 `featureQuantities`,返回 `{ membershipId, timing: "immediate" | "renewal" }`。membership 必须来自当前已认证 Customer 的真实订阅;只有明确新订阅的场景才返回 `undefined`,订阅缺失或有歧义时应拒绝。完整示例见[英文说明](README.md#managed-funnel-purchase-recovery)。
216
216
 
217
- 可在 parameters.commerce.intent(独立 Paywall 则为 commerce.intent)传入 subscription_change,使 Offering 按 Customer 唯一已持有 membership 判断升级可用性;省略时保留新购语义。显式变更意图缺少 membership 会被拒绝,不回退新购。该路径保留选中 Coupon,使用 `previewUpdate/update/readSubscriptionUpdate`,不创建新的 attachment;预付 featureQuantities 在命令、报价、operation 和恢复选项中保持不变(最多 100 个 Feature UUID,每项整数 0–10000);服务端仍拒绝不支持的执行方式/时机,Web 变更不能混用原生商店 offer。升级首屏数量使用服务端核实的原订阅档位初始化;之后保留用户调整和原报价,原订数量缺失则不可用,不根据显示价格猜测。默认以已发布 Paywall 的购买按钮作为确认,新购、升级和试用都不再追加 SDK 二次确认区;购买和续费条款应显示在 Paywall 或支付方收银台。确需 SDK 报价审阅时显式设置 `purchaseConfirmation: "paywall"`,展示商户固定的抵扣、实付、续费和 consent;此选项适用于独立、Funnel 和预渲染 Paywall。重开或刷新原报价不会自动确认,只有用户点击原套餐才继续同一个 operation。取消、丢响应和重开保留同一 Run、receipt 和 operation。公开 `PaywallQuote/PaywallOperation` 为 attach/update 联合类型,可用 `isPaywallUpdateQuote/isPaywallUpdateOperation` 区分;update 保留真实 `effective/scheduled` 状态,并等待商户权益处理和交易记录确认。未完成的变更付款跳转只恢复原来经核对的 URL。
217
+ 可在 parameters.commerce.intent(独立 Paywall 则为 commerce.intent)传入 subscription_change,使 Offering 按 Customer 唯一已持有 membership 判断升级可用性;省略时保留新购语义。显式变更意图缺少 membership 会被拒绝,不回退新购。该路径保留选中 Coupon,使用 `previewUpdate/update/readSubscriptionUpdate`,不创建新的 attachment;预付 featureQuantities 在命令、报价、operation 和恢复选项中保持不变(最多 100 个 Feature UUID,每项整数 0–10000);服务端仍拒绝不支持的执行方式/时机,Web 变更不能混用原生商店 offer。升级首屏数量使用服务端核实的原订阅档位初始化;之后保留用户调整和原报价,原订数量缺失则不可用,不根据显示价格猜测。默认以已发布 Paywall 的购买按钮作为确认,新购、升级和试用都不再追加 SDK 二次确认区;购买和续费条款应显示在 Paywall 或支付方收银台。确需 SDK 报价审阅时显式设置 `purchaseConfirmation: "paywall"`,展示商户固定的抵扣、实付、续费和 consent;此选项适用于独立、Funnel 和预渲染 Paywall。重开或刷新原报价不会自动确认,只有用户点击原套餐才继续同一个 operation。Paywall 可见时,`prepareSubscriptionChange(signal)` 可以提前读取 Customer 当前的订阅和会员信息,返回一个按最终选择推出变更的函数;SDK 只在读取时的 Paywall 状态下使用它:Paywall 的套餐变化或页面切到后台都会作废,回到前台时重新读取;点击时读取尚未完成就等待它,不再重新读取。SDK 把这份读取作为 `resolveSubscriptionChange` 的第二个参数传入,读取不可用时回调可以改用当场读取。返回的函数必须确认 Customer 仍是当前用户。报价、领券和 Checkout 仍等购买动作触发。从按钮发起的购买进行中,该按钮原位转圈并显示进度(「正在准备报价…」「正在处理…」「正在确认付款…」),托管和站内 Checkout 都一样;Paywall 不再在内容上方弹出状态栏,状态区只为读屏保留这段文字。取消、丢响应和重开保留同一 Run、receipt 和 operation。公开 `PaywallQuote/PaywallOperation` 为 attach/update 联合类型,可用 `isPaywallUpdateQuote/isPaywallUpdateOperation` 区分;update 保留真实 `effective/scheduled` 状态,并等待商户权益处理和交易记录确认。未完成的变更付款跳转只恢复原来经核对的 URL。
218
218
 
219
219
  替换未付款 Checkout 时,可在 `terminateCheckout` 外提供 `beforeCheckoutReplacement(intent)`。SDK 会先等待新 action、Product Version、selection 和 featureQuantities 的校验,通过后才关闭原 Checkout;拒绝校验时保留原付款链接,重试会重新校验。该回调适用于独立 Paywall、Funnel 宿主和接管后的预渲染 Paywall。SDK 仍会先读回原单已关闭且未付款,再创建替换报价。
220
220
 
@@ -0,0 +1 @@
1
+ import{a,b}from"./chunk-E3FUZSTM.js";import"./chunk-O5YYORDW.js";import"./chunk-OKPWZZZW.js";import"./chunk-46USIMCJ.js";import"./chunk-XIBJF5E6.js";import"./chunk-YLH3AYCK.js";import"./chunk-CILM5XMH.js";import"./chunk-WOT6VMZA.js";export{a as validateEntitlementCheck,b as validateResourceCheck};
@@ -1 +1 @@
1
- import{O as x,a as w,b as f,c as T,d as E,e as j,h as b,i as y,m as G,n as Q,o as $,p as D,q as k,s as g,t as S}from"./chunk-S5RM3VO6.js";import{a as ee}from"./chunk-VILB5M4X.js";import{a as H,b as _,c as Z,d as W,q as J}from"./chunk-ZRGL2CAP.js";import{a as u,b as K,c as V,d as Y}from"./chunk-KTWKDR5L.js";import{e as X,f as R,g as z}from"./chunk-FQMZY5VP.js";import{b as t}from"./chunk-PZTWDJHN.js";var te={"zh-Hans":{merchandise:"减 {discount}(单次使用)",once:"首期减 {discount}",repeating:"前 {months} 个月每月减 {discount}",forever:"每期减 {discount}"},"zh-Hant":{merchandise:"減 {discount}(單次使用)",once:"首期減 {discount}",repeating:"前 {months} 個月每月減 {discount}",forever:"每期減 {discount}"},en:{merchandise:"{discount} off · one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} 割引(1回のみ)",once:"初回のお支払いが {discount} 割引",repeating:"最初の {months} か月間、毎月 {discount} 割引",forever:"毎回のお支払いが {discount} 割引"},ko:{merchandise:"{discount} 할인 · 1회 사용",once:"첫 결제 {discount} 할인",repeating:"첫 {months}개월 동안 매월 {discount} 할인",forever:"매 결제 {discount} 할인"},es:{merchandise:"{discount} de descuento · un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de réduction · une utilisation",once:"{discount} de réduction sur le premier paiement",repeating:"{discount} de réduction par mois pendant les {months} premiers mois",forever:"{discount} de réduction sur chaque paiement",repeatingOne:"{discount} de réduction pendant le premier mois"},de:{merchandise:"{discount} Rabatt · einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat für die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto · um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por mês nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro mês"},it:{merchandise:"{discount} di sconto · un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"Скидка {discount} · одно использование",once:"Скидка {discount} на первый платёж",repeating:"Скидка {discount} каждый месяц в течение первых {months} мес.",repeatingOne:"Скидка {discount} в первый месяц",forever:"Скидка {discount} на каждый платёж"},vi:{merchandise:"Giảm {discount} · dùng một lần",once:"Giảm {discount} cho lần thanh toán đầu tiên",repeating:"Giảm {discount} mỗi tháng trong {months} tháng đầu",forever:"Giảm {discount} cho mỗi lần thanh toán"},th:{merchandise:"ลด {discount} · ใช้ได้ครั้งเดียว",once:"ลด {discount} สำหรับการชำระเงินครั้งแรก",repeating:"ลด {discount} ต่อเดือนในช่วง {months} เดือนแรก",forever:"ลด {discount} สำหรับการชำระเงินทุกครั้ง"},id:{merchandise:"Diskon {discount} · sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"خصم {discount} · استخدام واحد",once:"خصم {discount} على الدفعة الأولى",repeating:"خصم {discount} شهريًا لمدة {period}",forever:"خصم {discount} على كل دفعة"}};function N(e){let i=J(e)??"en",n=i.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(c=>["TW","HK","MO"].includes(c))?"zh-Hant":"zh-Hans":n[0]??"en",o=te[r];return o?{locale:i,copy:o}:{locale:"en",copy:te.en}}function je(e,i,n="zh-CN"){let r=K(i);return V(e,i,N(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function De(e,i="zh-CN"){let n=N(i).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):je(e.amountOffCents,e.currency,n)}var ie={zh:"前 {months} 个月内开出的账单减 {discount}","zh-Hant":"前 {months} 個月內開出的帳單減 {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"最初の {months} か月以内の請求が {discount} 割引",ko:"첫 {months}개월 내 청구서 {discount} 할인",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de réduction sur les factures émises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"Скидка {discount} на счета в течение первых {months} мес.",vi:"Giảm {discount} cho hóa đơn trong {months} tháng đầu",th:"ลด {discount} สำหรับใบแจ้งหนี้ในช่วง {months} เดือนแรก",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"خصم {discount} على الفواتير الصادرة خلال أول {period}"};function Lt(e,i="zh-CN",n="month"){let r=N(i),o=De(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",o);let c=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0]??"en",d=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,l=e.duration.type==="repeating"&&n!=="month"?ie[d]??ie.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],Ee=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return l.replace("{discount}",o).replace("{months}",c).replace("{period}",Ee)}var Qt=t.discriminatedUnion("action",[t.strictObject({action:t.literal("create"),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:t.enum(["introductory","promotional"])}),t.strictObject({action:t.literal("set_enabled"),id:t.uuid(),revision:t.number().int().nonnegative(),enabled:t.boolean()})]),$t=t.array(t.strictObject({id:t.uuid(),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).nullable(),storeOfferType:t.enum(["introductory","promotional"]),enabled:t.boolean(),revision:t.number().int().nonnegative()})).max(500),I=t.strictObject({offerKind:t.enum(["none","introductory","promotional"]),offerId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:t.number().int().min(0).max(1e8),trialDays:t.number().int().min(1).max(730).nullable()}).superRefine((e,i)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&i.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),Kt=t.record(t.uuid(),I).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var U=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:Y,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(o=>o.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var ke=t.enum(["active","inactive"]),Re=t.preprocess((e,i)=>{let n=0;function r(o,c){if(!(++n>1e4||c>20)){if(Array.isArray(o))o.forEach(a=>r(a,c+1));else if(o&&typeof o=="object")for(let[a,d]of Object.entries(o))["__proto__","constructor","prototype"].includes(a)&&i.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(d,c+1)}}return r(e,0),e},X),Ne=t.strictObject({id:t.string().trim().min(1).max(255),name:t.string().trim().min(1).max(255),status:ke,metadata:Re}),ei=Ne.extend({internal_id:t.uuid(),project_id:t.uuid(),environment_id:t.uuid(),created_at:t.iso.datetime({offset:!0}),updated_at:t.iso.datetime({offset:!0})}),ti=t.union([t.strictObject({id:t.string().trim().min(1).max(255)}),t.strictObject({internalId:t.uuid()})]),ii=t.enum(["customer","merchandise","context"]),ni=t.enum(["system","stored","request"]),ri=t.enum(["customer","merchandise","mixed"]),ne=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function q(e,i={},n=new Set){if(ee(e).some(ne))return!0;for(let r of z(e)){if(n.has(r))continue;n.add(r);let o=i[r];if(o?.type==="list"&&ne(o.attributeKey)||o?.type==="condition"&&q(o.condition,i,n))return!0}return!1}var di=t.enum(["draft","active","paused","archived"]),v=t.discriminatedUnion("type",[t.object({type:t.literal("percent"),percentOff:t.number().min(1).max(100).multipleOf(.01)}).strict(),t.object({type:t.literal("amount"),amountOffCents:t.number().int().min(1).max(1e8),currency:u}).strict()]),A=t.discriminatedUnion("type",[t.object({type:t.literal("once")}).strict(),t.object({type:t.literal("repeating"),months:t.number().int().min(1).max(36)}).strict(),t.object({type:t.literal("forever")}).strict()]),re=[t.object({type:t.literal("all")}).strict(),t.object({type:t.literal("plans"),planIds:t.array(t.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"套餐不能重复")}).strict()],Ue=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.discriminatedUnion("type",[t.strictObject({type:t.literal("all")}),t.strictObject({type:t.literal("selected"),merchandiseIds:t.array(t.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),t.strictObject({type:t.literal("condition"),condition:R})])})]),qe=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.strictObject({type:t.enum(["all","selected","condition"])})})]),Be=t.strictObject({firstPurchaseOnly:t.boolean(),condition:R}),pi=t.object({name:t.string().trim().min(1).max(80),description:t.string().max(500),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:Ue,eligibility:Be,selfClaimEnabled:t.boolean().default(!1),startsAt:t.iso.datetime().nullable(),endsAt:t.iso.datetime().nullable(),totalLimit:t.number().int().min(1).max(1e6).nullable(),perCustomerLimit:t.number().int().min(1).max(10),grantWindowHours:t.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"结束时间必须晚于开始时间",path:["endsAt"]}).refine(e=>!q(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),li=t.object({code:t.string().trim().transform(e=>e.toUpperCase()).pipe(t.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"优惠码只能用 3–32 位字母、数字、- 和 _,以字母或数字开头")),maxRedemptions:t.number().int().min(1).max(1e6).nullable(),expiresAt:t.iso.datetime().nullable(),firstPurchaseOnly:t.boolean(),minimumAmountCents:t.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:u.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var hi=t.object({id:t.uuid(),couponId:t.uuid(),status:t.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:t.iso.datetime(),expiresAt:t.iso.datetime(),coupon:t.object({name:t.string(),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:qe}).strict()}).strict(),fi=t.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var oe=t.strictObject({itemKey:t.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:Z,pricing:H.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{W(e.includedAmount,e.terms.units,e.quantity),_({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var C=t.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID 使用小写字母、数字和下划线,并以字母开头"),vi=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"免费套餐金额必须为 0,付费金额必须大于 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"附加币种不能重复默认币种;免费套餐不设置附加价格");var Le=t.registry(),{BillingInterval:ae}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Fe}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(t),{withSpecDefault:Ge}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:o})=>(e.add(n,{description:o,default:r}),n)}))(Le),{COMMON:se}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Qe}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:$e}=(e=>({COMMON_SET:new Set(e)}))(se),{hasNoDuplicateCurrencies:ce}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let o=r.toLowerCase();if(n.has(o))return!1;n.add(o)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:ue}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ke}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Ve}={Infinite:"inf"},{TierBehavior:He}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:me}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ze}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:We}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ye}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Je}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:de}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(t),{VIOLATION_MESSAGES:Xe}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:pe}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:ze}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,pe),{InvoiceUsageEntrySchema:et}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(t),{AttachDiscountSchema:le}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(t),{CustomLineItemSchema:tt}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(t),{UnixMsTimestampSchema:it}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:nt}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(t),{ReissueInvoiceParamsSchema:wi}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(t),{InvoiceModeParamsSchema:h}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(t),{InvoiceTemplateSchema:Ti}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(t),{BasePriceSchema:rt}=((e,i,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(i).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(t,ae,Fe),{CURRENCY_CODES:ot}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(o=>!n.has(o)).sort()]}))(se,Qe,$e),{ApiPriceProcessorsSchema:he}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ke),{AllocatedBillingFieldSchema:at}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(t,Ze),{CreditDimensionNameSchema:st}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(o=>!o.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,We,Ye),{ApiCreditMatchSchema:fe}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Je),{findCreditTierViolations:ct}=(e=>({findCreditTierViolations:n=>{let r=[],o=(a,d)=>r.push({index:a,reason:d,message:e[d]}),c=0;for(let[a,d]of n.entries()){let l=a===n.length-1;if(d==="inf"){l||o(a,"non_final_infinity");continue}(!Number.isFinite(d)||d<=c)&&o(a,"not_increasing"),c=d,l&&o(a,"final_not_infinity")}return r}}))(Xe),{ApiCreditMultiplierSchema:ut}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(t,fe),{ProviderMarkupsSchema:mt}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,pe),{InvoiceFeatureQuantitySchema:be}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(o=>o.quantity!==void 0!=(o.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,me,et),{CreateInvoicePreviewSchema:Ei}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(t,nt),{SUPPORTED_SET:dt}=(e=>({SUPPORTED_SET:new Set(e)}))(ot),{ApiCreditDimensionBaseSchema:pt}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,fe),{refineGraduatedTiers:ye}=(e=>({refineGraduatedTiers:(n,r)=>{let o=e(n.tiers.map(c=>c.to));for(let{index:c,message:a}of o)r.addIssue({code:"custom",message:a,path:["tiers",c,"to"]})}}))(ct),{ApiFeatureMarkupsOverrideSchema:lt}=((e,i,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:i.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(t,mt,ze),{isValidCurrencyCode:ht}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(dt),{ApiCreditDimensionSchema:ft}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,pt,de,ye),{CurrencyCodeSchema:ge}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,ht),{AdditionalCurrencyTierSchema:bt}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(t,ge),{ApiCreditSchemaItemBaseSchema:Se}=((e,i,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(i,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,st,ft,ut),{ApiFlatCreditSchemaItemSchema:yt}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Se,t),{AdditionalCurrencyPriceSchema:gt}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,ge),{AdditionalCurrencyTierArraySchema:St}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,bt,ce,ue),{ApiGraduatedCreditSchemaItemSchema:_t}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(Se,t,de,ye),{AdditionalCurrencyPriceArraySchema:_e}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,gt,ce,ue),{ApiUsageTierWithCurrenciesSchema:xt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(o=>o.amount!==void 0||o.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(o=>({...o,amount:o.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Ve,St),{ApiCreditSchemaItemSchema:It}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,_t,yt),{BasePriceParamsSchema:vt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(rt,Ge,t,_e),{PlanItemPriceParamsSchema:At}=((e,i,n,r,o,c,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:i.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(o).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(c).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(t,_e,xt,He,ae,me,at),{ApiFeatureOverrideSchema:Ct}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(t,It,lt),{InvoiceBasePriceParamsSchema:xe}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(vt,he),{InvoiceItemPriceParamsSchema:Ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(At,he),{InvoiceLicenseQuantitySchema:Pt}=((e,i,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:i.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(t,xe,be),{InvoiceCustomizeItemSchema:Mt}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(t,Ot,Ct),{InvoiceCustomizeSchema:wt}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(t,xe,Mt),{InvoicePlanParamsSchema:Tt}=((e,i,n,r,o)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(o).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(t,wt,be,Pt,le),{CreateInvoiceParamsSchema:ji}=((e,i,n,r,o)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:o.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start → period_end against one price interval starting at period_start."}),period_end:o.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(t,Tt,tt,le,it);var m=t.iso.datetime({offset:!0}),Ae=t.url().refine(e=>new URL(e).protocol==="https:").nullable(),Zi=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:h.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:I.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(C,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Wi=t.strictObject({operationId:t.uuid()}),s=t.number().int().min(0).max(1e8),Et=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:s,seats:t.array(t.strictObject({key:C,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:s})).max(20),prepaid:t.array(oe).max(100).optional(),catalogAmountMinor:s,trial:G.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+_({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Ce=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),jt=t.strictObject({id:Ce,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Dt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),Oe=t.strictObject({invoiceMode:h.optional(),append:Dt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:Ce,terms:jt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:m}),B=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:v,duration:A,amountMinor:s,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:s})).min(1).max(20),expiresAt:m}).nullable(),charge:t.strictObject({effectiveAt:m,periodEndsAt:m,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s}).nullable(),expiresAt:m,provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:I.optional(),currency:u,lines:t.array(Et).min(1).max(20),catalogAmountMinor:s,nativeDiscountMinor:s.optional(),automaticTax:t.boolean(),execution:t.union([Oe,T]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&S(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Pe=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:Ae,execution:t.union([Oe,T]).nullable(),currency:u,catalogAmountMinor:s,taxMinor:s,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:U.nullable(),confirmedAt:m.nullable().optional(),quote:B.optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),P=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Yi=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:h.optional(),membershipId:t.uuid(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid(),featureQuantities:f.optional()}),t.strictObject({type:t.literal("seats"),licenseKey:C,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),O=t.string().regex(/^price_[A-Za-z0-9]+$/),Ie=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),ve=t.strictObject({price:O.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),Me=t.strictObject({provider:t.literal("stripe"),invoiceMode:h.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(ve).max(20),remove:t.array(O).max(20),restoreItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:Ie}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(ve).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:Ie}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:m}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),M=t.strictObject({merchantTerms:g.optional(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),timing:t.enum(["immediate","renewal"]),effectiveAt:m,expiresAt:m,currency:u,creditMinor:s,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([Me,E])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"subscription_change",e.currency)),L=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:m,checkoutUrl:Ae,executor:t.enum(["indiana","merchant"]),execution:t.union([Me,E]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),quote:M.optional(),authority:x.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),kt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:m,currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:s,policy:t.enum(["apple_store","google_full_price"])})}),Rt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:m.nullable(),checkoutUrl:t.null(),nativePurchase:U.nullable()}),Ji=t.union([M,kt]),Xi=t.union([L,Rt]),F=Q,p=$,zi=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount"),we=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:F,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Nt=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([we,j]),expiresAt:m}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ut=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:Nt.optional(),execution:t.union([we,j]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:m,completedAt:m.nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),en=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,refundableMinor:p,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(Ut).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),tn=t.strictObject({requestId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount");var an=t.strictObject({membershipId:t.uuid(),timing:t.enum(["immediate","renewal"])}),sn=t.union([B,M]),cn=t.union([Pe,L]);function un(e){return"membershipId"in e}function Te(e){return"membershipId"in e}function mn(e){return Te(e)?e.status==="effective"||e.status==="scheduled":e.status==="complete"}function dn(e){return Te(e)?["prepared","quoted","confirmed","pending"].includes(e.status):e.status==="pending"}export{I as a,ti as b,je as c,De as d,Lt as e,v as f,A as g,qe as h,hi as i,fi as j,wi as k,Ei as l,ji as m,Zi as n,Wi as o,B as p,Pe as q,Yi as r,M as s,Ji as t,Xi as u,zi as v,Nt as w,Ut as x,an as y,sn as z,cn as A,un as B,Te as C,mn as D,dn as E};
1
+ import{O as x,a as w,b as f,c as T,d as E,e as j,h as b,i as y,m as G,n as Q,o as $,p as D,q as k,s as g,t as S}from"./chunk-5WFI36LF.js";import{a as ee}from"./chunk-VILB5M4X.js";import{a as H,b as _,c as Z,d as W,q as J}from"./chunk-56YCOGQZ.js";import{a as u,b as K,c as V,d as Y}from"./chunk-O5YYORDW.js";import{e as X,f as R,g as z}from"./chunk-7OJIW75D.js";import{b as t}from"./chunk-YLH3AYCK.js";var te={"zh-Hans":{merchandise:"减 {discount}(单次使用)",once:"首期减 {discount}",repeating:"前 {months} 个月每月减 {discount}",forever:"每期减 {discount}"},"zh-Hant":{merchandise:"減 {discount}(單次使用)",once:"首期減 {discount}",repeating:"前 {months} 個月每月減 {discount}",forever:"每期減 {discount}"},en:{merchandise:"{discount} off · one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} 割引(1回のみ)",once:"初回のお支払いが {discount} 割引",repeating:"最初の {months} か月間、毎月 {discount} 割引",forever:"毎回のお支払いが {discount} 割引"},ko:{merchandise:"{discount} 할인 · 1회 사용",once:"첫 결제 {discount} 할인",repeating:"첫 {months}개월 동안 매월 {discount} 할인",forever:"매 결제 {discount} 할인"},es:{merchandise:"{discount} de descuento · un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de réduction · une utilisation",once:"{discount} de réduction sur le premier paiement",repeating:"{discount} de réduction par mois pendant les {months} premiers mois",forever:"{discount} de réduction sur chaque paiement",repeatingOne:"{discount} de réduction pendant le premier mois"},de:{merchandise:"{discount} Rabatt · einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat für die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto · um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por mês nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro mês"},it:{merchandise:"{discount} di sconto · un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"Скидка {discount} · одно использование",once:"Скидка {discount} на первый платёж",repeating:"Скидка {discount} каждый месяц в течение первых {months} мес.",repeatingOne:"Скидка {discount} в первый месяц",forever:"Скидка {discount} на каждый платёж"},vi:{merchandise:"Giảm {discount} · dùng một lần",once:"Giảm {discount} cho lần thanh toán đầu tiên",repeating:"Giảm {discount} mỗi tháng trong {months} tháng đầu",forever:"Giảm {discount} cho mỗi lần thanh toán"},th:{merchandise:"ลด {discount} · ใช้ได้ครั้งเดียว",once:"ลด {discount} สำหรับการชำระเงินครั้งแรก",repeating:"ลด {discount} ต่อเดือนในช่วง {months} เดือนแรก",forever:"ลด {discount} สำหรับการชำระเงินทุกครั้ง"},id:{merchandise:"Diskon {discount} · sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"خصم {discount} · استخدام واحد",once:"خصم {discount} على الدفعة الأولى",repeating:"خصم {discount} شهريًا لمدة {period}",forever:"خصم {discount} على كل دفعة"}};function N(e){let i=J(e)??"en",n=i.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(c=>["TW","HK","MO"].includes(c))?"zh-Hant":"zh-Hans":n[0]??"en",o=te[r];return o?{locale:i,copy:o}:{locale:"en",copy:te.en}}function je(e,i,n="zh-CN"){let r=K(i);return V(e,i,N(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function De(e,i="zh-CN"){let n=N(i).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):je(e.amountOffCents,e.currency,n)}var ie={zh:"前 {months} 个月内开出的账单减 {discount}","zh-Hant":"前 {months} 個月內開出的帳單減 {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"最初の {months} か月以内の請求が {discount} 割引",ko:"첫 {months}개월 내 청구서 {discount} 할인",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de réduction sur les factures émises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"Скидка {discount} на счета в течение первых {months} мес.",vi:"Giảm {discount} cho hóa đơn trong {months} tháng đầu",th:"ลด {discount} สำหรับใบแจ้งหนี้ในช่วง {months} เดือนแรก",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"خصم {discount} على الفواتير الصادرة خلال أول {period}"};function Lt(e,i="zh-CN",n="month"){let r=N(i),o=De(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",o);let c=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0]??"en",d=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,l=e.duration.type==="repeating"&&n!=="month"?ie[d]??ie.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],Ee=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return l.replace("{discount}",o).replace("{months}",c).replace("{period}",Ee)}var Qt=t.discriminatedUnion("action",[t.strictObject({action:t.literal("create"),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:t.enum(["introductory","promotional"])}),t.strictObject({action:t.literal("set_enabled"),id:t.uuid(),revision:t.number().int().nonnegative(),enabled:t.boolean()})]),$t=t.array(t.strictObject({id:t.uuid(),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).nullable(),storeOfferType:t.enum(["introductory","promotional"]),enabled:t.boolean(),revision:t.number().int().nonnegative()})).max(500),I=t.strictObject({offerKind:t.enum(["none","introductory","promotional"]),offerId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:t.number().int().min(0).max(1e8),trialDays:t.number().int().min(1).max(730).nullable()}).superRefine((e,i)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&i.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),Kt=t.record(t.uuid(),I).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var U=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:Y,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(o=>o.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var ke=t.enum(["active","inactive"]),Re=t.preprocess((e,i)=>{let n=0;function r(o,c){if(!(++n>1e4||c>20)){if(Array.isArray(o))o.forEach(a=>r(a,c+1));else if(o&&typeof o=="object")for(let[a,d]of Object.entries(o))["__proto__","constructor","prototype"].includes(a)&&i.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(d,c+1)}}return r(e,0),e},X),Ne=t.strictObject({id:t.string().trim().min(1).max(255),name:t.string().trim().min(1).max(255),status:ke,metadata:Re}),ei=Ne.extend({internal_id:t.uuid(),project_id:t.uuid(),environment_id:t.uuid(),created_at:t.iso.datetime({offset:!0}),updated_at:t.iso.datetime({offset:!0})}),ti=t.union([t.strictObject({id:t.string().trim().min(1).max(255)}),t.strictObject({internalId:t.uuid()})]),ii=t.enum(["customer","merchandise","context"]),ni=t.enum(["system","stored","request"]),ri=t.enum(["customer","merchandise","mixed"]),ne=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function q(e,i={},n=new Set){if(ee(e).some(ne))return!0;for(let r of z(e)){if(n.has(r))continue;n.add(r);let o=i[r];if(o?.type==="list"&&ne(o.attributeKey)||o?.type==="condition"&&q(o.condition,i,n))return!0}return!1}var di=t.enum(["draft","active","paused","archived"]),v=t.discriminatedUnion("type",[t.object({type:t.literal("percent"),percentOff:t.number().min(1).max(100).multipleOf(.01)}).strict(),t.object({type:t.literal("amount"),amountOffCents:t.number().int().min(1).max(1e8),currency:u}).strict()]),A=t.discriminatedUnion("type",[t.object({type:t.literal("once")}).strict(),t.object({type:t.literal("repeating"),months:t.number().int().min(1).max(36)}).strict(),t.object({type:t.literal("forever")}).strict()]),re=[t.object({type:t.literal("all")}).strict(),t.object({type:t.literal("plans"),planIds:t.array(t.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"套餐不能重复")}).strict()],Ue=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.discriminatedUnion("type",[t.strictObject({type:t.literal("all")}),t.strictObject({type:t.literal("selected"),merchandiseIds:t.array(t.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),t.strictObject({type:t.literal("condition"),condition:R})])})]),qe=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.strictObject({type:t.enum(["all","selected","condition"])})})]),Be=t.strictObject({firstPurchaseOnly:t.boolean(),condition:R}),pi=t.object({name:t.string().trim().min(1).max(80),description:t.string().max(500),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:Ue,eligibility:Be,selfClaimEnabled:t.boolean().default(!1),startsAt:t.iso.datetime().nullable(),endsAt:t.iso.datetime().nullable(),totalLimit:t.number().int().min(1).max(1e6).nullable(),perCustomerLimit:t.number().int().min(1).max(10),grantWindowHours:t.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"结束时间必须晚于开始时间",path:["endsAt"]}).refine(e=>!q(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),li=t.object({code:t.string().trim().transform(e=>e.toUpperCase()).pipe(t.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"优惠码只能用 3–32 位字母、数字、- 和 _,以字母或数字开头")),maxRedemptions:t.number().int().min(1).max(1e6).nullable(),expiresAt:t.iso.datetime().nullable(),firstPurchaseOnly:t.boolean(),minimumAmountCents:t.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:u.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var hi=t.object({id:t.uuid(),couponId:t.uuid(),status:t.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:t.iso.datetime(),expiresAt:t.iso.datetime(),coupon:t.object({name:t.string(),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:qe}).strict()}).strict(),fi=t.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var oe=t.strictObject({itemKey:t.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:Z,pricing:H.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{W(e.includedAmount,e.terms.units,e.quantity),_({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var C=t.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID 使用小写字母、数字和下划线,并以字母开头"),vi=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"免费套餐金额必须为 0,付费金额必须大于 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"附加币种不能重复默认币种;免费套餐不设置附加价格");var Le=t.registry(),{BillingInterval:ae}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Fe}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(t),{withSpecDefault:Ge}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:o})=>(e.add(n,{description:o,default:r}),n)}))(Le),{COMMON:se}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Qe}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:$e}=(e=>({COMMON_SET:new Set(e)}))(se),{hasNoDuplicateCurrencies:ce}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let o=r.toLowerCase();if(n.has(o))return!1;n.add(o)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:ue}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ke}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Ve}={Infinite:"inf"},{TierBehavior:He}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:me}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ze}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:We}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ye}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Je}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:de}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(t),{VIOLATION_MESSAGES:Xe}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:pe}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:ze}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,pe),{InvoiceUsageEntrySchema:et}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(t),{AttachDiscountSchema:le}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(t),{CustomLineItemSchema:tt}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(t),{UnixMsTimestampSchema:it}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:nt}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(t),{ReissueInvoiceParamsSchema:wi}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(t),{InvoiceModeParamsSchema:h}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(t),{InvoiceTemplateSchema:Ti}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(t),{BasePriceSchema:rt}=((e,i,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(i).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(t,ae,Fe),{CURRENCY_CODES:ot}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(o=>!n.has(o)).sort()]}))(se,Qe,$e),{ApiPriceProcessorsSchema:he}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ke),{AllocatedBillingFieldSchema:at}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(t,Ze),{CreditDimensionNameSchema:st}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(o=>!o.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,We,Ye),{ApiCreditMatchSchema:fe}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Je),{findCreditTierViolations:ct}=(e=>({findCreditTierViolations:n=>{let r=[],o=(a,d)=>r.push({index:a,reason:d,message:e[d]}),c=0;for(let[a,d]of n.entries()){let l=a===n.length-1;if(d==="inf"){l||o(a,"non_final_infinity");continue}(!Number.isFinite(d)||d<=c)&&o(a,"not_increasing"),c=d,l&&o(a,"final_not_infinity")}return r}}))(Xe),{ApiCreditMultiplierSchema:ut}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(t,fe),{ProviderMarkupsSchema:mt}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,pe),{InvoiceFeatureQuantitySchema:be}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(o=>o.quantity!==void 0!=(o.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,me,et),{CreateInvoicePreviewSchema:Ei}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(t,nt),{SUPPORTED_SET:dt}=(e=>({SUPPORTED_SET:new Set(e)}))(ot),{ApiCreditDimensionBaseSchema:pt}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,fe),{refineGraduatedTiers:ye}=(e=>({refineGraduatedTiers:(n,r)=>{let o=e(n.tiers.map(c=>c.to));for(let{index:c,message:a}of o)r.addIssue({code:"custom",message:a,path:["tiers",c,"to"]})}}))(ct),{ApiFeatureMarkupsOverrideSchema:lt}=((e,i,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:i.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(t,mt,ze),{isValidCurrencyCode:ht}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(dt),{ApiCreditDimensionSchema:ft}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,pt,de,ye),{CurrencyCodeSchema:ge}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,ht),{AdditionalCurrencyTierSchema:bt}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(t,ge),{ApiCreditSchemaItemBaseSchema:Se}=((e,i,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(i,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,st,ft,ut),{ApiFlatCreditSchemaItemSchema:yt}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Se,t),{AdditionalCurrencyPriceSchema:gt}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,ge),{AdditionalCurrencyTierArraySchema:St}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,bt,ce,ue),{ApiGraduatedCreditSchemaItemSchema:_t}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(Se,t,de,ye),{AdditionalCurrencyPriceArraySchema:_e}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,gt,ce,ue),{ApiUsageTierWithCurrenciesSchema:xt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(o=>o.amount!==void 0||o.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(o=>({...o,amount:o.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Ve,St),{ApiCreditSchemaItemSchema:It}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,_t,yt),{BasePriceParamsSchema:vt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(rt,Ge,t,_e),{PlanItemPriceParamsSchema:At}=((e,i,n,r,o,c,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:i.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(o).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(c).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(t,_e,xt,He,ae,me,at),{ApiFeatureOverrideSchema:Ct}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(t,It,lt),{InvoiceBasePriceParamsSchema:xe}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(vt,he),{InvoiceItemPriceParamsSchema:Ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(At,he),{InvoiceLicenseQuantitySchema:Pt}=((e,i,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:i.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(t,xe,be),{InvoiceCustomizeItemSchema:Mt}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(t,Ot,Ct),{InvoiceCustomizeSchema:wt}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(t,xe,Mt),{InvoicePlanParamsSchema:Tt}=((e,i,n,r,o)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(o).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(t,wt,be,Pt,le),{CreateInvoiceParamsSchema:ji}=((e,i,n,r,o)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:o.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start → period_end against one price interval starting at period_start."}),period_end:o.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(t,Tt,tt,le,it);var m=t.iso.datetime({offset:!0}),Ae=t.url().refine(e=>new URL(e).protocol==="https:").nullable(),Zi=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:h.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:I.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(C,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Wi=t.strictObject({operationId:t.uuid()}),s=t.number().int().min(0).max(1e8),Et=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:s,seats:t.array(t.strictObject({key:C,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:s})).max(20),prepaid:t.array(oe).max(100).optional(),catalogAmountMinor:s,trial:G.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+_({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Ce=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),jt=t.strictObject({id:Ce,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Dt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),Oe=t.strictObject({invoiceMode:h.optional(),append:Dt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:Ce,terms:jt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:m}),B=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:v,duration:A,amountMinor:s,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:s})).min(1).max(20),expiresAt:m}).nullable(),charge:t.strictObject({effectiveAt:m,periodEndsAt:m,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s}).nullable(),expiresAt:m,provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:I.optional(),currency:u,lines:t.array(Et).min(1).max(20),catalogAmountMinor:s,nativeDiscountMinor:s.optional(),automaticTax:t.boolean(),execution:t.union([Oe,T]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&S(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Pe=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:Ae,execution:t.union([Oe,T]).nullable(),currency:u,catalogAmountMinor:s,taxMinor:s,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:U.nullable(),confirmedAt:m.nullable().optional(),quote:B.optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),P=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Yi=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:h.optional(),membershipId:t.uuid(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid(),featureQuantities:f.optional()}),t.strictObject({type:t.literal("seats"),licenseKey:C,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),O=t.string().regex(/^price_[A-Za-z0-9]+$/),Ie=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),ve=t.strictObject({price:O.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),Me=t.strictObject({provider:t.literal("stripe"),invoiceMode:h.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(ve).max(20),remove:t.array(O).max(20),restoreItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:Ie}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(ve).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:Ie}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:m}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),M=t.strictObject({merchantTerms:g.optional(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),timing:t.enum(["immediate","renewal"]),effectiveAt:m,expiresAt:m,currency:u,creditMinor:s,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([Me,E])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"subscription_change",e.currency)),L=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:m,checkoutUrl:Ae,executor:t.enum(["indiana","merchant"]),execution:t.union([Me,E]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),quote:M.optional(),authority:x.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),kt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:m,currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:s,policy:t.enum(["apple_store","google_full_price"])})}),Rt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:m.nullable(),checkoutUrl:t.null(),nativePurchase:U.nullable()}),Ji=t.union([M,kt]),Xi=t.union([L,Rt]),F=Q,p=$,zi=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount"),we=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:F,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Nt=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([we,j]),expiresAt:m}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ut=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:Nt.optional(),execution:t.union([we,j]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:m,completedAt:m.nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),en=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,refundableMinor:p,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(Ut).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),tn=t.strictObject({requestId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount");var an=t.strictObject({membershipId:t.uuid(),timing:t.enum(["immediate","renewal"])}),sn=t.union([B,M]),cn=t.union([Pe,L]);function un(e){return"membershipId"in e}function Te(e){return"membershipId"in e}function mn(e){return Te(e)?e.status==="effective"||e.status==="scheduled":e.status==="complete"}function dn(e){return Te(e)?["prepared","quoted","confirmed","pending"].includes(e.status):e.status==="pending"}export{I as a,ti as b,je as c,De as d,Lt as e,v as f,A as g,qe as h,hi as i,fi as j,wi as k,Ei as l,ji as m,Zi as n,Wi as o,B as p,Pe as q,Yi as r,M as s,Ji as t,Xi as u,zi as v,Nt as w,Ut as x,an as y,sn as z,cn as A,un as B,Te as C,mn as D,dn as E};
@@ -1 +1 @@
1
- import{b as B}from"./chunk-AEQUKR4O.js";import{a as Y}from"./chunk-NDNHTG5B.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-5LNX7MHO.js";import{K as L}from"./chunk-EKUDMQXT.js";import{b as J}from"./chunk-4OODZM64.js";import{B as V}from"./chunk-EB7MIZ4T.js";import{x as H}from"./chunk-S5RM3VO6.js";import{t as z}from"./chunk-VXDVMAS6.js";import{a as u}from"./chunk-TK3WOD2O.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:m,load:d}=ie(r);try{return await d(),m}catch(h){throw m.destroy(),h}}function ie(r){let m=r.view;if(!m?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=m.paywall.receiptId,h=m.nodeId,E=m.visit,R=m.paywall.resolution,n=m.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,f=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??m.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(f=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??m.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??f,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!f?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(f&&f!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=f!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(f===e.requestId&&g)return g;f!==e.requestId&&C++;let y=C;f=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),f===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(f=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
1
+ import{b as B}from"./chunk-AEQUKR4O.js";import{a as Y}from"./chunk-KVLOMX2G.js";import{c as W,e as X,f as Z,g as $,h as ee,i as te}from"./chunk-JBN6ADWQ.js";import{K as L}from"./chunk-AD35L6BX.js";import{b as J}from"./chunk-ZWNWVMCH.js";import{B as V}from"./chunk-3Q3DZEP3.js";import{x as H}from"./chunk-5WFI36LF.js";import{t as z}from"./chunk-Q523TPZM.js";import{a as u}from"./chunk-46USIMCJ.js";import{a as K}from"./chunk-DSPLGTQI.js";async function ye(r){let{session:m,load:d}=ie(r);try{return await d(),m}catch(h){throw m.destroy(),h}}function ie(r){let m=r.view;if(!m?.paywall)throw new u("INVALID_REQUEST","The current node is not a Paywall");let d=m.paywall.receiptId,h=m.nodeId,E=m.visit,R=m.paywall.resolution,n=m.paywall,N="document"in R?{document:R.document,offering:R.offering,capabilities:R.capabilities}:null;function D(){let e=n.resolution;return"document"in e?e:N&&{...e,document:N.document,offering:N.offering,capabilities:W(e.capabilities,N.capabilities)}}function F(e){if(!X(e,R))throw new u("INVALID_RESPONSE","The pinned Paywall binding changed")}let p=!1,A=new Set,_=null;function G(){let e=D();if(e&&!p)for(let o of A)K(o,structuredClone(e))}async function M(){b();let e=D();if(e)return structuredClone(e);if(!_){let o=(async()=>{if("document"in n.resolution||!r.resolvePaywall)throw new u("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await B(r,n.resolution);return b(),F(s),N={document:s.document,offering:s.offering,capabilities:s.capabilities},G(),D()})();_=o;let t=()=>{_===o&&(_=null)};o.then(t,t)}return _.then(o=>structuredClone(o))}let q=new AbortController,f=(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).find(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_quote")?.requestId??m.paywall.purchaseRequestId,C=0,g=null,T=new Set,I=null,v=new Map;function U(e){if(e.purchase&&e.purchase.receiptId!==d)throw new u("INVALID_RESPONSE","Purchase receipt changed");let o=e.run.paywall;return e.purchase??(o?.receiptId===d?o:null)}function b(){if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed")}function S(e,o,t){if(b(),o!==C||t!==void 0&&n.quote?.operationId!==t)return!1;let s=n.selectionGeneration??0,i=e.run.paywall;if(i?.receiptId===d){if((i.selectionGeneration??0)<(n.selectionGeneration??0))return!1;F(i.resolution)}let a=U(e),c=i?.receiptId===d&&(i.selectionGeneration??0)>s,l=c?a?.quote??null:a?.quote??n.quote,y=a?.operation??(l?.operationId===n.quote?.operationId?n.operation:null);return n.quote&&l&&ee(n.quote,l),l&&y&&Z(y,{operationId:l.operationId,membershipId:V(l)?l.membershipId:null,...V(l)?{featureQuantities:l.featureQuantities??{}}:{}},"Purchase operation changed"),(c||l?.operationId!==n.quote?.operationId)&&(C++,i?.receiptId===d&&(f=i.purchaseRequestId)),i?.canReselect===!0&&i.purchaseRequestId===I&&!(r.pendingCommands??[r.pendingCommand]).some(w=>w?.requestId===I)&&(I=null),n={...n,...i?.receiptId===d?i:{},...t!==void 0&&!c&&a?.canReselect!==void 0?{canReselect:a.canReselect}:{},quote:l,operation:te(n.operation,y,!0)},G(),!0}function O(e,o,t){return new Promise((s,i)=>{let a=!1,c=()=>{clearTimeout(P),q.signal.removeEventListener("abort",w)},l=Q=>{a||(a=!0,c(),s(Q))},y=Q=>{a||(a=!0,c(),i(Q))},w=()=>y(new u("IDENTITY_CHANGED","Paywall presentation has closed")),P=setTimeout(()=>y(new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t)),Math.max(0,o-Date.now()));q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w(),e.then(l,y)})}function ne(e){return new Promise(o=>{let t=()=>{clearTimeout(s),q.signal.removeEventListener("abort",t),o()},s=setTimeout(t,e);q.signal.addEventListener("abort",t,{once:!0}),q.signal.aborted&&t()})}function j(e,o){b();let t=v.get(e)??r.pendingCommands?.find(a=>a.requestId===e)??r.pendingCommand;if(t?.operation==="submit"&&t.requestId===e&&t.nodeId===h&&t.visit===E){o.type==="paywall_quote"&&t.input.type==="paywall_quote"&&t.input.predecessor&&!o.predecessor&&(o={...o,predecessor:t.input.predecessor});let a=L.parse(t),c=L.parse({...t,input:o});if(a.operation!=="submit"||c.operation!=="submit"||JSON.stringify(a.input)!==JSON.stringify(c.input))throw new u("CONFLICT","A purchase request cannot change its input");return v.set(e,a),a}let s=r.view;if(!s||s.nodeId!==h||s.visit!==E||s.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","The Paywall visit has changed");let i=L.parse({operation:"submit",requestId:e,nodeId:h,visit:E,revision:s.revision,input:structuredClone(o)});if(i.operation!=="submit")throw new u("INVALID_REQUEST","A purchase submission is required");return v.set(e,i),i}async function x(e,o){b();let{requestId:t,input:s}=e,i=Date.now()+3e4;T.add(t);try{let a=await O(r.submit(e),i,t);for(;a.run.pendingRequest?.requestId===t&&Date.now()<i&&!p&&(await ne(Math.min(1e3,i-Date.now())),!(p||Date.now()>=i));)a=await O(r.resume(t),i,t);if(p)throw new u("IDENTITY_CHANGED","Paywall presentation has closed");if(a.run.pendingRequest?.requestId===t)throw new u("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!S(a,o,s.type==="paywall_confirm"||s.type==="paywall_cancel"?s.operationId:void 0))throw new u("PRECONDITION_FAILED","The purchase selection has changed");I===t&&(I=null)}catch(a){if(I=t,s.type==="paywall_quote"&&r.settle&&!p&&a instanceof u&&a.status!==void 0&&![401,425].includes(a.status)&&!a.retryable&&a.recovery!=="recover_operation")try{if((await O(r.settle(t),i,t)).settlement?.state==="settled"){let l=await O(r.get(),i,t);S(l,o)&&l.run.paywall?.purchaseRequestId===t&&n.canReselect===!0&&v.delete(t)}}catch{}throw a instanceof u&&a.code==="COMMAND_PENDING"&&a.status===void 0&&v.delete(t),a}finally{T.delete(t)}}async function k(e){if(!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let o=e==="confirm"?"paywall_confirm":"paywall_cancel",t=[...v.values(),...r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])].find(i=>i.operation==="submit"&&i.input.type===o&&"operationId"in i.input&&i.input.operationId===n.quote.operationId),s=t?.operation==="submit"&&t.input.type===o&&"operationId"in t.input&&t.input.operationId===n.quote.operationId?t.requestId:crypto.randomUUID();if(await x(j(s,{type:e==="confirm"?"paywall_confirm":"paywall_cancel",operationId:n.quote.operationId,...e==="confirm"&&n.quote.merchantTerms?{merchantConfirmation:H(n.quote.merchantTerms)}:{}}),C),!n.operation)throw new u("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(n.operation)}let oe={get view(){return structuredClone(D())},get quote(){return n.quote?structuredClone(n.quote):null},get operation(){return n.operation?structuredClone(n.operation):null},get webViewUrl(){return r.webViewUrl},get locale(){return r.view?.locale??m.locale},get canReselect(){return n.canReselect===!0&&I===null},get recovery(){let e=r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[]),o=r.pendingPurchase;if(o&&(o.receiptId!==d||o.operationId!==n.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:e[0]?.requestId??null};let t=Y({quote:n.quote,operation:n.operation,requestId:e[0]?.requestId??I??f,pending:T.size>0||e.length>0||I!==null,destroyed:p,canReselect:n.canReselect});return t.type==="recover"&&t.requestId===null&&!p&&r.hasDurableJournal===!0&&!n.quote&&!n.operation&&(n.selectionGeneration??0)===0&&!o&&!e.length&&!T.size&&!f?{type:"native",operationId:null}:t},get pendingCancellation(){return!p&&(r.pendingCommands??(r.pendingCommand?[r.pendingCommand]:[])).some(e=>e.operation==="submit"&&e.nodeId===h&&e.visit===E&&e.input.type==="paywall_cancel"&&e.input.operationId===n.quote?.operationId)},subscribe(e){return p?()=>{}:(A.add(e),()=>A.delete(e))},async refresh(){b();let e=C,o=await r.get();if(S(o,e),o.run.paywall?.receiptId!==d)throw new u("PRECONDITION_FAILED","Paywall presentation has changed");return M()},preview(e){let o=D();if(!o)return Promise.reject(new u("PRECONDITION_FAILED","Load the Paywall presentation first"));if(f&&f!==e.requestId&&(g||n.canReselect!==!0))return Promise.reject(new u("COMMAND_PENDING","Retry the original purchase before starting another"));let t=o.document.buttons[e.actionId],s=t?.type==="checkout"?J(t.product,e.selection,o.capabilities):null;if(!s)return Promise.reject(new u("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let i=z(o.document.screen,s,e.selection,o.capabilities),a=f!==e.requestId&&(n.selectionGeneration??0)>0?{operationId:n.quote?.operationId??null,generation:n.selectionGeneration??0}:void 0,c=r.view?.parameters.commerce;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.intent==="subscription_change"&&!e.subscriptionChange)return Promise.reject(new u("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(e.subscriptionChange&&e.nativeOffer)return Promise.reject(new u("INVALID_REQUEST","A web membership change cannot include a store offer"));if(a&&n.canReselect!==!0)return Promise.reject(new u("COMMAND_PENDING","Original purchase requires authoritative termination"));let l;try{l=j(e.requestId,{type:"paywall_quote",actionId:e.actionId,productVersionId:s,...Object.keys(i).length?{featureQuantities:i}:{},...a?{predecessor:a}:{},...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{},...e.subscriptionChange?{subscriptionChange:e.subscriptionChange}:{}})}catch(P){return Promise.reject(P)}if(f===e.requestId&&g)return g;f!==e.requestId&&C++;let y=C;f=e.requestId;let w=(async()=>{if(await x(l,y),!n.quote)throw new u("INVALID_RESPONSE","The accepted quote is missing");return $(n.quote,{productVersionId:s,featureQuantities:i,subscriptionChange:e.subscriptionChange},"The selected purchase changed"),structuredClone(n.quote)})();return g=w,w.then(()=>{g===w&&(g=null)},P=>{g===w&&(g=null),f===e.requestId&&r.pendingCommand?.requestId!==e.requestId&&P instanceof u&&P.status!==void 0&&P.status<500&&![401,425].includes(P.status)&&(f=null)}),w},confirm:()=>k("confirm"),cancel:()=>k("cancel"),async read(){if(b(),!n.quote)throw new u("INVALID_REQUEST","A quoted purchase is required");let e=n.quote.operationId,o=C,t=r.pendingCommands?.find(l=>l.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===e)??r.pendingCommand;t?.operation==="submit"&&(t.input.type==="paywall_confirm"||t.input.type==="paywall_cancel")&&t.input.operationId===e&&await r.settle?.(t.requestId);let s=await r.get(void 0,{receiptId:d,operationId:e});b();let i=U(s);if(i?.quote&&i.quote.operationId!==e||i?.operation&&i.operation.operationId!==e)throw new u("INVALID_RESPONSE","Purchase operation changed");let a=S(s,o,e),c=a?n.operation:i?.operation;if(!c)throw new u("INVALID_RESPONSE","The current purchase result is missing");return a&&T.size===0&&!(r.pendingCommands?.length??(r.pendingCommand?1:0))&&(I=null),structuredClone(c)},destroy(){p=!0,re(),A.clear(),q.abort(),v.clear()}},re=r.subscribe(e=>{p||e.nodeId!==h||e.visit!==E||e.paywall?.receiptId!==d||(e.paywall.selectionGeneration??0)<(n.selectionGeneration??0)||(F(e.paywall.resolution),n={...n,resolution:e.paywall.resolution},G())});return{session:oe,load:M}}export{ye as a};
@@ -1 +1 @@
1
- import{f as o}from"./chunk-RIEWU4MN.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
1
+ import{f as o}from"./chunk-XIBJF5E6.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
@@ -1 +1 @@
1
- import{a as s}from"./chunk-TK3WOD2O.js";var p=new WeakMap;function P(i,n){p.set(i,n)}function v(i){let n,l=!1,d=new AbortController,u=e=>(i.client.pendingCommands??(i.client.pendingCommand?[i.client.pendingCommand]:[])).some(r=>r.requestId===e.command.requestId),m=()=>i.document.defaultView?.navigator.onLine!==!1,C=e=>new Promise((r,t)=>{let o=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),r()},a=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),t(new s("IDENTITY_CHANGED","Closing presentation was released"))},c=setTimeout(o,e);d.signal.addEventListener("abort",a,{once:!0}),d.signal.aborted&&a()});async function b(e,r){try{let t;for(let o=0;o<3;o++){if(l)throw new s("IDENTITY_CHANGED","Closing presentation was released");if(o&&(!m()||(await C(o===1?500:2e3),!m())))break;try{let a=p.get(i.client),c=r&&o===0?await(a?a(e.command,()=>{l||n!==e||(e.retained=!0,i.conceal())}):i.client.submit(e.command)):await i.client.retry();if(l)return c;if(!e.retained||!u(e))return n===e&&(n=void 0),await i.receive(c),c;t=new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(a){if(t=a,!e.retained||!u(e))throw a}}throw t??new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(t){throw!u(e)&&n===e&&(n=void 0),!l&&e.retained&&i.failed(t),t}}function f(e,r){if(e.flight)return e.flight;let t=b(e,r);e.flight=t;let o=()=>{e.flight===t&&(e.flight=void 0)};return t.then(o,o),t}function g(){if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));let e=n;return!e||!u(e)?Promise.reject(new s("INVALID_REQUEST","No closing command is pending")):(!e.flight&&e.retained&&i.conceal(),f(e,!1))}let w=()=>{!l&&n?.retained&&!n.flight&&u(n)&&g().catch(()=>{})};return i.document.defaultView?.addEventListener("online",w),{get pending(){return n?.retained===!0},observe(){n&&!n.flight&&!u(n)&&(n=void 0)},submit(e){if(e.operation==="submit"&&e.input.type!=="screen")return Promise.reject(new s("INVALID_REQUEST","Presentation closure cannot execute a purchase"));if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));if(n&&u(n)){let t=n.command;return t.operation===e.operation&&t.nodeId===e.nodeId&&t.visit===e.visit&&(t.operation==="close"||t.operation==="submit"&&e.operation==="submit"&&JSON.stringify(t.input)===JSON.stringify(e.input))?f(n,!n.retained):Promise.reject(new s("COMMAND_PENDING","Recover the original closing command"))}let r={command:e,retained:!1};return n=r,f(r,!0)},retry:g,destroy(){l=!0,d.abort(),i.document.defaultView?.removeEventListener("online",w)}}}export{P as a,v as b};
1
+ import{a as s}from"./chunk-46USIMCJ.js";var p=new WeakMap;function P(i,n){p.set(i,n)}function v(i){let n,l=!1,d=new AbortController,u=e=>(i.client.pendingCommands??(i.client.pendingCommand?[i.client.pendingCommand]:[])).some(r=>r.requestId===e.command.requestId),m=()=>i.document.defaultView?.navigator.onLine!==!1,C=e=>new Promise((r,t)=>{let o=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),r()},a=()=>{clearTimeout(c),d.signal.removeEventListener("abort",a),t(new s("IDENTITY_CHANGED","Closing presentation was released"))},c=setTimeout(o,e);d.signal.addEventListener("abort",a,{once:!0}),d.signal.aborted&&a()});async function b(e,r){try{let t;for(let o=0;o<3;o++){if(l)throw new s("IDENTITY_CHANGED","Closing presentation was released");if(o&&(!m()||(await C(o===1?500:2e3),!m())))break;try{let a=p.get(i.client),c=r&&o===0?await(a?a(e.command,()=>{l||n!==e||(e.retained=!0,i.conceal())}):i.client.submit(e.command)):await i.client.retry();if(l)return c;if(!e.retained||!u(e))return n===e&&(n=void 0),await i.receive(c),c;t=new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(a){if(t=a,!e.retained||!u(e))throw a}}throw t??new s("COMMAND_PENDING","Closing is still being confirmed. Retry the original request.")}catch(t){throw!u(e)&&n===e&&(n=void 0),!l&&e.retained&&i.failed(t),t}}function f(e,r){if(e.flight)return e.flight;let t=b(e,r);e.flight=t;let o=()=>{e.flight===t&&(e.flight=void 0)};return t.then(o,o),t}function g(){if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));let e=n;return!e||!u(e)?Promise.reject(new s("INVALID_REQUEST","No closing command is pending")):(!e.flight&&e.retained&&i.conceal(),f(e,!1))}let w=()=>{!l&&n?.retained&&!n.flight&&u(n)&&g().catch(()=>{})};return i.document.defaultView?.addEventListener("online",w),{get pending(){return n?.retained===!0},observe(){n&&!n.flight&&!u(n)&&(n=void 0)},submit(e){if(e.operation==="submit"&&e.input.type!=="screen")return Promise.reject(new s("INVALID_REQUEST","Presentation closure cannot execute a purchase"));if(l)return Promise.reject(new s("IDENTITY_CHANGED","Closing presentation was released"));if(n&&u(n)){let t=n.command;return t.operation===e.operation&&t.nodeId===e.nodeId&&t.visit===e.visit&&(t.operation==="close"||t.operation==="submit"&&e.operation==="submit"&&JSON.stringify(t.input)===JSON.stringify(e.input))?f(n,!n.retained):Promise.reject(new s("COMMAND_PENDING","Recover the original closing command"))}let r={command:e,retained:!1};return n=r,f(r,!0)},retry:g,destroy(){l=!0,d.abort(),i.document.defaultView?.removeEventListener("online",w)}}}export{P as a,v as b};