@tinkerlandai/longplay-sdk 0.10.70 → 0.10.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +1 -1
- package/dist/check-response-FTYRCENP.js +1 -0
- package/dist/{chunk-FEOTHBMD.js → chunk-2DAYQCEC.js} +1 -1
- package/dist/{chunk-F3WIZE6M.js → chunk-2UB5RFXZ.js} +1 -1
- package/dist/{chunk-5DWUXPEL.js → chunk-2WINZC4O.js} +1 -1
- package/dist/chunk-2WMBBFPQ.js +1 -0
- package/dist/{chunk-OLRWD7DF.js → chunk-3DW3Q6RU.js} +1 -1
- package/dist/chunk-3TKVWOFW.js +1 -0
- package/dist/{chunk-AME3L7BT.js → chunk-4MGLQ6UP.js} +1 -1
- package/dist/{chunk-POPGX22M.js → chunk-5HDJT7E5.js} +1 -1
- package/dist/{chunk-ORIC64LN.js → chunk-5MX7OICH.js} +1 -1
- package/dist/{chunk-WU7M7ZZZ.js → chunk-64TKCCJF.js} +1 -1
- package/dist/{chunk-FOBN6LEV.js → chunk-6DE2YAGZ.js} +1 -1
- package/dist/{chunk-CNWG4S72.js → chunk-6OXRK7PK.js} +1 -1
- package/dist/{chunk-M5V62FLG.js → chunk-6TX2UFWN.js} +1 -1
- package/dist/{chunk-35CGFRWR.js → chunk-ANNZWFFN.js} +1 -1
- package/dist/chunk-C57G3LX4.js +1 -0
- package/dist/{chunk-HV7LI2JU.js → chunk-DRY3ZZCD.js} +1 -1
- package/dist/{chunk-46FG3J5X.js → chunk-EHWMZCNT.js} +1 -1
- package/dist/{chunk-2CK6XBGN.js → chunk-EU4XNTEE.js} +1 -1
- package/dist/chunk-FU4XNGGP.js +1 -0
- package/dist/chunk-FXKZJP4T.js +10 -0
- package/dist/{chunk-LS55FUZZ.js → chunk-FXRBRAJR.js} +1 -1
- package/dist/{chunk-BFU25JPT.js → chunk-FZSVLHCH.js} +2 -2
- package/dist/{chunk-QTVVVOJZ.js → chunk-G7QLMLCR.js} +1 -1
- package/dist/{chunk-YLZEADRF.js → chunk-GACCPVPU.js} +1 -1
- package/dist/{chunk-REPLGJ4W.js → chunk-HATZIRVQ.js} +1 -1
- package/dist/{chunk-5JUUTENA.js → chunk-JLDKGCU2.js} +1 -1
- package/dist/{chunk-NPFQD4WY.js → chunk-JR56NRGI.js} +1 -1
- package/dist/chunk-JT5RMCS6.js +1 -0
- package/dist/{chunk-XT25VURZ.js → chunk-K3GKANLZ.js} +1 -1
- package/dist/{chunk-O6ZYZM6E.js → chunk-K55XWFEI.js} +1 -1
- package/dist/{chunk-MJ5FVEM6.js → chunk-L5IBJODQ.js} +1 -1
- package/dist/{chunk-CEDCYLLH.js → chunk-MYYLRNLZ.js} +1 -1
- package/dist/{chunk-LN54XCEF.js → chunk-NSNEBNOM.js} +1 -1
- package/dist/{chunk-U63XQGMP.js → chunk-QPCIIQ6Q.js} +1 -1
- package/dist/{chunk-RYCZEVTK.js → chunk-RHARJTIX.js} +1 -1
- package/dist/{chunk-H3LTDAI5.js → chunk-RPN7SE4S.js} +1 -1
- package/dist/{chunk-GRC6NWQH.js → chunk-TQM2JVHJ.js} +1 -1
- package/dist/{chunk-DDAP4VXQ.js → chunk-UFEILUGE.js} +1 -1
- package/dist/{chunk-URSBR2ZU.js → chunk-UZAJOV75.js} +1 -1
- package/dist/{chunk-VSWF46OO.js → chunk-V6RXIFHI.js} +1 -1
- package/dist/{chunk-7AWA6PKI.js → chunk-WO6BLOJI.js} +1 -1
- package/dist/{chunk-T4UKYSRF.js → chunk-WWEHYERC.js} +1 -1
- package/dist/{chunk-VF6PR4HV.js → chunk-X3VCEYMU.js} +1 -1
- package/dist/{chunk-ASJZKRCY.js → chunk-X6IKITFV.js} +1 -1
- package/dist/{chunk-CETHPZ2K.js → chunk-XHJ33SCP.js} +1 -1
- package/dist/{chunk-NDXHLKAC.js → chunk-Y7CKOODV.js} +1 -1
- package/dist/{chunk-XPWU4XOF.js → chunk-ZQZFQHV4.js} +1 -1
- package/dist/content-KUCHBKX6.js +1 -0
- package/dist/funnel-host-purchase-WMAKTI2H.js +1 -0
- package/dist/{funnel-host-recovery-paywall-KRG22QX7.js → funnel-host-recovery-paywall-YMOYXK4D.js} +1 -1
- package/dist/{funnel-local-client-Cb9jJGpo.d.ts → funnel-local-client-2Yx0Q_lF.d.ts} +27 -0
- package/dist/{funnel-paywall-copies-RUUXK6MC.js → funnel-paywall-copies-WAX7Q2N4.js} +1 -1
- package/dist/funnel-paywall-prerender-U5BVF7QG.js +1 -0
- package/dist/{funnel-process-client-DE650LzB.d.ts → funnel-process-client-BTusJtqx.d.ts} +10 -1
- package/dist/funnel-route-prediction-EKSGU3ZG.js +1 -0
- package/dist/funnel-route-source-AV45OI6M.js +1 -0
- package/dist/funnel-runtime-host-SCBNV4VB.js +1 -0
- package/dist/index.d.ts +22 -6
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-LPMJFG7V.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-YFZHNHKS.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-BHPQH2ZJ.js +1 -0
- package/dist/paywall-content-WAUQRLBP.js +1 -0
- package/dist/paywall-session-I2YT3WUZ.js +1 -0
- package/dist/popup.d.ts +56 -3
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-B8W6a9WB.d.ts → presentation-loading-CU4c-koG.d.ts} +3 -1
- package/dist/react-native.d.ts +4 -4
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-4X5MLXGZ.js +1 -0
- package/dist/server.d.ts +20 -2
- package/dist/server.js +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-NKWICRAW.js +0 -1
- package/dist/chunk-65IMHQSS.js +0 -1
- package/dist/chunk-6E7CXGVN.js +0 -1
- package/dist/chunk-6FL4QVU5.js +0 -1
- package/dist/chunk-O7QCWT4T.js +0 -10
- package/dist/chunk-RWZZAFR7.js +0 -1
- package/dist/chunk-XQWYYXWZ.js +0 -1
- package/dist/content-JMJYZQAJ.js +0 -1
- package/dist/funnel-host-purchase-2T5X2VHD.js +0 -1
- package/dist/funnel-paywall-prerender-VDMHERHO.js +0 -1
- package/dist/funnel-route-prediction-UIF45MJM.js +0 -1
- package/dist/funnel-route-source-YLUKLBOY.js +0 -1
- package/dist/funnel-runtime-host-N75NI5NS.js +0 -1
- package/dist/merchant-bridge-contracts-SCRRFZIX.js +0 -1
- package/dist/operation-contracts-MBTMAKH2.js +0 -1
- package/dist/paywall-Z6F2GGOB.js +0 -1
- package/dist/paywall-content-SRZPUYGX.js +0 -1
- package/dist/paywall-session-MGNQ2JOG.js +0 -1
- package/dist/screen-renderer-POUJYMIZ.js +0 -1
- /package/dist/{chunk-BFU25JPT.js.LEGAL.txt → chunk-FZSVLHCH.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-HI6KTEQA.js → chunk-RTKI4V2J.js} +0 -0
|
@@ -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-QTVVVOJZ.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-F3WIZE6M.js";import{a as u,b as K,c as V,d as Y}from"./chunk-POPGX22M.js";import{e as X,f as R,g as z}from"./chunk-RYCZEVTK.js";import{b as t}from"./chunk-HI6KTEQA.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-G7QLMLCR.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-2UB5RFXZ.js";import{a as u,b as K,c as V,d as Y}from"./chunk-5HDJT7E5.js";import{e as X,f as R,g as z}from"./chunk-RHARJTIX.js";import{b as t}from"./chunk-RTKI4V2J.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 He}from"./chunk-2CK6XBGN.js";import{a as $}from"./chunk-OLRWD7DF.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-65IMHQSS.js";import{a as Ne,b as je,c as Ue}from"./chunk-WU7M7ZZZ.js";import{a as se}from"./chunk-U63XQGMP.js";import{i as ue}from"./chunk-LS55FUZZ.js";import{K as G}from"./chunk-O6ZYZM6E.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-7AWA6PKI.js";import{x as ye}from"./chunk-QTVVVOJZ.js";import{b as Ve}from"./chunk-CNWG4S72.js";import{a as l}from"./chunk-46FG3J5X.js";import{h as oe}from"./chunk-FOBN6LEV.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-HI6KTEQA.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-RUUXK6MC.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-SRZPUYGX.js"),import("./check-response-NKWICRAW.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
|
|
1
|
+
import{b as He}from"./chunk-EU4XNTEE.js";import{a as $}from"./chunk-3DW3Q6RU.js";import{D as K,F as Qe,c as Te,e as z,j as xe,u as Le,v as Me,x as Ge,z as ze}from"./chunk-FU4XNGGP.js";import{a as Ne,b as je,c as Ue}from"./chunk-64TKCCJF.js";import{a as se}from"./chunk-QPCIIQ6Q.js";import{i as ue}from"./chunk-FXRBRAJR.js";import{K as G}from"./chunk-K55XWFEI.js";import{A as ae,B as ie,C as J,E as Fe}from"./chunk-WO6BLOJI.js";import{x as ye}from"./chunk-G7QLMLCR.js";import{b as Ve}from"./chunk-6OXRK7PK.js";import{a as l}from"./chunk-EHWMZCNT.js";import{h as oe}from"./chunk-6DE2YAGZ.js";import{a as De}from"./chunk-5MRSFLQA.js";import{b as r}from"./chunk-RTKI4V2J.js";import{a as ge}from"./chunk-DSPLGTQI.js";var R=G.options,st=r.discriminatedUnion("operation",[R[1].omit({customerToken:!0}),R[2].omit({customerToken:!0}),R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0}),R[8].omit({customerToken:!0}),xe.omit({customerToken:!0})]),Pe=r.strictObject({receiptId:r.uuid(),operationId:r.uuid()}),yt=r.discriminatedUnion("operation",[r.strictObject({operation:r.literal("find_purchase")}),r.strictObject({operation:r.literal("recover_start"),intent:r.enum(["lookup","resume","start"]),start:r.strictObject({requestId:R[0].shape.requestId,funnelId:R[0].shape.funnelId,locale:R[0].shape.locale,parameters:R[0].shape.parameters})}),r.strictObject({operation:r.literal("recover_run"),runId:r.uuid(),funnelId:r.uuid()}),r.strictObject({operation:r.literal("recover_purchase"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe,includePaywallVersion:r.literal(!0).optional()}),r.strictObject({operation:r.literal("terminate_checkout"),runId:r.uuid(),funnelId:r.uuid(),purchase:Pe}),r.strictObject({operation:r.literal("settle_command"),runId:r.uuid(),funnelId:r.uuid(),requestId:r.uuid(),command:r.discriminatedUnion("operation",[R[3].omit({customerToken:!0}),R[4].omit({customerToken:!0}),R[5].omit({customerToken:!0}),R[6].omit({customerToken:!0}),R[7].omit({customerToken:!0})]).optional()}).refine(i=>!i.command||i.requestId===i.command.requestId),r.strictObject({operation:r.literal("run_command"),runId:r.uuid(),funnelId:r.uuid(),command:st})]),ce=r.strictObject({runId:r.uuid(),funnelId:r.uuid(),versionId:r.uuid(),startRequestId:r.uuid(),runExpiresAt:r.iso.datetime({offset:!0}),status:z.shape.run.shape.status}),H={scope:oe,customerId:r.uuid()},Be=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("unknown"),target:r.null(),view:r.null(),access:r.null()}),r.strictObject({...H,outcome:r.literal("resolved"),target:ce,view:z.shape.run.nullable(),access:r.discriminatedUnion("type",[r.strictObject({type:r.literal("customer")}),r.strictObject({type:r.literal("operation_only"),cause:r.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((i,d)=>{i.outcome==="resolved"&&(i.access.type==="customer"!=(i.view!==null)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Ye=r.strictObject({...H,target:ce,view:z.shape.run.nullable(),settlement:r.strictObject({requestId:r.uuid(),state:r.enum(["pending","unknown","settled"]),acceptance:r.enum(["accepted","not_accepted","unknown"]),receiptPhase:r.enum(["accepted","processing","done"]).nullable(),basis:r.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:r.uuid().nullable(),operationId:r.uuid().nullable()}),purchase:z.shape.purchase.unwrap().nullable()}).superRefine((i,d)=>{let f=i.settlement;(f.acceptance==="accepted"!=(f.receiptPhase!==null)||f.acceptance==="accepted"&&f.basis!=="receipt"||f.acceptance==="unknown"&&(f.state!=="unknown"||f.basis!=="none")||f.acceptance!=="accepted"&&(f.operationId!==null||f.receiptId!==null)||f.acceptance==="not_accepted"&&(f.state!=="settled"||!["run_terminal","position_advanced"].includes(f.basis))||i.purchase&&(i.purchase.receiptId!==f.receiptId||i.purchase.operation&&i.purchase.operation.operationId!==f.operationId||i.purchase.quote&&i.purchase.quote.operationId!==f.operationId)||i.view&&(i.view.id!==i.target.runId||i.view.source.id!==i.target.funnelId||i.view.source.versionId!==i.target.versionId||i.view.status!==i.target.status||i.view.runExpiresAt!==i.target.runExpiresAt||i.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Je=r.strictObject({...H,target:ce,purchase:z.shape.purchase.unwrap(),paywallVersionId:r.uuid().optional()}).superRefine((i,d)=>{(!i.purchase.operation||typeof i.purchase.canReselect!="boolean"||i.purchase.quote&&i.purchase.quote.operationId!==i.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ke=r.discriminatedUnion("outcome",[r.strictObject({...H,outcome:r.literal("none")}),r.strictObject({...H,outcome:r.literal("blocked")}),r.strictObject({...H,outcome:r.literal("found"),target:ce,start:r.strictObject({locale:R[0].shape.locale,parameters:R[0].shape.parameters}),purchase:Pe})]);var ut=G.options[0].refine(i=>!i.customer&&!i.customerData),ct=r.strictObject({receiptId:r.uuid(),operationId:r.uuid(),terminal:r.enum(["complete","native"]).nullable()}),$e=r.strictObject({schemaVersion:r.literal(1),baseUrl:r.url(),scope:oe,customerId:r.uuid(),sessionId:r.uuid(),start:ut,allowed:r.array(r.enum(["merchant","record_only","indiana","native"])),run:r.strictObject({id:r.uuid(),versionId:r.uuid(),status:Te.shape.status,revision:r.number().int().nonnegative(),runExpiresAt:r.iso.datetime({offset:!0}).optional()}).optional(),purchases:r.array(ct).max(100),operationCommand:r.strictObject({operationId:r.uuid(),intent:r.literal("confirm")}).optional(),journal:r.strictObject({revision:r.number().int().nonnegative(),entry:Le.nullable()})});function We(i){return Ge({...i,namespace:"purchases",identity:[i.scope.projectId,i.scope.environment,i.customerId]})}function Xe(i){let d=new URL(i.baseUrl??De).href,f=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){i.assertCurrent();try{let E=await i.storage.read();if(i.assertCurrent(),!Number.isSafeInteger(E.revision)||E.revision<0)throw f();let c=E.entry===null?null:$e.parse(E.entry);if(c&&(c.baseUrl!==d||c.customerId!==i.customerId||c.scope.projectId!==i.scope.projectId||c.scope.environment!==i.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(c?.journal.entry&&(c.journal.entry.scope.projectId!==c.scope.projectId||c.journal.entry.scope.environment!==c.scope.environment||c.journal.entry.funnelId!==c.start.funnelId||c.journal.entry.runId!==c.run?.id||c.journal.entry.versionId!==c.run?.versionId)||c?.operationCommand&&!c.purchases.some(k=>k.operationId===c.operationCommand?.operationId))throw f();return{revision:E.revision,entry:c}}catch(E){throw E instanceof l?E:f()}}async function W(E){for(let c=0;c<8;c++){let k=await S(),q=E(structuredClone(k.entry));if(JSON.stringify(q)===JSON.stringify(k.entry))return q;q&&$e.parse(q),i.assertCurrent();let j;try{j=await i.storage.write(k.revision,q)}catch{throw f()}if(i.assertCurrent(),j!==null){if(!Number.isSafeInteger(j)||j<=k.revision)throw f();return q}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:W,baseUrl:d}}var lt=5*6e4,dt=2e3;function pt(i,d){let f=i.purchases.find(S=>S.type==="checkout");if(!i.actions.includes("continue_checkout")||f?.type!=="checkout"||d!==void 0&&f.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return f.checkoutUrl}function Qt(i){let d={...i,scope:{...i.scope},executionPolicy:structuredClone(i.executionPolicy)},f=d.session.snapshot();if(!f)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:W}=f,E=!1,c=null,k,q,j=null,F=!1,U,X,Z,b={mode:"idle",status:"idle",actions:["start"],purchases:[]},g=new Map,ve=new Map,T=new Map,le=new AbortController,ee=new Set,Q=Ve(d),te=He(Q.request);function B(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function P(){if(E||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let w=Xe({...d,customerId:S,assertCurrent:P,storage:d.storage??We({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),Ze,Re=()=>Ze??=import("./funnel-paywall-copies-WAX7Q2N4.js").then(({createPaywallCopies:e})=>e({baseUrl:d.baseUrl,scope:d.scope,customerId:S})),et={read:async e=>(await Re()).read(e),write:async(e,t)=>(await Re()).write(e,t)},tt=d.session.subscribeIdentity(Se);function Se(){E||(E=!0,clearTimeout(Z),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),tt(),c?.reset(),c=null,j=null,Q.dispose(),ee.clear(),g.clear(),T.clear())}function v(e){P();let t=JSON.stringify(e)!==JSON.stringify(b);b=e,clearTimeout(Z),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Z=setTimeout(()=>{M().catch(()=>{})},5e3)),t&&ge(d.onRecovery,structuredClone(e));for(let n of t?ee:[]){if(E)break;ge(n,structuredClone(e))}return structuredClone(e)}function y(e){if(P(),!e||e.start.requestId!==q)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function Ce(e){return!e.run&&!O(e).length&&!e.journal.entry&&!e.operationCommand}function O(e){let t=[...e.purchases],n=e.journal.entry?.purchase;return n&&!t.some(o=>o.operationId===n.operationId)&&t.push({receiptId:n.receiptId,operationId:n.operationId,terminal:null}),t}function x(e){let t=O(e),n=F&&t.length>0&&t.every(o=>o.terminal==="native"&&D(g.get(o.operationId))==="native")&&t.some(o=>{let s=g.get(o.operationId);return!!s&&J(s)&&T.get(o.operationId)===!0});return e.run&&(n||!["running","waiting"].includes(e.run.status))&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&t.every(o=>o.terminal!==null)}function A(e,t){let n=e.journal.entry?.command??e.journal.entry?.closeCommand,o=O(e).map(I=>{let C=g.get(I.operationId);return I.terminal&&!C?{type:I.terminal,operationId:I.operationId}:se({quote:C?.quote??null,operation:C??null,requestId:n?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(I.operationId)===!0})}),s=o.filter(I=>!["complete","native"].includes(I.type)),u=s[0],a=s.length===1&&u?.operationId?g.get(u.operationId):void 0;if(a&&(u?.type==="checkout"||u?.type==="cancel"))try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote)}catch(I){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:B(I)}}let m;if(t==="operation"&&!n&&u?.type==="cancel"&&a?.quote&&!a.problem&&!a.confirmedAt)try{K({allowed:e.allowed.filter(I=>d.executionPolicy.allowed.includes(I))},a.quote),Date.parse(a.quote.expiresAt)>Date.now()&&(m={operationId:a.operationId,quote:a.quote})}catch{}let p=o.length>0&&s.length===0,h=x(e)||t==="operation"&&p&&!n&&!e.operationCommand?"complete":u?.type==="checkout"?"checkout":u?.type==="fulfillment"?"fulfillment":u?.type==="recording"?"recording":n||e.operationCommand||u&&u.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:h,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...x(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...s.length===1&&u?.type==="checkout"?["continue_checkout"]:[]]}}function D(e){let t=se({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function de(e){if(!e.operation)return;let t=ae.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let n=ue(g.get(t.operationId)??null,t);g.set(t.operationId,n),n===t&&T.set(t.operationId,e.canReselect===!0)}async function nt(e){P();for(let n of[e.purchase,e.run.paywall])n&&de(n);let t=await w.update(n=>{if(y(n),n.run&&(n.run.id!==e.run.id||n.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=O(n);for(let s of[e.purchase,e.run.paywall]){let u=s?.operation?.operationId??s?.quote?.operationId;if(!s||!u)continue;let a=o.find(p=>p.operationId===u);if(a&&a.receiptId!==s.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=D(g.get(u));a?a.terminal??=m:o.push({receiptId:s.receiptId,operationId:u,terminal:m})}return{...n,purchases:o,run:n.run&&(n.run.revision>e.run.revision||!["running","waiting"].includes(n.run.status)&&["running","waiting"].includes(e.run.status))?n.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});y(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(n=>!n.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(n=>!!n)))),y(t),v(A(t,"run"))}function rt(){return{async read(){let{entry:e}=await w.read();return y(e),structuredClone(e.journal)},async write(e,t){let n=null;return await w.update(o=>{if(y(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return n=null,o.journal.revision!==e?o:(n=e+1,{...o,journal:{revision:n,entry:t}})}),n}}}async function L(e,t=!1,n=new Set){y(e);let o=O(e);for(let u of o){if(u.terminal)continue;let a=n.has(u.operationId)?g.get(u.operationId):void 0;if(a??=await V(e,u),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(a.merchantExecution&&a.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&se({quote:a.quote??null,operation:a,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let m=J(a)?await te.update({operationId:u.operationId,intent:"cancel"}):await te.attach({operationId:u.operationId,intent:"cancel"});if(a=ae.parse(m.operation),P(),a.operationId!==u.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");a=await V(e,u)}g.set(u.operationId,ue(g.get(u.operationId)??null,a))}let s=await w.update(u=>{y(u);let a=u.operationCommand&&g.get(u.operationCommand.operationId);return{...u,...a&&(a.confirmedAt||a.merchantExecution||!Fe(a))?{operationCommand:void 0}:{},purchases:O(u).map(m=>({...m,terminal:m.terminal??D(g.get(m.operationId))}))}});return y(s),s}async function Y(e){P();let t=await Q.request("funnels",e);return P(),t}async function ot(e){try{return await Y(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return Y({...e,intent:"resume"})}}async function at(){let e=$(Ke,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:n}=e;return await w.update(o=>o&&!x(o)?o:{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...n,terminal:null}],journal:{revision:0,entry:null}}),"found"}let ne;function pe(e){let t=ne;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<lt))return t.job;let n={at:Date.now(),job:at().then(o=>(n.outcome=o,n.at=Date.now(),o),o=>{throw ne===n&&(ne=void 0),o})};return ne=n,n.job}async function V(e,t,n="recover_purchase",o=!1){let s=$(Je,await Y({operation:n,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId},...o?{includePaywallVersion:!0}:{}}));if(me(e,s),s.purchase.receiptId!==t.receiptId||s.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return de(s.purchase),o&&s.paywallVersionId&&ve.set(t.operationId,s.paywallVersionId),g.get(t.operationId)}async function Ee(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let n=$(Ye,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(me(e,n),n.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");n.purchase&&de(n.purchase);let o=await w.update(s=>{y(s);let u=O(s),{receiptId:a,operationId:m}=n.settlement;if(a&&m){let h=u.find(I=>I.operationId===m);if(h&&h.receiptId!==a)throw new l("INVALID_RESPONSE","Original Receipt changed");h||u.push({receiptId:a,operationId:m,terminal:D(g.get(m))})}let p=n.settlement.state==="settled"?Me(s.journal.entry,t.requestId):s.journal.entry;return{...s,purchases:u,journal:p===s.journal.entry?s.journal:{revision:s.journal.revision+1,entry:p}}});y(o),e=o}return e}function me(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function fe(e,t){if(y(e),e.run&&(e=await Ee(e)),!O(e).length&&x(e))return v(A(e,"operation"));if(!O(e).length)return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(t)});F=!0;let n=O(e);if(e.run&&["running","waiting"].includes(e.run.status)&&n.every(s=>s.terminal==="native"))for(let s of n)D(g.get(s.operationId))!=="native"&&await V(e,s);let o=await L(e);return v(A(o,"operation"))}async function re(e,t=!1,n=!0,o=!1){if(q=e.start.requestId,j=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!c){let s=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ot(s)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:B(h)});throw h}let a=$(Be,u);if(a.customerId!==S||a.scope.projectId!==d.scope.projectId||a.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(a.outcome==="unknown"){if(!t&&Ce(e)){let h=e.start.requestId;if(!await w.update(C=>C&&C.start.requestId===h&&Ce(C)?null:C))return v({mode:"idle",status:"idle",actions:["start"],purchases:[]})}return v({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:b.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}})}me(e,a);let m=await w.update(h=>(y(h),{...h,run:{id:a.target.runId,versionId:a.target.versionId,status:a.target.status,revision:a.view?.revision??h.run?.revision??0,runExpiresAt:a.target.runExpiresAt}}));if(y(m),e=m,a.access.type==="operation_only")return fe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ee(e);let p=a.view;if(p.locale!==e.start.locale||!ze(p.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");c=Qe({...d,customerRun:{runId:a.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:rt(),onAcceptedResponse:nt},{scope:a.scope,run:p})}try{let s=o&&k?.controller===c?performance.now()-k.at:1/0;(s>=dt||c.pendingCommands?.length||(c.viewAgeMs??0)<s)&&(k=void 0,await c.get(),k={controller:c,at:performance.now()}),c.view?.pendingRequest?.requestId===e.start.requestId&&!c.pendingCommands?.length&&await c.resume(c.view.pendingRequest.requestId);for(let a of c.pendingCommands??[])a.operation!=="close"&&await c.settle?.(a.requestId);c.pendingCommands?.length&&await c.retry(),P();let u=(await w.read()).entry;return y(u),v(A(u,"run"))}catch(s){if(P(),n&&s instanceof l&&(s.status===401||s.status===409&&s.reason==="STATE_CHANGED")){c.reset(),c=null;let u=(await w.read()).entry;return y(u),re(u,!1,!1,!1)}throw s}}function N(e,t="read",n){if(P(),U)return t==="read"||t===X?U:U.then(()=>N(e,t,n),()=>N(e,t,n));clearTimeout(Z);let o=e().catch(s=>{throw!E&&!n?.(s)&&v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:b.purchases,error:B(s)}),s});return U=o,X=t,o.then(()=>{U===o&&(U=void 0,X=void 0)},()=>{U===o&&(U=void 0,X=void 0)}),o}function M(e){let t=e?.reuseRecentRead===!0;return N(async()=>{let{entry:n}=await w.read();if(!n||x(n)){if(await pe(!1)==="blocked")return be();({entry:n}=await w.read())}return n?(q&&n.start.requestId!==q&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F&&q===n.start.requestId?fe(n,b.error):re(n,!1,!0,t)):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function be(){return v({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:B(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function Oe(){let e=await M();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:N(async()=>{let t=(await w.read()).entry;if(y(t),!F){if(!c?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=c.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(J(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return v(A(t,"run"));if(c.pendingCommands?.length)await c.retry();else{let I=c.view;await c.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:I.nodeId,visit:I.visit,revision:I.revision,input:{type:"paywall_confirm",operationId:I.paywall.quote.operationId,...I.paywall.quote.merchantTerms?{merchantConfirmation:ye(I.paywall.quote.merchantTerms)}:{}}})}let h=(await w.read()).entry;return y(h),v(A(h,"run"))}let n=t.operationCommand?.operationId??b.confirmation?.operationId,o=n&&g.get(n);if(!n||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");K({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await w.update(p=>{if(y(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==n)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:n,intent:"confirm"}}});let s={operationId:n,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:ye(o.quote.merchantTerms)}:{}},u=J(o)?await te.update(s):await te.attach(s),a=ae.parse(u.operation);if(P(),u.operation.operationId!==n)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");g.set(n,ue(o,a));let m=(await w.read()).entry;return y(m),v(A(await L(m,!1,new Set([n])),"operation"))},"confirm")}function it(e){let t=e?.quote;return t&&ie(t)&&t.timing==="immediate"&&t.execution.provider==="merchant"&&(e.confirmedAt||e.merchantExecution)?t:null}function _e(){if(b.mode!=="operation"||b.status==="blocked")return null;let e=b.purchases.filter(({type:n})=>n!=="complete"&&n!=="native"),t=e.length===1&&e[0]?.operationId;return t?it(g.get(t)):null}async function qe(){P();let{entry:e}=await w.read();return e?x(e)?"finished":"pending":"none"}return{get controller(){return c},get recovery(){return structuredClone(b)},get attempt(){return P(),structuredClone(j)},get identitySignal(){return le.signal},get customerId(){return S},retained:qe,get paywallCopies(){return et},async findPurchase(){let e=await qe();if(e==="pending")return e;let t=await pe(!0);return P(),t==="none"?e:t},async readPaywall(e){P();let t=Ne(e),[n,{readPaywallContent:o},{validateResourceCheck:s}]=await Promise.all([je(Q.request,"resolvePaywall"),import("./paywall-content-WAUQRLBP.js"),import("./check-response-FTYRCENP.js")]);P();let u=n.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),a=await Ue(Q.request,n,u);s(u,a.paywall.check,a.scope);let m=await o(d,a.paywall);if(P(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},get canRestoreUpgradePaywall(){return _e()!==null},recoverUpgradePaywall(){let e=_e();return e?this.recoverPurchasePaywall(void 0,e.operationId):Promise.resolve(null)},async recoverPurchasePaywall(e,t){if(b.mode!=="operation"||b.status==="blocked")return null;let{entry:n}=await w.read();if(!n?.run)return null;y(n);let o=O(n),s=o.filter(_=>!_.terminal),u=o.filter(_=>_.terminal==="complete"),a=s.length===1?s[0]:s.length?void 0:u.find(_=>e&&e.runId===n.run?.id&&_.receiptId===e.receiptId)??(u.length===1?u[0]:void 0);if(!a||t&&a.operationId!==t)return null;let m=e?.runId===n.run.id&&e.receiptId===a.receiptId?e.view:void 0,p;try{p=await V(n,a,"recover_purchase",!0)}catch(_){if(!(_ instanceof l&&_.status===400&&_.code==="INVALID_REQUEST"))throw _;if(!m)return null;p=await V(n,a)}let h=p.quote;if(!h||ie(h)&&(h.timing!=="immediate"||h.execution.provider!=="merchant")||!(p.confirmedAt||p.merchantExecution||p.checkoutUrl||D(p)==="complete"))return null;D(p)!=="complete"&&K({allowed:n.allowed.filter(_=>d.executionPolicy.allowed.includes(_))},h);let I=ve.get(a.operationId),C=n.start.parameters?.commerce,ke=n.start.locale??"en",he=m;if(I){if(typeof C!="object"||!C||!("provider"in C)||typeof C.provider!="string"||!("currency"in C)||typeof C.currency!="string")return null;he=await this.readPaywall({paywallVersionId:I,locale:ke,commerce:{provider:C.provider,currency:C.currency,...ie(h)?{intent:"subscription_change"}:{}}})}if(!he)return null;P();let Ae=he,we=!1,Ie=async()=>{throw new l("PURCHASE_PENDING","Only the original purchase can be recovered")};return{signal:le.signal,view:Ae,quote:h,locale:ke,get operation(){return p},get canReselect(){return T.get(a.operationId)===!0},async refresh(){return Ae},preview:Ie,confirm:Ie,cancel:Ie,async read(){if(we)throw new DOMException("Purchase view closed","AbortError");p=await V(n,a);let _=await L(n,!1,new Set([a.operationId]));return we||v(A(_,"operation")),structuredClone(p)},destroy(){we=!0}}},start(e){let t=G.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return N(async()=>{let n=(await w.read()).entry;if((!n||x(n))&&await pe(!0)==="blocked")return be();let o=await w.update(s=>{if(s&&!x(s)){if(s.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return s}return{schemaVersion:1,baseUrl:w.baseUrl,scope:d.scope,customerId:S,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return q!==o.start.requestId&&(c?.reset(),c=null,g.clear(),T.clear(),F=!1),F?fe(o,b.error):re(o,!0,!0,!0)},`start:${t.funnelId}`)},refresh:M,confirm:Oe,retry:()=>F?Oe():N(async()=>{let{entry:e}=await w.read();return e?re(e,!0):v({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return c?.view?N(async()=>{if(!c?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(c.pendingCommands?.find(n=>n.operation==="close"))await c.retry();else if(["running","waiting"].includes(c.view.status)){let n=c.view;await c.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision})}let t=(await w.read()).entry;return y(t),v(A(t,"run"))},"close"):M()},async continueCheckout(e,t){let n=t?await N(async()=>{let{entry:o}=await w.read();if(y(o),!o.run||!O(o).some(u=>u.operationId===t&&!u.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let s=await L(o);return v(A(s,F?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await M();P(),await e(pt(n,t))},async terminateCheckout(e){let t=await M();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return N(async()=>{let{entry:o}=await w.read();y(o);let s=O(o).find(a=>a.operationId===e&&!a.terminal);if(!s||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await V(o,s,"terminate_checkout");let u=await L(o,!1,new Set([e]));return v(A(u,F?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return ee.add(e),()=>{ee.delete(e)}},destroy:Se}}export{We as a,pt as b,Qt as c};
|