@tinkerlandai/longplay-sdk 0.10.55 → 0.10.57
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/dist/check-response-MJHH5FWT.js +1 -0
- package/dist/{chunk-6P3WCGPY.js → chunk-2NIMTHN7.js} +1 -1
- package/dist/{chunk-7L6F7FSH.js → chunk-2OBAMFGZ.js} +1 -1
- package/dist/{chunk-3NWMQ33E.js → chunk-36VNAOG6.js} +1 -1
- package/dist/{chunk-GLIZTWEO.js → chunk-3LDOPWRV.js} +1 -1
- package/dist/{chunk-LKZELSFX.js → chunk-554BTJ3I.js} +1 -1
- package/dist/{chunk-MEOMDJZI.js → chunk-5HYA7TBE.js} +1 -1
- package/dist/{chunk-UCYTLZPQ.js → chunk-5UVYLTM7.js} +1 -1
- package/dist/{chunk-4AXCP6YL.js → chunk-6HKQILBV.js} +1 -1
- package/dist/{chunk-DN4OYE4E.js → chunk-6K6N5XLO.js} +1 -1
- package/dist/{chunk-7MXSO2FW.js → chunk-725DCRIN.js} +1 -1
- package/dist/{chunk-3HT7SVBF.js → chunk-73UFNVEP.js} +1 -1
- package/dist/{chunk-QK2Y2ZEZ.js → chunk-ADTZEBQF.js} +1 -1
- package/dist/chunk-AJVVXHP7.js +1 -0
- package/dist/{chunk-ET6CBBLH.js → chunk-ANJPFGFN.js} +1 -1
- package/dist/{chunk-MSM3WAM5.js → chunk-BKBWGPNR.js} +1 -1
- package/dist/{chunk-VKY4K4KH.js → chunk-BX2MSRA4.js} +1 -1
- package/dist/{chunk-RG2JNNXL.js → chunk-C4NXQMSO.js} +1 -1
- package/dist/{chunk-GTMK4JF3.js → chunk-CAE4KIZN.js} +1 -1
- package/dist/{chunk-XRNBVBAA.js → chunk-CJUODAOF.js} +1 -1
- package/dist/{chunk-3QWERHSB.js → chunk-DHFJN4JM.js} +2 -2
- package/dist/{chunk-RSG74B3M.js → chunk-EACC667P.js} +1 -1
- package/dist/{chunk-ESQVXEKB.js → chunk-FQJWNS4U.js} +1 -1
- package/dist/{chunk-RSO5KO7S.js → chunk-GGZG56GR.js} +1 -1
- package/dist/{chunk-JDGH5QJP.js → chunk-HMJTABQ5.js} +2 -2
- package/dist/{chunk-J4GRBKUH.js → chunk-IN32NWRI.js} +1 -1
- package/dist/{chunk-UHPMOLMW.js → chunk-J4RM5GQP.js} +1 -1
- package/dist/{chunk-OO2GQESM.js → chunk-JJIP6BZL.js} +1 -1
- package/dist/{chunk-3BZTDD2U.js → chunk-JXWZS4UM.js} +1 -1
- package/dist/{chunk-IVWTAVT3.js → chunk-L64BS65O.js} +1 -1
- package/dist/{chunk-LNWK2TH6.js → chunk-LENTXDGK.js} +1 -1
- package/dist/{chunk-HXDNGCPJ.js → chunk-LOBZ45T3.js} +1 -1
- package/dist/{chunk-AZKU5JQD.js → chunk-LOKH33KR.js} +1 -1
- package/dist/{chunk-7IHAPLCS.js → chunk-M4P6TGBU.js} +1 -1
- package/dist/{chunk-5ZTKQAJV.js → chunk-NL7AXMUA.js} +1 -1
- package/dist/{chunk-M774BXNR.js → chunk-NMBKBC7X.js} +1 -1
- package/dist/{chunk-IZTD33WJ.js → chunk-NNJVMJUG.js} +1 -1
- package/dist/{chunk-HI6Y7XJ2.js → chunk-OQ2E3JLZ.js} +1 -1
- package/dist/{chunk-QYEQNDQD.js → chunk-OV46DXRX.js} +1 -1
- package/dist/{chunk-DNQLSWIX.js → chunk-OZK47BUU.js} +1 -1
- package/dist/{chunk-MKMYNK4K.js → chunk-PVMGYRGE.js} +1 -1
- package/dist/{chunk-RVBX3X7P.js → chunk-QGKROSRD.js} +1 -1
- package/dist/{chunk-VBX3OPEE.js → chunk-R4BYUK7S.js} +1 -1
- package/dist/{chunk-5ONJ4ZQH.js → chunk-RJT764B2.js} +1 -1
- package/dist/{chunk-GP7T4WEY.js → chunk-RRZZUIFM.js} +1 -1
- package/dist/chunk-UJVNIA5Q.js +1 -0
- package/dist/{chunk-KDHWO4RP.js → chunk-UWMXBSYO.js} +1 -1
- package/dist/{chunk-TZ4IC4US.js → chunk-WE55LJEN.js} +1 -1
- package/dist/{chunk-KJTRF35F.js → chunk-XHZH3E4G.js} +1 -1
- package/dist/{chunk-JPPEUS4P.js → chunk-YA2XHXUS.js} +1 -1
- package/dist/{chunk-5NVSHZHH.js → chunk-YMRWDMIL.js} +1 -1
- package/dist/{content-PZUD5TVQ.js → content-3MNGXC7L.js} +1 -1
- package/dist/{funnel-host-purchase-Q6P2YDVI.js → funnel-host-purchase-H6BMFIXK.js} +1 -1
- package/dist/{funnel-host-recovery-paywall-5EQRYS7M.js → funnel-host-recovery-paywall-UQC5FAL4.js} +1 -1
- package/dist/funnel-paywall-prerender-XBEUY6CG.js +1 -0
- package/dist/funnel-route-prediction-ICGW4DPX.js +1 -0
- package/dist/funnel-route-source-64LTJZXN.js +1 -0
- package/dist/funnel-runtime-host-HEBLLPFC.js +1 -0
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-DEDEIYNU.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-RHJJI5NO.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-HZVO7BDI.js +1 -0
- package/dist/paywall-content-KBHI22JD.js +1 -0
- package/dist/paywall-session-TS7G7OEM.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-XBWES3XN.js +1 -0
- package/dist/server.js +1 -1
- package/dist/{visual-dom-EG5K4MQZ.js → visual-dom-MH3JDJHJ.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/check-response-SGAJJZM3.js +0 -1
- package/dist/chunk-JO27764K.js +0 -1
- package/dist/chunk-XHKGJGCZ.js +0 -1
- package/dist/funnel-paywall-prerender-T4BYKZCR.js +0 -1
- package/dist/funnel-route-prediction-GIG2G525.js +0 -1
- package/dist/funnel-route-source-HXE7AGDB.js +0 -1
- package/dist/funnel-runtime-host-UFKTZW2N.js +0 -1
- package/dist/merchant-bridge-contracts-A3HCEH4C.js +0 -1
- package/dist/operation-contracts-5YSN3IKV.js +0 -1
- package/dist/paywall-XR5QXRMH.js +0 -1
- package/dist/paywall-content-UASETG4Y.js +0 -1
- package/dist/paywall-session-FH7UX2GO.js +0 -1
- package/dist/screen-renderer-4OBUAKRB.js +0 -1
- /package/dist/{chunk-ADCYMD2M.js → chunk-5YBTU4KS.js} +0 -0
- /package/dist/{chunk-3QWERHSB.js.LEGAL.txt → chunk-DHFJN4JM.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-NCKIG4QS.js → chunk-DLRCJF6U.js} +0 -0
- /package/dist/{chunk-JDGH5QJP.js.LEGAL.txt → chunk-HMJTABQ5.js.LEGAL.txt} +0 -0
- /package/dist/{chunk-AZKM26EX.js → chunk-VJIONC4S.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as K,b as U,d as D,v as _}from"./chunk-GP7T4WEY.js";import{a as z,c as F}from"./chunk-5ONJ4ZQH.js";import{d as $}from"./chunk-IZTD33WJ.js";import{i as C,j as m,l as O,m as g}from"./chunk-DNQLSWIX.js";import{b as e}from"./chunk-ADCYMD2M.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
|
|
1
|
+
import{C as K,b as U,d as D,v as _}from"./chunk-RRZZUIFM.js";import{a as z,c as F}from"./chunk-RJT764B2.js";import{d as $}from"./chunk-NNJVMJUG.js";import{i as C,j as m,l as O,m as g}from"./chunk-OZK47BUU.js";import{b as e}from"./chunk-5YBTU4KS.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" · 一次付款":" · one-time";let u=n.split("-")[0]??"en",a={zh:["/月","/年"],en:["/month","/year"],ja:["/月","/年"],ko:["/월","/년"],es:["/mes","/año"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/mês","/ano"],it:["/mese","/anno"],ar:["/شهر","/سنة"]},s={zh:"周",en:"week",ja:"週",ko:"주",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"أسبوع"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as h}from"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-LOBZ45T3.js";import{a as b,c as w,l as x,m as O}from"./chunk-J4RM5GQP.js";import{a as I}from"./chunk-VILB5M4X.js";import{b as y,f as g,g as v}from"./chunk-NNJVMJUG.js";import{b as t}from"./chunk-5YBTU4KS.js";var d=O,R=t.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),j=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([e,r])=>e<=r),F=t.strictObject({seed:t.string().min(1).max(255),variations:t.array(R).min(2).max(20),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),ranges:t.array(j).max(20).optional(),filters:t.array(t.strictObject({seed:t.string().min(1).max(255),ranges:t.array(j).max(100)})).max(100).optional(),passthrough:t.array(t.number().int().min(0).max(19)).max(20).optional(),condition:g.optional(),active:t.literal(!1).optional(),force:t.number().int().min(-1).max(19).optional()}),_=t.discriminatedUnion("type",[t.strictObject({type:t.literal("pass"),next:d}),t.strictObject({type:t.literal("condition"),cases:t.array(t.strictObject({condition:g,target:d})).min(1).max(50),default:d}),t.strictObject({type:t.literal("split"),experimentId:t.uuid(),bucketing:F,routes:t.record(R,d).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:d}),t.strictObject({type:t.literal("paywall"),paywallId:t.uuid(),paywallVersionId:t.uuid(),presentation:y}),t.strictObject({type:t.literal("screen"),surface:t.enum(["page","popup","onboarding"]),presentation:y}),t.strictObject({type:t.literal("external_page")}),t.strictObject({type:t.literal("end"),outcome:t.enum(["completed","closed","ineligible","failed"])}),t.strictObject({type:t.literal("server"),reason:t.enum(["action","wait","feature","condition","experiment","resource"])})]),P={nodes:500,maxBytes:262144},S=t.strictObject({kind:t.literal("funnel_route"),formatVersion:t.literal(1),funnelId:t.uuid(),versionId:t.uuid(),entry:d,maxTransitions:t.number().int().min(1).max(1e4),variables:t.record(b,w),nodes:t.record(d,_)}).superRefine((e,r)=>{let s=a=>r.addIssue({code:"custom",message:a});Object.keys(e.nodes).length>P.nodes&&s("Too many route nodes"),Object.hasOwn(e.nodes,e.entry)||s("Route entry is missing");for(let a of Object.values(e.variables))["parameter","input"].includes(a.source.type)||s("Only start parameters and inputs can be public");for(let a of Object.values(e.nodes)){for(let c of V(a))Object.hasOwn(e.nodes,c)||s("Route target is missing");a.type==="split"&&a.bucketing.variations.some(c=>!Object.hasOwn(a.routes,c))&&s("Every Variation needs a route")}});function V(e){switch(e.type){case"pass":return[e.next];case"condition":return[...e.cases.map(r=>r.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];default:return[]}}function E(e,r,s=[]){if(e==="id")return!0;if(!e.startsWith("variables."))return!1;let a=e.slice(10),c=i=>a===i||a.startsWith(`${i}.`)||i.startsWith(`${a}.`);return r.some(i=>a===i||a.startsWith(`${i}.`))&&!s.some(c)}function m(e,r,s=[]){return v(e).length===0&&I(e).every(a=>E(a,r,s))}function W(e){let{document:r}=e,s={},a=[];for(let[n,o]of Object.entries(r.variables))["parameter","input"].includes(o.source.type)?s[n]=o:a.push(n);let c=Object.keys(s),i=new Map(r.graph.nodes.map(n=>[n.id,n])),l={},u=[r.graph.entry],f=n=>{switch(n.type){case"entry":case"offering":case"coupon":case"coupons":return{type:"pass",next:n.next};case"condition":return n.cases.every(o=>m(o.condition,c,a))?{type:"condition",cases:n.cases.map(o=>({condition:o.condition,target:o.target})),default:n.default}:{type:"server",reason:"condition"};case"split":{let o=N(Object.hasOwn(e.experiments,n.experimentId)?e.experiments[n.experimentId]:void 0,n.routes,c,a);return o?{type:"split",experimentId:n.experimentId,bucketing:o,routes:{...n.routes},notParticipating:n.notParticipating}:{type:"server",reason:"experiment"}}case"screen":{let o=r.screens.find(p=>p.id===n.screenId);if(o?.type==="paywall"){let p=e.paywallOf(o.paywallVersionId);return p?{type:"paywall",paywallId:p,paywallVersionId:o.paywallVersionId,presentation:n.presentation}:{type:"server",reason:"resource"}}return o?.type==="owned"?{type:"screen",surface:o.document.surface,presentation:n.presentation}:{type:"server",reason:"resource"}}case"external_page":return{type:"external_page"};case"end":return{type:"end",outcome:n.outcome};case"output":return{type:"end",outcome:"completed"};case"feature":return{type:"server",reason:"feature"};case"action":return{type:"server",reason:"action"};case"wait":return{type:"server",reason:"wait"}}};for(;u.length;){let n=u.shift();if(Object.hasOwn(l,n))continue;let o=i.get(n);if(!o)throw new Error("Funnel route target is missing");let p=f(o);l[n]=p,u.push(...V(p))}return S.parse({kind:"funnel_route",formatVersion:1,funnelId:e.funnelId,versionId:e.versionId,entry:r.graph.entry,maxTransitions:r.execution.maxTransitions,variables:s,nodes:l})}function N(e,r,s,a){if(!e||(e.hashAttribute??"id")!=="id"||e.fallbackAttribute||e.parentConditions?.length||e.urlPatterns?.length||(e.hashVersion??2)!==2||(e.filters??[]).some(i=>(i.attribute??"id")!=="id")||e.condition&&!m(e.condition,s,a)||e.variations.some(i=>typeof i!="string"||!Object.hasOwn(r,i)))return;let c=(e.meta??[]).flatMap((i,l)=>i.passthrough?[l]:[]);return F.parse({seed:e.seed??e.key,variations:e.variations,...e.weights?{weights:e.weights}:{},...e.coverage!==void 0?{coverage:e.coverage}:{},...e.ranges?{ranges:e.ranges}:{},...e.filters?.length?{filters:e.filters.map(i=>({seed:i.seed,ranges:i.ranges}))}:{},...c.length?{passthrough:c}:{},...e.condition?{condition:e.condition}:{},...e.active===!1?{active:!1}:{},...e.force!==void 0?{force:e.force}:{}})}function G(e,r){return{key:e,seed:r.seed,hashAttribute:"id",hashVersion:2,variations:r.variations,...r.weights?{weights:r.weights}:{},...r.coverage!==void 0?{coverage:r.coverage}:{},...r.ranges?{ranges:r.ranges}:{},...r.filters?{filters:r.filters.map(s=>({attribute:"id",seed:s.seed,hashVersion:2,ranges:s.ranges}))}:{},...r.passthrough?{meta:r.variations.map((s,a)=>({passthrough:r.passthrough.includes(a)}))}:{},...r.condition?{condition:r.condition}:{},...r.active===!1?{active:!1}:{},...r.force!==void 0?{force:r.force}:{}}}function $(e,r){let s=[],a={versionId:e.versionId,path:s},c=f=>({...a,type:"unknown",reason:f}),i;try{i=x({declarations:e.variables,answers:{},parameters:r.parameters,attributes:{id:r.customerId},savedGroups:{},results:{}})}catch{return c("invalid_parameters")}let l=Object.keys(e.variables),u=e.entry;for(let f=0;;f++){let n=e.nodes[u];switch(s.push(u),n.type){case"paywall":return{...a,type:"paywall",paywallId:n.paywallId,paywallVersionId:n.paywallVersionId,presentation:n.presentation};case"screen":return{...a,type:"screen",surface:n.surface,presentation:n.presentation};case"external_page":return{...a,type:"external_page"};case"end":return{...a,type:"end",outcome:n.outcome};case"server":return c("server_step")}if(f>=e.maxTransitions)return c("transition_limit");if(n.type==="pass"){u=n.next;continue}if(n.type==="condition"){if(!n.cases.every(o=>m(o.condition,l)))return c("server_attribute");u=h({id:u,name:u,type:"condition",cases:n.cases,default:n.default},{attributes:i,savedGroups:{}},{}).target;continue}if(n.bucketing.condition&&!m(n.bucketing.condition,l))return c("server_attribute");u=h({id:u,name:u,type:"split",experimentId:n.experimentId,routes:n.routes,notParticipating:n.notParticipating},{attributes:i,savedGroups:{}},{[n.experimentId]:G(n.experimentId,n.bucketing)}).target}}export{P as a,S as b,W as c,$ as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as c,c as u}from"./chunk-
|
|
1
|
+
import{a as s,b as c,c as u}from"./chunk-BKBWGPNR.js";import{j as m,m as p}from"./chunk-OZK47BUU.js";import{b as e}from"./chunk-5YBTU4KS.js";var y=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],i=e.enum(y);function x(t){let n=i.parse(t.toUpperCase());return["JPY","KRW","VND"].includes(n)?0:2}function I(t,n,r="en",f={}){let a=i.parse(n.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...f}).format(t/10**x(a))}var l=e.enum(["stripe","apple","google","merchant"]),w=e.enum(["membership","credit_pack","lifetime"]),v=e.enum(["active","grace","suspended","inactive","revoked"]),z=e.strictObject({currency:e.string().regex(/^[A-Z]{3}$/),micros:e.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var d=e.object({provider:l,currency:i,intent:e.literal("subscription_change").optional()}).strict();var o=e.strictObject({internal_feature_id:e.uuid(),quantity:m.refine(t=>/[1-9]/.test(t)),properties:p,entityId:e.uuid().optional()}),B=e.strictObject({requirement:o,commerce:d.optional(),paywallId:e.uuid().optional()}),g=e.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),b=e.strictObject({productId:e.string().min(1),productVersionId:e.string().min(1),name:e.string().min(1).max(120),action:e.enum(["purchase","upgrade","addon","topup"]),membershipId:e.string().min(1).nullable(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional(),currency:i,amountMinor:e.string().regex(/^(0|[1-9]\d{0,8})$/),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(156)}),h=e.strictObject({subject:c,authority:e.enum(["longplay","merchant"]),observedAt:e.iso.datetime({offset:!0}),sourceRevision:e.string().min(1).max(128),requirementDigest:s});function S(t,n){return u({subject:c.parse(t),requirement:o.parse(n)})}var C=e.strictObject({internal_feature_id:e.string().min(1),name:e.string().min(1).max(120),kind:e.enum(["access","metered","credit"]),quantity:m,allowed:e.boolean(),observation:h.optional(),reason:g.nullable(),preview:e.strictObject({scenario:e.enum(["feature_flag","usage_limit"]),candidates:e.array(b).max(20)}).nullable()}).superRefine((t,n)=>{(t.allowed!==(t.reason===null)||t.allowed&&t.preview!==null||new Set(t.preview?.candidates.map(r=>r.productVersionId)).size!==(t.preview?.candidates.length??0)||t.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&n.addIssue({code:"custom",message:"Invalid access recommendation"})}),T=e.strictObject({paywallId:e.uuid(),requirement:o}),U=e.strictObject({subject:c,requirement:o}),$=C.safeExtend({observation:h.extend({authority:e.literal("merchant")})});function F(t,n){let r=o.parse(t);return n.internal_feature_id===r.internal_feature_id&&n.quantity===r.quantity&&(!n.observation||n.observation.requirementDigest===S(n.observation.subject,r))}export{i as a,x as b,I as c,w as d,d as e,o as f,B as g,b as h,S as i,C as j,U as k,$ as l,F as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as C,j as J}from"./chunk-5ONJ4ZQH.js";import{b as X}from"./chunk-IZTD33WJ.js";import{j as K,l as E}from"./chunk-DNQLSWIX.js";import{b as e}from"./chunk-ADCYMD2M.js";var Y=e.number().int().min(0).max(1e8),V=e.strictObject({kind:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Y,flatAmountMinor:Y.optional()})).min(1).max(12)}).refine(t=>t.tiers.at(-1)?.upTo===null&&t.tiers.slice(0,-1).every((n,i)=>{let r=t.tiers[i-1]?.upTo;return n.upTo!==null&&(i===0||r!=null&&n.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(t=>!t.tiers.some(n=>(n.flatAmountMinor??0)>0)||t.kind==="volume"&&t.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function M(t,n){if(!Number.isInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased pack quantity");let i=t.pricing?V.parse(t.pricing):void 0;if(n===0)return 0;let r=0n,o=0;if(!i)r=BigInt(t.amountMinor)*BigInt(n);else for(let a of i.tiers){let s=a.upTo??1e4;if(i.kind==="volume"){if(n<=s){r=BigInt(n)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else n>o&&(r+=BigInt(Math.min(n,s)-o)*BigInt(a.unitAmountMinor));o=s}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function wt(t){return M({amountMinor:t.unitAmountMinor,...t.pricing?{pricing:t.pricing}:{}},t.quantity)}var ve=K.refine(t=>/[1-9]/.test(t)),te=e.strictObject({units:ve,prices:e.array(e.strictObject({currency:C,amountMinor:e.number().int().min(0).max(1e8),pricing:V.optional()})).min(1).max(20).refine(t=>new Set(t.map(n=>n.currency)).size===t.length,"Currencies must be unique").refine(t=>t.every(n=>!n.pricing||n.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:e.number().int().min(0).max(1e4),maximumQuantity:e.number().int().min(0).max(1e4)}).refine(t=>t.maximumQuantity>=t.minimumQuantity,"Purchased quantity must fit its published bounds").refine(t=>{try{for(let n of t.prices)for(let i of[t.maximumQuantity,...n.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])i<=t.maximumQuantity&&M({amountMinor:n.amountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}},i);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function ee(t){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(t))throw new Error("Invalid quantity");let[n,i=""]=t.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*1000000n+BigInt(i.padEnd(6,"0"))}function Ot(t,n,i){if(!Number.isSafeInteger(i)||i<0||i>1e4)throw new Error("Invalid purchased quantity");let r=ee(t)+ee(n)*BigInt(i);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(o?"."+o:"")}var ne=e.strictObject({internalFeatureId:e.uuid(),name:e.string().min(1).max(120),includedAmount:e.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:e.enum(["hour","day","week","month","year","lifetime"]),resetCount:e.number().int().min(1).max(100),terms:te});var _e=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],T=e.object({plan:e.string().min(1).max(200).optional(),coupon:e.uuid().optional(),promotionCode:e.uuid().optional(),picker:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),re=e.object({text:e.string().optional(),label:e.string().optional(),alt:e.string().optional(),html:e.string().max(32768).optional(),price:e.object({current:e.string(),original:e.string().nullable(),period:e.string()}).optional(),code:e.string().optional(),countdownAt:e.iso.datetime().optional(),planId:e.string().min(1).max(200).optional(),planVersionId:e.string().min(1).max(200).optional(),currency:C.optional(),couponId:e.uuid().optional(),offerId:e.uuid().optional(),unavailable:e.boolean().optional(),unavailableReason:e.string().optional(),missing:e.array(e.string()).optional()}).strict(),Et=e.object({paywall:J.optional(),nodes:e.record(e.string(),e.object({base:re,picker:e.string().optional(),byPlan:e.record(e.string(),re).optional()}).strict()),plans:e.record(e.string(),e.object({id:e.string().min(1).max(200),versionId:e.string().min(1).max(200),available:e.boolean(),name:e.string(),price:e.string(),period:e.string(),currency:C.optional(),amountMinor:e.number().int().nonnegative().optional(),interval:e.enum(["free","week","month","year","one_time"]).optional(),intervalCount:e.number().int().positive().optional(),prepaid:e.array(ne).max(100).optional()}).strict()),pickers:e.record(e.string(),e.object({options:e.array(e.string().min(1).max(200)).max(20),selected:e.string().min(1).max(200).nullable()}).strict()),quantities:e.record(e.string(),e.strictObject({minimum:e.number().int().nonnegative(),maximum:e.number().int().nonnegative(),step:e.number().int().positive(),value:e.number().int().nonnegative(),label:e.string(),available:e.boolean()})).optional(),diagnostics:e.array(e.object({nodeId:e.string(),message:e.string()}).strict())}).strict();function ie(t){return[...t.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(n=>n[1]===void 0?[]:[n[1].trim()])}function Z(t){let n=ie(t).filter(r=>!_e.includes(r)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(r)),i=t.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(i.includes("{{")||i.includes("}}"))&&n.push("无效变量语法"),[...new Set(n)]}function Vt(t,n,i={}){let r=t?.nodes[n];if(!r)return;let o=r.picker?i[r.picker]??t?.pickers[r.picker]?.selected:void 0;return typeof o=="string"?r.byPlan?.[o]??r.base:r.base}var Ne=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],oe=e.enum(Ne),ae=e.object({source:oe,layout:e.enum(["full","compact"]),resourceKey:E.optional(),pageSize:e.number().int().min(1).max(50),showSources:e.boolean(),allowPurchase:e.boolean(),outputs:e.object({billing_adjustment:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((t,n)=>{(t.outputs?.billing_authorization||t.outputs?.billing_adjustment)&&t.source!=="billing_controls"&&n.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),t.resourceKey&&!["credit_balance","credit_transactions"].includes(t.source)&&n.addIssue({code:"custom",message:"这个数据源不能绑定积分资源。"}),t.showSources&&t.source!=="credit_balance"&&n.addIssue({code:"custom",message:"只有积分余额可以展开来源。"}),t.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(t.source)&&n.addIssue({code:"custom",message:"只有积分包、套餐与会员组件可以启用交易。"})}),x=e.string().max(2e3),se=e.object({id:e.string().max(100),label:x,detail:e.array(x).max(12),value:x.optional(),status:x.optional(),facts:e.array(e.object({label:x,value:x}).strict()).max(1e3),purchaseId:e.uuid().optional(),invoiceUrl:e.url().max(2048).refine(t=>{let n=new URL(t);return n.protocol==="https:"&&!n.username&&!n.password}).optional(),billingActions:e.array(e.strictObject({action:e.literal("invoice_open"),label:x})).max(1).optional(),membershipActions:e.array(e.object({value:e.string().max(100),label:x}).strict()).max(3).optional()}).strict(),Pe=e.object({key:E,name:x,spendable:x,reserved:x,available:x,expiry:x.nullable(),sources:e.array(se).max(50),sourceCount:e.number().int().nonnegative(),sourcePage:e.number().int().positive(),hasNextSources:e.boolean(),hasPreviousSources:e.boolean()}).strict(),Oe=e.object({source:oe,status:e.enum(["idle","loading","ready","error"]),stale:e.boolean(),preview:e.boolean(),errorCode:e.string().max(80).optional(),errorMessage:x.optional(),resources:e.array(Pe).max(500),rows:e.array(se).max(50),hasNext:e.boolean(),hasPrevious:e.boolean(),page:e.number().int().positive(),filter:e.string().max(40),updatedAt:e.iso.datetime().optional(),buyingId:e.uuid().optional(),membershipBusy:e.boolean().optional(),billingBusy:e.boolean().optional(),membershipReview:e.object({title:x,note:x,facts:e.array(e.object({label:x,value:x}).strict()).max(100)}).strict().optional(),membershipResult:x.optional()}).strict(),Qt=e.object({nodes:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Oe)}).strict(),Ft=e.object({nodeId:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:e.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:e.string().max(100).optional()}).strict();function ce(t){return t.type==="stack"&&t.interaction?.type==="select"&&t.interaction.purpose==="product"&&!!t.interaction.pickerId}function le(t){let n={};function i(r){if(ce(r)){let o=n[r.interaction.pickerId]??={ids:[],defaultId:null};for(let s of r.children){let l=s.type==="stack"?s.bind?.plan:void 0;l&&!o.ids.includes(l)&&o.ids.push(l)}let a=r.children[r.interaction.defaultIndex];!o.defaultId&&a?.type==="stack"&&(o.defaultId=a.bind?.plan??null)}r.type==="stack"&&r.children.forEach(i)}return t.pages.forEach(r=>i(r.root)),n}function pe(t,n,i){let r={};function o(u){if(u.hidden)return;if(u.type==="plan_picker"){let b=i.pickers[u.id];r[u.id]={ids:b?.options??[],defaults:b?.selected?[b.selected]:[],remembered:[]};return}if(u.type!=="stack")return;let y=u.children.filter(b=>!b.hidden),c=u.interaction;if(ce(u)){let b=r[u.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},k=i.pickers[u.interaction.pickerId]?.options??[];for(let p of y){let d=p.type==="stack"?p.bind?.plan:void 0;d&&k.includes(d)&&!b.ids.includes(d)&&b.ids.push(d),d&&p.id===n[u.id]&&b.remembered.push(d)}let m=u.children[u.interaction.defaultIndex];m?.type==="stack"&&!m.hidden&&m.bind?.plan&&b.defaults.push(m.bind.plan)}if(c?.type==="tabs"){let b=y.find(k=>k.id===n[u.id])??u.children[c.defaultIndex];b&&o(b)}else if(c?.type==="toggle"){let b=typeof n[u.id]=="boolean"?n[u.id]:c.defaultEnabled,k=u.children[b?0:1];k&&o(k)}else y.forEach(o)}let a=typeof n.__page=="string"?n.__page:t.initialPageId??t.pages[0]?.id,s=t.pages.find(u=>u.id===a);s&&o(s.root);let l={};for(let[u,y]of Object.entries(r)){let c=n[u],b=y.remembered[0]??(y.ids.includes(i.pickers[u]?.selected??"")?i.pickers[u]?.selected:y.defaults[0]);l[u]=typeof c=="string"?y.ids.includes(c)?c:"":b&&y.ids.includes(b)?b:""}for(let u of Object.keys(le(t)))l[u]??="";return l}var ue=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),me=e.strictObject({tiers:e.array(e.strictObject({id:ue,name:e.string().trim().min(1).max(80)})).min(1).max(8),assignments:e.array(e.strictObject({productVersionId:e.string().min(1).max(200),tierId:ue,period:e.enum(["month","year"])})).max(20)}).superRefine((t,n)=>{let i=t.tiers.map(r=>r.id);(new Set(i).size!==i.length||new Set(t.assignments.map(r=>r.productVersionId)).size!==t.assignments.length||new Set(t.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==t.assignments.length||t.assignments.some(r=>!i.includes(r.tierId)))&&n.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function fe(t,n){return t.assignments.length===n.length&&t.assignments.every(i=>n.includes(i.productVersionId))}function Jt(t){let n=Z(t).map(i=>`未知变量:${i}`);for(let i=0;i<t.length;i++){if(t[i]!=="<"||!/[A-Za-z!/?{]/.test(t[i+1]??""))continue;let r=i;if(t.startsWith("<!--",i)){let o=t.indexOf("-->",i+4);i=o<0?t.length:o+2}else{let o="";for(i++;i<t.length;i++){let a=t[i];if(o)a===o&&(o="");else if(a==='"'||a==="'")o=a;else if(a===">")break}}/\{\{|\}\}/.test(t.slice(r,i+1))&&n.push("变量只能放在 HTML 文字中,不能放入标签、属性或注释")}return[...new Set(n)]}var h={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},ge=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),S=e.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(t=>!ge.has(t),"Reserved UI identifier"),B=e.union([e.string().max(2e3),e.number().finite(),e.boolean(),e.null()]),Ae=e.discriminatedUnion("type",[e.strictObject({type:e.literal("enum"),values:e.array(B).min(1).max(h.enumValues),default:B}),e.strictObject({type:e.literal("number"),min:e.number().finite(),max:e.number().finite(),step:e.number().finite().positive(),default:e.number().finite()}),e.strictObject({type:e.literal("text"),maxLength:e.number().int().min(0).max(2e3),default:e.string().max(2e3).nullable()}),e.strictObject({type:e.literal("boolean"),default:e.boolean()})]);function D(t,n){if(t.type==="enum")return t.values.some(r=>r===n);if(t.type==="boolean")return typeof n=="boolean";if(t.type==="text")return n===null||typeof n=="string"&&n.length<=t.maxLength;if(typeof n!="number"||!Number.isFinite(n)||n<t.min||n>t.max)return!1;let i=(n-t.min)/t.step;return Number.isFinite(i)&&Math.abs(i-Math.round(i))<=Math.min(1e-7,Math.max(1,Math.abs(i))*Number.EPSILON*8)}var Ce=Ae.superRefine((t,n)=>{t.type==="enum"&&new Set(t.values).size!==t.values.length&&n.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),t.type==="number"&&t.min>t.max&&n.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),D(t,t.default)||n.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),$e=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function Ue(t,n){return t==="now"?n===0:t==="concat"?!0:t==="lookup"?n>=4&&n%2===0:t==="if"?n===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(t)?n===2:["round","floor","not","number","parse_number","money","duration"].includes(t)?n===1:n>=1}var N=e.lazy(()=>e.union([B,e.strictObject({ref:S}),e.strictObject({op:e.enum($e),args:e.array(N).max(h.expressionNodes)}).superRefine((t,n)=>{Ue(t.op,t.args.length)||n.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function j(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=Object.getPrototypeOf(t);return n===null||n===Object.prototype}function _(t,n,i){if(!t||typeof t!="object")return!0;if(!j(t))return n.addIssue({code:"custom",path:i,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(t)){if(ge.has(r))return n.addIssue({code:"custom",path:[...i,r],message:"Reserved UI object key"}),!1;let o=Object.getOwnPropertyDescriptor(t,r);if(o&&!Object.hasOwn(o,"value"))return n.addIssue({code:"custom",path:[...i,r],message:"UI objects cannot contain accessors"}),!1}return!0}function O(t,n,i,r){let o=[{value:t,depth:1,path:i}];for(;o.length;){let a=o.pop();if(++r.nodes>h.expressionNodes||a.depth>h.depth){n.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!_(a.value,n,a.path))return;if(j(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>h.expressionNodes){n.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let s=a.value.args.length-1;s>=0;s--)o.push({value:a.value.args[s],depth:a.depth+1,path:[...a.path,"args",s]})}}}var en=e.unknown().superRefine((t,n)=>{O(t,n,[],{nodes:0})}).pipe(N),Q=e.record(S,N).refine(t=>Object.keys(t).length>0&&Object.keys(t).length<=h.state,"UI assignments need 1–32 state keys"),Le=e.strictObject({target:S,property:e.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:N,className:S.optional()}).superRefine((t,n)=>{t.property==="class"!=(t.className!==void 0)&&n.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),Te=e.discriminatedUnion("type",[e.strictObject({type:e.literal("scroll_latch"),target:S,state:S}),e.strictObject({type:e.literal("input"),target:S,state:S,set:Q.optional()}),e.strictObject({type:e.literal("action"),target:S,set:Q}),e.strictObject({type:e.literal("carousel"),target:S,state:S,initialIndex:e.number().int().nonnegative().optional(),maxWidth:e.number().int().min(1).max(1e4).optional(),previousTarget:S.optional(),nextTarget:S.optional(),inactiveTargets:e.array(S).max(20).optional(),inactiveMaxWidth:e.number().int().min(1).max(1e4).optional()})]),De=e.strictObject({afterMs:e.number().int().min(0).max(6e4),set:Q}),Re=e.strictObject({type:e.literal("mosaic_waves"),target:S,color:e.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:e.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:N.optional(),speed:e.number().min(0).max(4).optional(),pitch:e.number().min(.05).max(4).optional(),fill:e.number().min(.05).max(1).optional(),feather:e.number().min(0).max(1).optional(),warp:e.number().min(0).max(4).optional(),warpScale:e.number().min(0).max(32).optional(),detailScale:e.number().min(0).max(32).optional(),waveScale:e.number().min(0).max(32).optional(),falloff:e.number().min(.1).max(32).optional(),brightness:e.number().min(0).max(32).optional(),ambient:e.number().min(0).max(1).optional(),gamma:e.number().min(.05).max(8).optional(),vignette:e.number().min(0).max(1).optional(),opacity:e.number().min(0).max(1).optional()}),Ee=e.strictObject({type:e.literal("number_counter"),target:S,value:N,prefix:e.string().max(20).optional(),format:e.enum(["number","short"]).optional()}),Ve=e.strictObject({state:e.record(S,Ce).refine(t=>Object.keys(t).length<=h.state,"Too many UI state keys").optional(),derived:e.record(S,N).refine(t=>Object.keys(t).length<=h.derived,"Too many UI derived keys").optional(),bindings:e.array(Le).max(h.bindings).optional(),controls:e.array(Te).max(h.controls).optional(),timers:e.array(De).max(h.timers).optional(),effects:e.array(e.discriminatedUnion("type",[Re,Ee])).max(h.effects).optional(),clock:e.boolean().optional()});function Me(t,n){if(!_(t,n,[])||!j(t))return;for(let[r,o]of[["state",h.state],["derived",h.derived]]){let a=t[r];if(!_(a,n,[r]))return;if(j(a)&&Object.keys(a).length>o){n.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,o]of[["bindings",h.bindings],["controls",h.controls],["timers",h.timers],["effects",h.effects]])if(Array.isArray(t[r])&&t[r].length>o){n.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(t.effects)){for(let[r,o]of t.effects.entries())if(!_(o,n,["effects",r]))return}if(j(t.state))for(let[r,o]of Object.entries(t.state)){if(!_(o,n,["state",r]))return;if(j(o)&&Array.isArray(o.values)&&o.values.length>h.enumValues){n.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let i={nodes:0};if(j(t.derived))for(let[r,o]of Object.entries(t.derived))O(o,n,["derived",r],i);for(let r of["bindings","controls","timers"]){let o=t[r];if(Array.isArray(o)){for(let[a,s]of o.entries())if(!(!_(s,n,[r,a])||!j(s))){if(r==="bindings")O(s.expression,n,[r,a,"expression"],i);else if(_(s.set,n,[r,a,"set"])&&j(s.set)){if(Object.keys(s.set).length>h.state){n.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[l,u]of Object.entries(s.set))O(u,n,[r,a,"set",l],i)}if(i.nodes>h.expressionNodes)return}}}if(Array.isArray(t.effects))for(let[r,o]of t.effects.entries())j(o)&&o.type==="number_counter"?O(o.value,n,["effects",r,"value"],i):j(o)&&o.enabled!==void 0&&O(o.enabled,n,["effects",r,"enabled"],i)}function de(t){let n=[],i=[t];for(;i.length;){let r=i.pop();!r||typeof r!="object"||("ref"in r?n.push(r.ref):i.push(...r.args))}return n}var be=e.unknown().superRefine(Me).pipe(Ve).superRefine((t,n)=>{let i=t.state??{},r=t.derived??{},o=new Set([...Object.keys(i),...Object.keys(r)]),a=(m,p)=>{for(let d of de(m))o.has(d)||n.addIssue({code:"custom",path:p,message:`Unknown UI reference: ${d}`})};for(let[m,p]of Object.entries(t.derived??{}))Object.hasOwn(i,m)&&n.addIssue({code:"custom",path:["derived",m],message:"UI state and derived identifiers must be distinct"}),a(p,["derived",m]);let s=new Set,l=new Set,u=m=>{if(s.has(m))return!1;if(l.has(m))return!0;s.add(m);for(let p of de(r[m]))if(Object.hasOwn(r,p)&&!u(p))return!1;return s.delete(m),l.add(m),!0};for(let m of Object.keys(r))if(!u(m)){n.addIssue({code:"custom",path:["derived",m],message:"Cyclic UI derived references"});break}for(let[m,p]of(t.bindings??[]).entries())a(p.expression,["bindings",m,"expression"]);let y=new Set;for(let[m,p]of(t.effects??[]).entries())y.has(p.target)&&n.addIssue({code:"custom",path:["effects",m,"target"],message:"Effect targets must be unique"}),y.add(p.target),p.type==="number_counter"?(a(p.value,["effects",m,"value"]),typeof p.value=="number"&&Math.abs(p.value)>1e12&&n.addIssue({code:"custom",path:["effects",m,"value"],message:"Counter values must be within the display bound"})):p.enabled!==void 0&&a(p.enabled,["effects",m,"enabled"]);let c=(m,p)=>{for(let[d,v]of Object.entries(m))Object.hasOwn(i,d)||n.addIssue({code:"custom",path:[...p,d],message:"UI assignments can only update declared state"}),a(v,[...p,d])},b=new Set,k=new Set;for(let[m,p]of(t.controls??[]).entries()){if(p.type==="carousel"&&p.inactiveMaxWidth!==void 0&&p.inactiveTargets===void 0&&n.addIssue({code:"custom",path:["controls",m,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),p.type==="carousel")for(let d of p.inactiveTargets??[])(d===p.target||k.has(d))&&n.addIssue({code:"custom",path:["controls",m,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),k.add(d);if(p.type==="carousel")for(let d of["previousTarget","nextTarget"]){let v=p[d];v!==void 0&&((v===p.target||b.has(v)||(t.controls??[]).some(ze=>ze.target===v))&&n.addIssue({code:"custom",path:["controls",m,d],message:"Carousel navigation needs a distinct, exclusive button target"}),b.add(v))}if(p.type!=="action"){let d=Object.hasOwn(i,p.state)?i[p.state]:void 0;(!d||p.type==="input"&&d.type==="enum"&&d.values.some(v=>typeof v!="string"))&&n.addIssue({code:"custom",path:["controls",m,"state"],message:"Control needs a supported declared UI state"}),p.type==="carousel"&&(d?.type!=="number"||!Number.isInteger(d.min)||d.min<0||!Number.isInteger(d.max)||d.step!==1||p.initialIndex!==void 0&&!D(d,p.initialIndex))&&n.addIssue({code:"custom",path:["controls",m],message:"Carousel needs bounded nonnegative integer index state"}),p.type==="scroll_latch"&&d?.type!=="boolean"&&n.addIssue({code:"custom",path:["controls",m,"state"],message:"Scroll latches require boolean UI state"})}(p.type==="input"||p.type==="action")&&p.set&&c(p.set,["controls",m,"set"])}for(let[m,p]of(t.timers??[]).entries())c(p.set,["timers",m,"set"])});var he=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,A=e.string().max(16).regex(he,"语言代码格式不正确,例如 zh-CN、en").refine(t=>{try{return Intl.getCanonicalLocales(t)[0]===t}catch{return!1}},"持久化语言代码必须使用规范写法");function F(t){if(typeof t!="string")return null;try{let n=Intl.getCanonicalLocales(t.trim().replaceAll("_","-"))[0];if(!n)return null;let{language:i,script:r,region:o}=new Intl.Locale(n),a=[i,r,o].filter(Boolean).join("-");return he.test(a)?a:null}catch{return null}}var Ze=new Set(["TW","HK","MO"]);function ye(t){let[n,i,r]=t.split("-");if(n!=="zh")return`${n}-${new Intl.Locale(t).maximize().script??""}`;let o=i?.length===4?i:void 0,a=i?.length===4?r:i;return o?`zh-${o}`:a&&Ze.has(a)?"zh-Hant":"zh-Hans"}function xe(t,n,i){let r=n.map(o=>({code:A.parse(o),normalized:o}));for(let o of t){let a=F(o);if(!a)continue;let s=r.find(c=>c.normalized===a);if(s)return s.code;let l=ye(a),u=r.filter(c=>ye(c.normalized)===l),y=u.find(c=>!c.normalized.includes("-")||c.normalized===l)??u[0];if(y)return y.code}return i}var Be=4,z={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},U=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),g=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Qe=e.enum(["none","xs","sm","md","lg","xl"]),Fe=e.enum(["none","sm","md","lg","full"]),H=e.string().regex(/^#[0-9a-fA-F]{6}$/),G=e.string().max(2048).refine(t=>{try{let n=new URL(t);return n.protocol==="https:"&&n.hostname.length>0}catch{return!1}},"只支持 https 链接"),q=e.union([G,e.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),e.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),e.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Se=e.object({primary:H,background:H,text:H,radius:Fe,font:e.enum(["system","serif","rounded","mono"]),fontAssets:e.object({family:e.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:e.array(e.object({url:G,weight:e.number().int().min(100).max(900).multipleOf(100),family:e.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),L=e.union([e.enum(["primary","text","muted","background","surface"]),e.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),f=(t,n)=>e.number().int().min(t).max(n),ke=e.union([e.enum(["fit","fill"]),f(1,1200)]),He=e.object({top:f(0,200),right:f(0,200),bottom:f(0,200),left:f(0,200)}).strict(),qe=e.object({top:f(-100,200),right:f(-100,200),bottom:f(-100,200),left:f(-100,200)}).strict(),Ie=e.object({x:f(0,100),y:f(0,100)}).strict(),Ge=e.discriminatedUnion("type",[e.object({type:e.literal("color"),color:L}).strict(),e.object({type:e.literal("linear"),angle:f(0,360),stops:e.array(e.object({color:L,at:f(0,100)}).strict()).min(2).max(4)}).strict(),e.object({type:e.literal("image"),src:q,fit:e.enum(["cover","contain"]),position:Ie.optional()}).strict()]),We=e.discriminatedUnion("type",[e.object({type:e.literal("rect"),radius:e.union([f(0,200),e.object({topLeft:f(0,200),topRight:f(0,200),bottomRight:f(0,200),bottomLeft:f(0,200)}).strict()])}).strict(),e.object({type:e.literal("pill")}).strict()]),Ke=e.object({width:f(0,12),color:L,style:e.enum(["solid","dashed"])}).strict(),Je=e.object({x:f(-40,40),y:f(-40,40),blur:f(0,80),spread:f(-20,40),color:L}).strict(),Xe=e.object({font:e.enum(["system","serif","rounded","mono"]),size:f(8,96),weight:e.number().int().min(100).max(900).multipleOf(100),lineHeight:e.number().min(.8).max(3),letterSpacing:e.number().min(-5).max(20),color:L,align:e.enum(["start","center","end"]),italic:e.boolean(),decoration:e.enum(["none","underline","line-through"]),transform:e.enum(["none","uppercase"])}).strict().partial(),P=e.object({width:ke,height:ke,padding:He,margin:qe,gap:f(0,120),grow:e.union([e.boolean(),e.number().min(0).max(12)]),background:Ge,opacity:e.number().min(0).max(1),clipContent:e.boolean(),shape:We,border:Ke,shadow:Je,text:Xe}).strict().partial(),I={id:U,name:e.string().trim().min(1).max(60).optional(),hidden:e.boolean().optional(),style:P.optional(),fallback:g.optional()},Ye=e.object({...I,type:e.literal("text"),productField:e.enum(["name","price","trial","period"]).optional(),feature:e.object({id:e.uuid(),field:e.enum(["name","allowance"])}).strict().optional(),text:g,variant:e.enum(["title","heading","body","caption"])}).strict(),et=e.object({...I,type:e.literal("image"),src:q,localizedSrc:e.record(A,q).optional(),alt:g,aspect:e.enum(["auto","1:1","4:3","16:9","3:1"]),fit:e.enum(["cover","contain"]),position:Ie.optional()}).strict(),tt=e.object({...I,type:e.literal("button"),label:g,variant:e.enum(["primary","secondary","link"]),action:g,purpose:e.enum(["purchase","navigation","close"]).optional(),bind:T.optional()}).strict(),nt=e.object({...I,type:e.literal("divider")}).strict(),rt=e.object({...I,type:e.literal("customer_data"),title:g,data:ae}).strict(),it=e.object({...I,type:e.literal("spacer"),size:Qe}).strict(),ot=e.object({...I,type:e.literal("custom_html"),html:e.record(A,e.string().max(z.customHtml)),css:e.string().max(z.customCss),ui:be.optional()}).strict(),at=e.object({...I,type:e.literal("price"),fallback:g,parts:e.object({current:P.optional(),original:P.optional(),period:P.optional()}).strict().optional()}).strict(),st=e.object({...I,type:e.literal("coupon_code"),label:g,fallback:g}).strict(),ct=e.object({...I,type:e.literal("countdown"),source:e.enum(["offer.ends_at","offer.expires_at","fixed"]),at:e.iso.datetime().optional(),granularity:e.enum(["day","hour","minute","second"]),expired:g,fallback:g}).strict().refine(t=>t.source!=="fixed"||!!t.at,"固定倒计时需要结束时间"),lt=e.object({...I,type:e.literal("plan_picker"),label:g,fallback:g,planIds:e.array(e.string().min(1).max(200)).min(1).max(20).refine(t=>new Set(t).size===t.length,"套餐不能重复").optional(),defaultPlan:e.string().min(1).max(200).optional(),grouping:me.safeExtend({monthLabel:g,yearLabel:g,unavailableLabel:g}).optional(),states:e.object({selected:P.optional()}).strict().optional()}).strict().superRefine((t,n)=>{t.grouping&&(!t.planIds||!fe(t.grouping,t.planIds))&&n.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),pt=e.object({...I,type:e.literal("quantity_picker"),bind:T.optional(),label:g,fallback:g,internalFeatureId:e.uuid(),minimumQuantity:f(0,1e4),maximumQuantity:f(0,1e4),defaultQuantity:f(0,1e4),step:f(1,1e4)}).strict().refine(t=>t.minimumQuantity<=t.defaultQuantity&&t.defaultQuantity<=t.maximumQuantity&&(t.defaultQuantity-t.minimumQuantity)%t.step===0,"Quantity controls require a Product binding and valid bounds"),ut=e.discriminatedUnion("type",[e.object({type:e.literal("input"),label:g,keyboard:e.enum(["text","email","tel","url"]),maxLength:f(1,500)}).strict(),e.object({type:e.literal("multiselect"),label:g,min:f(0,50),max:f(1,50)}).strict(),e.object({type:e.literal("select"),label:g,defaultIndex:f(0,49),purpose:e.enum(["option","product","tier"]).optional(),pickerId:U.optional(),selectedStyle:P.optional()}).strict(),e.object({type:e.literal("tabs"),label:g,defaultIndex:f(0,49),purpose:e.literal("tier").optional()}).strict(),e.object({type:e.literal("toggle"),label:g,defaultEnabled:e.boolean()}).strict(),e.object({type:e.literal("carousel"),label:g}).strict()]),w={...I,type:e.literal("stack"),direction:e.enum(["vertical","horizontal","overlay"]),align:e.enum(["start","center","end","stretch"]),justify:e.enum(["start","center","end","between"]),productSlot:e.object({index:f(0,19),period:e.enum(["month","year"]).optional(),requireBinding:e.boolean().optional()}).strict().optional(),interaction:ut.optional(),states:e.object({selected:P.optional()}).strict().optional(),purpose:e.literal("benefits").optional(),purchaseAction:g.optional(),buttonVariant:e.enum(["primary","secondary","link"]).optional(),bind:T.optional()},je=e.lazy(()=>e.object({...I,type:w.type,direction:w.direction,align:w.align,justify:w.justify,children:e.array(mt).max(z.children),productSlot:w.productSlot,interaction:w.interaction,states:w.states,purpose:w.purpose,purchaseAction:w.purchaseAction,buttonVariant:w.buttonVariant,bind:w.bind}).strict()),mt=e.lazy(()=>e.union([je,Ye,et,tt,nt,it,ot,at,st,ct,lt,pt,rt])),ft=e.union([e.string().max(500),e.number().finite(),e.boolean(),e.null()]),$={id:g,event:g,properties:e.record(g,ft).refine(t=>Object.keys(t).length<=20,"最多 20 个参数")},dt=e.discriminatedUnion("type",[e.object({...$,type:e.literal("navigate"),close:e.literal(!1),pageId:U}).strict(),e.object({...$,type:e.literal("event"),close:e.boolean()}).strict(),e.object({...$,type:e.literal("close"),close:e.literal(!0)}).strict(),e.object({...$,type:e.literal("open_url"),close:e.boolean(),url:G}).strict(),e.object({...$,type:e.literal("claim_offer"),close:e.boolean(),couponId:e.uuid()}).strict()]),gt=e.object({defaultLocale:A,locales:e.record(A,e.record(g,e.string().max(z.stringLength)))}).strict(),bt=e.enum(["popup","paywall","onboarding","page","banner"]);var yt=e.object({kind:e.literal("screen"),schemaVersion:e.literal(Be),name:e.string().trim().min(1).max(80),surface:bt,initialPageId:U.optional(),presentation:X,theme:Se,pages:e.array(e.object({id:U,name:e.string().trim().min(1).max(60),root:je,theme:Se.optional(),editorPosition:e.object({x:e.number().finite().min(-1e5).max(1e5),y:e.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:gt,actions:e.array(dt).max(z.actions)}).strict();function R(t,n){for(let i of t.pages)W(i.root,n)}var dn=yt.superRefine((t,n)=>{let i=z;t.surface!=="paywall"&&t.pages.length!==1&&n.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),t.initialPageId&&!t.pages.some(c=>c.id===t.initialPageId)&&n.addIssue({code:"custom",message:"Initial screen does not exist"});for(let c of t.actions)c.type==="navigate"&&(t.surface!=="paywall"||!t.pages.some(b=>b.id===c.pageId))&&n.addIssue({code:"custom",message:"Navigation screen does not exist"});t.pages.length>i.pages&&n.addIssue({code:"custom",message:`页面最多 ${i.pages} 个`}),t.actions.length>i.actions&&n.addIssue({code:"custom",message:`动作最多 ${i.actions} 个`});let r=c=>n.addIssue({code:"custom",message:c}),o=Object.keys(t.strings.locales);o.includes(t.strings.defaultLocale)||r("默认语言必须在语言列表里"),o.length>z.locales&&r(`最多 ${z.locales} 种语言`);let a=new Set;for(let c of t.actions)a.has(c.id)&&r(`动作标识重复:${c.id}`),a.add(c.id);let s=new Set;for(let c of t.pages)["next","back"].includes(c.id)&&r(`页面 id 不能使用保留名称:${c.id}`),s.has(c.id)&&r(`页面 id 重复:${c.id}`),s.add(c.id);let l=new Set,u=0,y=!1;R(t,(c,b)=>{if(u++,b>z.depth&&(y=!0),l.has(c.id)&&r(`组件 id 重复:${c.id}`),l.add(c.id),c.type==="button"&&!a.has(c.action)&&r(`按钮 ${c.id} 引用的动作不存在:${c.action}`),c.type==="custom_html")for(let k of Object.keys(c.html))o.includes(k)||r(`自定义 HTML ${c.id} 含有未启用的语言:${k}`);if(c.type==="image")for(let k of Object.keys(c.localizedSrc??{}))o.includes(k)||r(`图片 ${c.id} 含有未启用的语言:${k}`)}),u>i.nodes&&r(`组件最多 ${i.nodes} 个`),y&&r(`层级最多 ${z.depth} 层`)});function W(t,n,i=1,r=null){if(n(t,i,r)!==!1&&t.type==="stack")for(let o of t.children)W(o,n,i+1,t)}function we(t){let n=[],i=new Set;return R(t,r=>{let o=(a,s,l)=>{i.has(a)||(i.add(a),n.push({key:a,nodeId:r.id,nodeType:r.type,field:s,required:l}))};r.type==="stack"&&r.interaction&&o(r.interaction.label,"label",!0),r.fallback&&o(r.fallback,"text",!0),r.type==="text"&&o(r.text,"text",!0),r.type==="customer_data"&&o(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&o(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(o(r.grouping.monthLabel,"label",!0),o(r.grouping.yearLabel,"label",!0),o(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&o(r.expired,"text",!0),r.type==="button"&&o(r.label,"label",!0),r.type==="image"&&(o(`image:${r.id}`,"src",!1),o(r.alt,"alt",!1)),r.type==="custom_html"&&o(`html:${r.id}`,"html",!0)}),n}function ht(t,n,i){if(n.field==="html"){let r;return R(t,o=>{o.id===n.nodeId&&o.type==="custom_html"&&(r=o.html[i])}),r}if(n.field==="src"){let r=It(t,n.nodeId);return r?.type==="image"?r.localizedSrc?.[i]??(i===t.strings.defaultLocale?r.src:void 0):void 0}return t.strings.locales[i]?.[n.key]}function xt(t){let n=we(t).filter(r=>r.required);return Object.keys(t.strings.locales).sort((r,o)=>r===t.strings.defaultLocale?-1:o===t.strings.defaultLocale?1:0).map(r=>{let o=n.filter(a=>!ht(t,a,r)?.trim()).map(a=>a.key);return{locale:r,total:n.length,filled:n.length-o.length,missing:o,complete:o.length===0}})}function St(t){return xt(t).filter(n=>n.complete||n.locale===t.strings.defaultLocale).map(n=>n.locale)}function gn(t,n){return xe(n,St(t),t.strings.defaultLocale)}function bn(t,n){let i=t.strings.locales[n]??{},r=t.strings.locales[t.strings.defaultLocale]??{},o={};for(let s of we(t)){if(s.field==="html"||s.field==="src")continue;let l=i[s.key]?.trim()?i[s.key]:r[s.key];l!==void 0&&(o[s.key]=l)}let a=s=>{if(s.type==="stack")return{...s,children:s.children.map(a)};if(s.type==="custom_html"){let l=s.html[n]?.trim()?s.html[n]:s.html[t.strings.defaultLocale];return{...s,html:l===void 0?{}:{[n]:l}}}if(s.type==="image"){let{localizedSrc:l,...u}=s;return{...u,src:l?.[n]??l?.[t.strings.defaultLocale]??s.src}}return s};return{...t,pages:t.pages.map(s=>({...s,root:a(s.root)})),strings:{defaultLocale:n,locales:{[n]:o}}}}function kt(t,n){let i=null;return W(t,r=>{if(i)return!1;r.id===n&&(i=r)}),i}function It(t,n){for(let i of t.pages){let r=kt(i.root,n);if(r)return r}return null}function yn(t){let n=F(t)?.split("-")[0];return n!==void 0&&["ar","he","fa","ur"].includes(n)}function hn(t,n,i){let r={};if(!n||typeof n!="object"||Array.isArray(n))return r;let o=n;if(R(t,a=>{if(a.type==="quantity_picker"){let l=o[a.id];typeof l=="number"&&Number.isSafeInteger(l)&&l>=a.minimumQuantity&&l<=a.maximumQuantity&&(l-a.minimumQuantity)%a.step===0&&(r[a.id]=l);return}if(a.type==="plan_picker"){let l=o[a.id];typeof l=="string"&&(r[a.id]=i?.pickers[a.id]?.options.includes(l)?l:"");return}if(a.type==="custom_html"&&a.ui)for(let[l,u]of Object.entries(a.ui.state??{})){let y=`${a.id}.${l}`,c=o[y];c!==null&&D(u,c)&&(r[y]=c)}if(a.type!=="stack"||!a.interaction)return;let s=Object.hasOwn(o,a.id)?o[a.id]:void 0;["select","tabs"].includes(a.interaction.type)&&typeof s=="string"&&a.children.some(l=>l.id===s)&&(r[a.id]=s),a.interaction.type==="toggle"&&typeof s=="boolean"&&(r[a.id]=s)}),t.surface==="paywall"&&typeof o.__page=="string"&&t.pages.some(a=>a.id===o.__page)&&(r.__page=o.__page),i){let a={...r};for(let[s,l]of Object.entries(o))(typeof l=="string"||typeof l=="boolean")&&(a[s]=l);Object.assign(r,pe(t,a,i))}return r}export{V as a,wt as b,te as c,Ot as d,ne as e,re as f,Et as g,ie as h,Vt as i,le as j,me as k,fe as l,Qt as m,Ft as n,Jt as o,A as p,F as q,z as r,U as s,g as t,q as u,R as v,dn as w,W as x,we as y,xt as z,gn as A,bn as B,It as C,yn as D,hn as E};
|
|
1
|
+
import{a as C,j as J}from"./chunk-RJT764B2.js";import{b as X}from"./chunk-NNJVMJUG.js";import{j as K,l as E}from"./chunk-OZK47BUU.js";import{b as e}from"./chunk-5YBTU4KS.js";var Y=e.number().int().min(0).max(1e8),V=e.strictObject({kind:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Y,flatAmountMinor:Y.optional()})).min(1).max(12)}).refine(t=>t.tiers.at(-1)?.upTo===null&&t.tiers.slice(0,-1).every((n,i)=>{let r=t.tiers[i-1]?.upTo;return n.upTo!==null&&(i===0||r!=null&&n.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(t=>!t.tiers.some(n=>(n.flatAmountMinor??0)>0)||t.kind==="volume"&&t.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function M(t,n){if(!Number.isInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased pack quantity");let i=t.pricing?V.parse(t.pricing):void 0;if(n===0)return 0;let r=0n,o=0;if(!i)r=BigInt(t.amountMinor)*BigInt(n);else for(let a of i.tiers){let s=a.upTo??1e4;if(i.kind==="volume"){if(n<=s){r=BigInt(n)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else n>o&&(r+=BigInt(Math.min(n,s)-o)*BigInt(a.unitAmountMinor));o=s}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function wt(t){return M({amountMinor:t.unitAmountMinor,...t.pricing?{pricing:t.pricing}:{}},t.quantity)}var ve=K.refine(t=>/[1-9]/.test(t)),te=e.strictObject({units:ve,prices:e.array(e.strictObject({currency:C,amountMinor:e.number().int().min(0).max(1e8),pricing:V.optional()})).min(1).max(20).refine(t=>new Set(t.map(n=>n.currency)).size===t.length,"Currencies must be unique").refine(t=>t.every(n=>!n.pricing||n.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:e.number().int().min(0).max(1e4),maximumQuantity:e.number().int().min(0).max(1e4)}).refine(t=>t.maximumQuantity>=t.minimumQuantity,"Purchased quantity must fit its published bounds").refine(t=>{try{for(let n of t.prices)for(let i of[t.maximumQuantity,...n.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])i<=t.maximumQuantity&&M({amountMinor:n.amountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}},i);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function ee(t){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(t))throw new Error("Invalid quantity");let[n,i=""]=t.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*1000000n+BigInt(i.padEnd(6,"0"))}function Ot(t,n,i){if(!Number.isSafeInteger(i)||i<0||i>1e4)throw new Error("Invalid purchased quantity");let r=ee(t)+ee(n)*BigInt(i);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(o?"."+o:"")}var ne=e.strictObject({internalFeatureId:e.uuid(),name:e.string().min(1).max(120),includedAmount:e.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:e.enum(["hour","day","week","month","year","lifetime"]),resetCount:e.number().int().min(1).max(100),terms:te});var _e=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],T=e.object({plan:e.string().min(1).max(200).optional(),coupon:e.uuid().optional(),promotionCode:e.uuid().optional(),picker:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),re=e.object({text:e.string().optional(),label:e.string().optional(),alt:e.string().optional(),html:e.string().max(32768).optional(),price:e.object({current:e.string(),original:e.string().nullable(),period:e.string()}).optional(),code:e.string().optional(),countdownAt:e.iso.datetime().optional(),planId:e.string().min(1).max(200).optional(),planVersionId:e.string().min(1).max(200).optional(),currency:C.optional(),couponId:e.uuid().optional(),offerId:e.uuid().optional(),unavailable:e.boolean().optional(),unavailableReason:e.string().optional(),missing:e.array(e.string()).optional()}).strict(),Et=e.object({paywall:J.optional(),nodes:e.record(e.string(),e.object({base:re,picker:e.string().optional(),byPlan:e.record(e.string(),re).optional()}).strict()),plans:e.record(e.string(),e.object({id:e.string().min(1).max(200),versionId:e.string().min(1).max(200),available:e.boolean(),name:e.string(),price:e.string(),period:e.string(),currency:C.optional(),amountMinor:e.number().int().nonnegative().optional(),interval:e.enum(["free","week","month","year","one_time"]).optional(),intervalCount:e.number().int().positive().optional(),prepaid:e.array(ne).max(100).optional()}).strict()),pickers:e.record(e.string(),e.object({options:e.array(e.string().min(1).max(200)).max(20),selected:e.string().min(1).max(200).nullable()}).strict()),quantities:e.record(e.string(),e.strictObject({minimum:e.number().int().nonnegative(),maximum:e.number().int().nonnegative(),step:e.number().int().positive(),value:e.number().int().nonnegative(),label:e.string(),available:e.boolean()})).optional(),diagnostics:e.array(e.object({nodeId:e.string(),message:e.string()}).strict())}).strict();function ie(t){return[...t.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(n=>n[1]===void 0?[]:[n[1].trim()])}function Z(t){let n=ie(t).filter(r=>!_e.includes(r)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(r)),i=t.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(i.includes("{{")||i.includes("}}"))&&n.push("无效变量语法"),[...new Set(n)]}function Vt(t,n,i={}){let r=t?.nodes[n];if(!r)return;let o=r.picker?i[r.picker]??t?.pickers[r.picker]?.selected:void 0;return typeof o=="string"?r.byPlan?.[o]??r.base:r.base}var Ne=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],oe=e.enum(Ne),ae=e.object({source:oe,layout:e.enum(["full","compact"]),resourceKey:E.optional(),pageSize:e.number().int().min(1).max(50),showSources:e.boolean(),allowPurchase:e.boolean(),outputs:e.object({billing_adjustment:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((t,n)=>{(t.outputs?.billing_authorization||t.outputs?.billing_adjustment)&&t.source!=="billing_controls"&&n.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),t.resourceKey&&!["credit_balance","credit_transactions"].includes(t.source)&&n.addIssue({code:"custom",message:"这个数据源不能绑定积分资源。"}),t.showSources&&t.source!=="credit_balance"&&n.addIssue({code:"custom",message:"只有积分余额可以展开来源。"}),t.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(t.source)&&n.addIssue({code:"custom",message:"只有积分包、套餐与会员组件可以启用交易。"})}),x=e.string().max(2e3),se=e.object({id:e.string().max(100),label:x,detail:e.array(x).max(12),value:x.optional(),status:x.optional(),facts:e.array(e.object({label:x,value:x}).strict()).max(1e3),purchaseId:e.uuid().optional(),invoiceUrl:e.url().max(2048).refine(t=>{let n=new URL(t);return n.protocol==="https:"&&!n.username&&!n.password}).optional(),billingActions:e.array(e.strictObject({action:e.literal("invoice_open"),label:x})).max(1).optional(),membershipActions:e.array(e.object({value:e.string().max(100),label:x}).strict()).max(3).optional()}).strict(),Pe=e.object({key:E,name:x,spendable:x,reserved:x,available:x,expiry:x.nullable(),sources:e.array(se).max(50),sourceCount:e.number().int().nonnegative(),sourcePage:e.number().int().positive(),hasNextSources:e.boolean(),hasPreviousSources:e.boolean()}).strict(),Oe=e.object({source:oe,status:e.enum(["idle","loading","ready","error"]),stale:e.boolean(),preview:e.boolean(),errorCode:e.string().max(80).optional(),errorMessage:x.optional(),resources:e.array(Pe).max(500),rows:e.array(se).max(50),hasNext:e.boolean(),hasPrevious:e.boolean(),page:e.number().int().positive(),filter:e.string().max(40),updatedAt:e.iso.datetime().optional(),buyingId:e.uuid().optional(),membershipBusy:e.boolean().optional(),billingBusy:e.boolean().optional(),membershipReview:e.object({title:x,note:x,facts:e.array(e.object({label:x,value:x}).strict()).max(100)}).strict().optional(),membershipResult:x.optional()}).strict(),Qt=e.object({nodes:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Oe)}).strict(),Ft=e.object({nodeId:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:e.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:e.string().max(100).optional()}).strict();function ce(t){return t.type==="stack"&&t.interaction?.type==="select"&&t.interaction.purpose==="product"&&!!t.interaction.pickerId}function le(t){let n={};function i(r){if(ce(r)){let o=n[r.interaction.pickerId]??={ids:[],defaultId:null};for(let s of r.children){let l=s.type==="stack"?s.bind?.plan:void 0;l&&!o.ids.includes(l)&&o.ids.push(l)}let a=r.children[r.interaction.defaultIndex];!o.defaultId&&a?.type==="stack"&&(o.defaultId=a.bind?.plan??null)}r.type==="stack"&&r.children.forEach(i)}return t.pages.forEach(r=>i(r.root)),n}function pe(t,n,i){let r={};function o(u){if(u.hidden)return;if(u.type==="plan_picker"){let b=i.pickers[u.id];r[u.id]={ids:b?.options??[],defaults:b?.selected?[b.selected]:[],remembered:[]};return}if(u.type!=="stack")return;let y=u.children.filter(b=>!b.hidden),c=u.interaction;if(ce(u)){let b=r[u.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},k=i.pickers[u.interaction.pickerId]?.options??[];for(let p of y){let d=p.type==="stack"?p.bind?.plan:void 0;d&&k.includes(d)&&!b.ids.includes(d)&&b.ids.push(d),d&&p.id===n[u.id]&&b.remembered.push(d)}let m=u.children[u.interaction.defaultIndex];m?.type==="stack"&&!m.hidden&&m.bind?.plan&&b.defaults.push(m.bind.plan)}if(c?.type==="tabs"){let b=y.find(k=>k.id===n[u.id])??u.children[c.defaultIndex];b&&o(b)}else if(c?.type==="toggle"){let b=typeof n[u.id]=="boolean"?n[u.id]:c.defaultEnabled,k=u.children[b?0:1];k&&o(k)}else y.forEach(o)}let a=typeof n.__page=="string"?n.__page:t.initialPageId??t.pages[0]?.id,s=t.pages.find(u=>u.id===a);s&&o(s.root);let l={};for(let[u,y]of Object.entries(r)){let c=n[u],b=y.remembered[0]??(y.ids.includes(i.pickers[u]?.selected??"")?i.pickers[u]?.selected:y.defaults[0]);l[u]=typeof c=="string"?y.ids.includes(c)?c:"":b&&y.ids.includes(b)?b:""}for(let u of Object.keys(le(t)))l[u]??="";return l}var ue=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),me=e.strictObject({tiers:e.array(e.strictObject({id:ue,name:e.string().trim().min(1).max(80)})).min(1).max(8),assignments:e.array(e.strictObject({productVersionId:e.string().min(1).max(200),tierId:ue,period:e.enum(["month","year"])})).max(20)}).superRefine((t,n)=>{let i=t.tiers.map(r=>r.id);(new Set(i).size!==i.length||new Set(t.assignments.map(r=>r.productVersionId)).size!==t.assignments.length||new Set(t.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==t.assignments.length||t.assignments.some(r=>!i.includes(r.tierId)))&&n.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function fe(t,n){return t.assignments.length===n.length&&t.assignments.every(i=>n.includes(i.productVersionId))}function Jt(t){let n=Z(t).map(i=>`未知变量:${i}`);for(let i=0;i<t.length;i++){if(t[i]!=="<"||!/[A-Za-z!/?{]/.test(t[i+1]??""))continue;let r=i;if(t.startsWith("<!--",i)){let o=t.indexOf("-->",i+4);i=o<0?t.length:o+2}else{let o="";for(i++;i<t.length;i++){let a=t[i];if(o)a===o&&(o="");else if(a==='"'||a==="'")o=a;else if(a===">")break}}/\{\{|\}\}/.test(t.slice(r,i+1))&&n.push("变量只能放在 HTML 文字中,不能放入标签、属性或注释")}return[...new Set(n)]}var h={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},ge=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),S=e.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(t=>!ge.has(t),"Reserved UI identifier"),B=e.union([e.string().max(2e3),e.number().finite(),e.boolean(),e.null()]),Ae=e.discriminatedUnion("type",[e.strictObject({type:e.literal("enum"),values:e.array(B).min(1).max(h.enumValues),default:B}),e.strictObject({type:e.literal("number"),min:e.number().finite(),max:e.number().finite(),step:e.number().finite().positive(),default:e.number().finite()}),e.strictObject({type:e.literal("text"),maxLength:e.number().int().min(0).max(2e3),default:e.string().max(2e3).nullable()}),e.strictObject({type:e.literal("boolean"),default:e.boolean()})]);function D(t,n){if(t.type==="enum")return t.values.some(r=>r===n);if(t.type==="boolean")return typeof n=="boolean";if(t.type==="text")return n===null||typeof n=="string"&&n.length<=t.maxLength;if(typeof n!="number"||!Number.isFinite(n)||n<t.min||n>t.max)return!1;let i=(n-t.min)/t.step;return Number.isFinite(i)&&Math.abs(i-Math.round(i))<=Math.min(1e-7,Math.max(1,Math.abs(i))*Number.EPSILON*8)}var Ce=Ae.superRefine((t,n)=>{t.type==="enum"&&new Set(t.values).size!==t.values.length&&n.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),t.type==="number"&&t.min>t.max&&n.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),D(t,t.default)||n.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),$e=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function Ue(t,n){return t==="now"?n===0:t==="concat"?!0:t==="lookup"?n>=4&&n%2===0:t==="if"?n===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(t)?n===2:["round","floor","not","number","parse_number","money","duration"].includes(t)?n===1:n>=1}var N=e.lazy(()=>e.union([B,e.strictObject({ref:S}),e.strictObject({op:e.enum($e),args:e.array(N).max(h.expressionNodes)}).superRefine((t,n)=>{Ue(t.op,t.args.length)||n.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function j(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let n=Object.getPrototypeOf(t);return n===null||n===Object.prototype}function _(t,n,i){if(!t||typeof t!="object")return!0;if(!j(t))return n.addIssue({code:"custom",path:i,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(t)){if(ge.has(r))return n.addIssue({code:"custom",path:[...i,r],message:"Reserved UI object key"}),!1;let o=Object.getOwnPropertyDescriptor(t,r);if(o&&!Object.hasOwn(o,"value"))return n.addIssue({code:"custom",path:[...i,r],message:"UI objects cannot contain accessors"}),!1}return!0}function O(t,n,i,r){let o=[{value:t,depth:1,path:i}];for(;o.length;){let a=o.pop();if(++r.nodes>h.expressionNodes||a.depth>h.depth){n.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!_(a.value,n,a.path))return;if(j(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>h.expressionNodes){n.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let s=a.value.args.length-1;s>=0;s--)o.push({value:a.value.args[s],depth:a.depth+1,path:[...a.path,"args",s]})}}}var en=e.unknown().superRefine((t,n)=>{O(t,n,[],{nodes:0})}).pipe(N),Q=e.record(S,N).refine(t=>Object.keys(t).length>0&&Object.keys(t).length<=h.state,"UI assignments need 1–32 state keys"),Le=e.strictObject({target:S,property:e.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:N,className:S.optional()}).superRefine((t,n)=>{t.property==="class"!=(t.className!==void 0)&&n.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),Te=e.discriminatedUnion("type",[e.strictObject({type:e.literal("scroll_latch"),target:S,state:S}),e.strictObject({type:e.literal("input"),target:S,state:S,set:Q.optional()}),e.strictObject({type:e.literal("action"),target:S,set:Q}),e.strictObject({type:e.literal("carousel"),target:S,state:S,initialIndex:e.number().int().nonnegative().optional(),maxWidth:e.number().int().min(1).max(1e4).optional(),previousTarget:S.optional(),nextTarget:S.optional(),inactiveTargets:e.array(S).max(20).optional(),inactiveMaxWidth:e.number().int().min(1).max(1e4).optional()})]),De=e.strictObject({afterMs:e.number().int().min(0).max(6e4),set:Q}),Re=e.strictObject({type:e.literal("mosaic_waves"),target:S,color:e.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:e.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:N.optional(),speed:e.number().min(0).max(4).optional(),pitch:e.number().min(.05).max(4).optional(),fill:e.number().min(.05).max(1).optional(),feather:e.number().min(0).max(1).optional(),warp:e.number().min(0).max(4).optional(),warpScale:e.number().min(0).max(32).optional(),detailScale:e.number().min(0).max(32).optional(),waveScale:e.number().min(0).max(32).optional(),falloff:e.number().min(.1).max(32).optional(),brightness:e.number().min(0).max(32).optional(),ambient:e.number().min(0).max(1).optional(),gamma:e.number().min(.05).max(8).optional(),vignette:e.number().min(0).max(1).optional(),opacity:e.number().min(0).max(1).optional()}),Ee=e.strictObject({type:e.literal("number_counter"),target:S,value:N,prefix:e.string().max(20).optional(),format:e.enum(["number","short"]).optional()}),Ve=e.strictObject({state:e.record(S,Ce).refine(t=>Object.keys(t).length<=h.state,"Too many UI state keys").optional(),derived:e.record(S,N).refine(t=>Object.keys(t).length<=h.derived,"Too many UI derived keys").optional(),bindings:e.array(Le).max(h.bindings).optional(),controls:e.array(Te).max(h.controls).optional(),timers:e.array(De).max(h.timers).optional(),effects:e.array(e.discriminatedUnion("type",[Re,Ee])).max(h.effects).optional(),clock:e.boolean().optional()});function Me(t,n){if(!_(t,n,[])||!j(t))return;for(let[r,o]of[["state",h.state],["derived",h.derived]]){let a=t[r];if(!_(a,n,[r]))return;if(j(a)&&Object.keys(a).length>o){n.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,o]of[["bindings",h.bindings],["controls",h.controls],["timers",h.timers],["effects",h.effects]])if(Array.isArray(t[r])&&t[r].length>o){n.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(t.effects)){for(let[r,o]of t.effects.entries())if(!_(o,n,["effects",r]))return}if(j(t.state))for(let[r,o]of Object.entries(t.state)){if(!_(o,n,["state",r]))return;if(j(o)&&Array.isArray(o.values)&&o.values.length>h.enumValues){n.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let i={nodes:0};if(j(t.derived))for(let[r,o]of Object.entries(t.derived))O(o,n,["derived",r],i);for(let r of["bindings","controls","timers"]){let o=t[r];if(Array.isArray(o)){for(let[a,s]of o.entries())if(!(!_(s,n,[r,a])||!j(s))){if(r==="bindings")O(s.expression,n,[r,a,"expression"],i);else if(_(s.set,n,[r,a,"set"])&&j(s.set)){if(Object.keys(s.set).length>h.state){n.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[l,u]of Object.entries(s.set))O(u,n,[r,a,"set",l],i)}if(i.nodes>h.expressionNodes)return}}}if(Array.isArray(t.effects))for(let[r,o]of t.effects.entries())j(o)&&o.type==="number_counter"?O(o.value,n,["effects",r,"value"],i):j(o)&&o.enabled!==void 0&&O(o.enabled,n,["effects",r,"enabled"],i)}function de(t){let n=[],i=[t];for(;i.length;){let r=i.pop();!r||typeof r!="object"||("ref"in r?n.push(r.ref):i.push(...r.args))}return n}var be=e.unknown().superRefine(Me).pipe(Ve).superRefine((t,n)=>{let i=t.state??{},r=t.derived??{},o=new Set([...Object.keys(i),...Object.keys(r)]),a=(m,p)=>{for(let d of de(m))o.has(d)||n.addIssue({code:"custom",path:p,message:`Unknown UI reference: ${d}`})};for(let[m,p]of Object.entries(t.derived??{}))Object.hasOwn(i,m)&&n.addIssue({code:"custom",path:["derived",m],message:"UI state and derived identifiers must be distinct"}),a(p,["derived",m]);let s=new Set,l=new Set,u=m=>{if(s.has(m))return!1;if(l.has(m))return!0;s.add(m);for(let p of de(r[m]))if(Object.hasOwn(r,p)&&!u(p))return!1;return s.delete(m),l.add(m),!0};for(let m of Object.keys(r))if(!u(m)){n.addIssue({code:"custom",path:["derived",m],message:"Cyclic UI derived references"});break}for(let[m,p]of(t.bindings??[]).entries())a(p.expression,["bindings",m,"expression"]);let y=new Set;for(let[m,p]of(t.effects??[]).entries())y.has(p.target)&&n.addIssue({code:"custom",path:["effects",m,"target"],message:"Effect targets must be unique"}),y.add(p.target),p.type==="number_counter"?(a(p.value,["effects",m,"value"]),typeof p.value=="number"&&Math.abs(p.value)>1e12&&n.addIssue({code:"custom",path:["effects",m,"value"],message:"Counter values must be within the display bound"})):p.enabled!==void 0&&a(p.enabled,["effects",m,"enabled"]);let c=(m,p)=>{for(let[d,v]of Object.entries(m))Object.hasOwn(i,d)||n.addIssue({code:"custom",path:[...p,d],message:"UI assignments can only update declared state"}),a(v,[...p,d])},b=new Set,k=new Set;for(let[m,p]of(t.controls??[]).entries()){if(p.type==="carousel"&&p.inactiveMaxWidth!==void 0&&p.inactiveTargets===void 0&&n.addIssue({code:"custom",path:["controls",m,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),p.type==="carousel")for(let d of p.inactiveTargets??[])(d===p.target||k.has(d))&&n.addIssue({code:"custom",path:["controls",m,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),k.add(d);if(p.type==="carousel")for(let d of["previousTarget","nextTarget"]){let v=p[d];v!==void 0&&((v===p.target||b.has(v)||(t.controls??[]).some(ze=>ze.target===v))&&n.addIssue({code:"custom",path:["controls",m,d],message:"Carousel navigation needs a distinct, exclusive button target"}),b.add(v))}if(p.type!=="action"){let d=Object.hasOwn(i,p.state)?i[p.state]:void 0;(!d||p.type==="input"&&d.type==="enum"&&d.values.some(v=>typeof v!="string"))&&n.addIssue({code:"custom",path:["controls",m,"state"],message:"Control needs a supported declared UI state"}),p.type==="carousel"&&(d?.type!=="number"||!Number.isInteger(d.min)||d.min<0||!Number.isInteger(d.max)||d.step!==1||p.initialIndex!==void 0&&!D(d,p.initialIndex))&&n.addIssue({code:"custom",path:["controls",m],message:"Carousel needs bounded nonnegative integer index state"}),p.type==="scroll_latch"&&d?.type!=="boolean"&&n.addIssue({code:"custom",path:["controls",m,"state"],message:"Scroll latches require boolean UI state"})}(p.type==="input"||p.type==="action")&&p.set&&c(p.set,["controls",m,"set"])}for(let[m,p]of(t.timers??[]).entries())c(p.set,["timers",m,"set"])});var he=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,A=e.string().max(16).regex(he,"语言代码格式不正确,例如 zh-CN、en").refine(t=>{try{return Intl.getCanonicalLocales(t)[0]===t}catch{return!1}},"持久化语言代码必须使用规范写法");function F(t){if(typeof t!="string")return null;try{let n=Intl.getCanonicalLocales(t.trim().replaceAll("_","-"))[0];if(!n)return null;let{language:i,script:r,region:o}=new Intl.Locale(n),a=[i,r,o].filter(Boolean).join("-");return he.test(a)?a:null}catch{return null}}var Ze=new Set(["TW","HK","MO"]);function ye(t){let[n,i,r]=t.split("-");if(n!=="zh")return`${n}-${new Intl.Locale(t).maximize().script??""}`;let o=i?.length===4?i:void 0,a=i?.length===4?r:i;return o?`zh-${o}`:a&&Ze.has(a)?"zh-Hant":"zh-Hans"}function xe(t,n,i){let r=n.map(o=>({code:A.parse(o),normalized:o}));for(let o of t){let a=F(o);if(!a)continue;let s=r.find(c=>c.normalized===a);if(s)return s.code;let l=ye(a),u=r.filter(c=>ye(c.normalized)===l),y=u.find(c=>!c.normalized.includes("-")||c.normalized===l)??u[0];if(y)return y.code}return i}var Be=4,z={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},U=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),g=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Qe=e.enum(["none","xs","sm","md","lg","xl"]),Fe=e.enum(["none","sm","md","lg","full"]),H=e.string().regex(/^#[0-9a-fA-F]{6}$/),G=e.string().max(2048).refine(t=>{try{let n=new URL(t);return n.protocol==="https:"&&n.hostname.length>0}catch{return!1}},"只支持 https 链接"),q=e.union([G,e.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),e.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),e.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Se=e.object({primary:H,background:H,text:H,radius:Fe,font:e.enum(["system","serif","rounded","mono"]),fontAssets:e.object({family:e.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:e.array(e.object({url:G,weight:e.number().int().min(100).max(900).multipleOf(100),family:e.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),L=e.union([e.enum(["primary","text","muted","background","surface"]),e.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),f=(t,n)=>e.number().int().min(t).max(n),ke=e.union([e.enum(["fit","fill"]),f(1,1200)]),He=e.object({top:f(0,200),right:f(0,200),bottom:f(0,200),left:f(0,200)}).strict(),qe=e.object({top:f(-100,200),right:f(-100,200),bottom:f(-100,200),left:f(-100,200)}).strict(),Ie=e.object({x:f(0,100),y:f(0,100)}).strict(),Ge=e.discriminatedUnion("type",[e.object({type:e.literal("color"),color:L}).strict(),e.object({type:e.literal("linear"),angle:f(0,360),stops:e.array(e.object({color:L,at:f(0,100)}).strict()).min(2).max(4)}).strict(),e.object({type:e.literal("image"),src:q,fit:e.enum(["cover","contain"]),position:Ie.optional()}).strict()]),We=e.discriminatedUnion("type",[e.object({type:e.literal("rect"),radius:e.union([f(0,200),e.object({topLeft:f(0,200),topRight:f(0,200),bottomRight:f(0,200),bottomLeft:f(0,200)}).strict()])}).strict(),e.object({type:e.literal("pill")}).strict()]),Ke=e.object({width:f(0,12),color:L,style:e.enum(["solid","dashed"])}).strict(),Je=e.object({x:f(-40,40),y:f(-40,40),blur:f(0,80),spread:f(-20,40),color:L}).strict(),Xe=e.object({font:e.enum(["system","serif","rounded","mono"]),size:f(8,96),weight:e.number().int().min(100).max(900).multipleOf(100),lineHeight:e.number().min(.8).max(3),letterSpacing:e.number().min(-5).max(20),color:L,align:e.enum(["start","center","end"]),italic:e.boolean(),decoration:e.enum(["none","underline","line-through"]),transform:e.enum(["none","uppercase"])}).strict().partial(),P=e.object({width:ke,height:ke,padding:He,margin:qe,gap:f(0,120),grow:e.union([e.boolean(),e.number().min(0).max(12)]),background:Ge,opacity:e.number().min(0).max(1),clipContent:e.boolean(),shape:We,border:Ke,shadow:Je,text:Xe}).strict().partial(),I={id:U,name:e.string().trim().min(1).max(60).optional(),hidden:e.boolean().optional(),style:P.optional(),fallback:g.optional()},Ye=e.object({...I,type:e.literal("text"),productField:e.enum(["name","price","trial","period"]).optional(),feature:e.object({id:e.uuid(),field:e.enum(["name","allowance"])}).strict().optional(),text:g,variant:e.enum(["title","heading","body","caption"])}).strict(),et=e.object({...I,type:e.literal("image"),src:q,localizedSrc:e.record(A,q).optional(),alt:g,aspect:e.enum(["auto","1:1","4:3","16:9","3:1"]),fit:e.enum(["cover","contain"]),position:Ie.optional()}).strict(),tt=e.object({...I,type:e.literal("button"),label:g,variant:e.enum(["primary","secondary","link"]),action:g,purpose:e.enum(["purchase","navigation","close"]).optional(),bind:T.optional()}).strict(),nt=e.object({...I,type:e.literal("divider")}).strict(),rt=e.object({...I,type:e.literal("customer_data"),title:g,data:ae}).strict(),it=e.object({...I,type:e.literal("spacer"),size:Qe}).strict(),ot=e.object({...I,type:e.literal("custom_html"),html:e.record(A,e.string().max(z.customHtml)),css:e.string().max(z.customCss),ui:be.optional()}).strict(),at=e.object({...I,type:e.literal("price"),fallback:g,parts:e.object({current:P.optional(),original:P.optional(),period:P.optional()}).strict().optional()}).strict(),st=e.object({...I,type:e.literal("coupon_code"),label:g,fallback:g}).strict(),ct=e.object({...I,type:e.literal("countdown"),source:e.enum(["offer.ends_at","offer.expires_at","fixed"]),at:e.iso.datetime().optional(),granularity:e.enum(["day","hour","minute","second"]),expired:g,fallback:g}).strict().refine(t=>t.source!=="fixed"||!!t.at,"固定倒计时需要结束时间"),lt=e.object({...I,type:e.literal("plan_picker"),label:g,fallback:g,planIds:e.array(e.string().min(1).max(200)).min(1).max(20).refine(t=>new Set(t).size===t.length,"套餐不能重复").optional(),defaultPlan:e.string().min(1).max(200).optional(),grouping:me.safeExtend({monthLabel:g,yearLabel:g,unavailableLabel:g}).optional(),states:e.object({selected:P.optional()}).strict().optional()}).strict().superRefine((t,n)=>{t.grouping&&(!t.planIds||!fe(t.grouping,t.planIds))&&n.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),pt=e.object({...I,type:e.literal("quantity_picker"),bind:T.optional(),label:g,fallback:g,internalFeatureId:e.uuid(),minimumQuantity:f(0,1e4),maximumQuantity:f(0,1e4),defaultQuantity:f(0,1e4),step:f(1,1e4)}).strict().refine(t=>t.minimumQuantity<=t.defaultQuantity&&t.defaultQuantity<=t.maximumQuantity&&(t.defaultQuantity-t.minimumQuantity)%t.step===0,"Quantity controls require a Product binding and valid bounds"),ut=e.discriminatedUnion("type",[e.object({type:e.literal("input"),label:g,keyboard:e.enum(["text","email","tel","url"]),maxLength:f(1,500)}).strict(),e.object({type:e.literal("multiselect"),label:g,min:f(0,50),max:f(1,50)}).strict(),e.object({type:e.literal("select"),label:g,defaultIndex:f(0,49),purpose:e.enum(["option","product","tier"]).optional(),pickerId:U.optional(),selectedStyle:P.optional()}).strict(),e.object({type:e.literal("tabs"),label:g,defaultIndex:f(0,49),purpose:e.literal("tier").optional()}).strict(),e.object({type:e.literal("toggle"),label:g,defaultEnabled:e.boolean()}).strict(),e.object({type:e.literal("carousel"),label:g}).strict()]),w={...I,type:e.literal("stack"),direction:e.enum(["vertical","horizontal","overlay"]),align:e.enum(["start","center","end","stretch"]),justify:e.enum(["start","center","end","between"]),productSlot:e.object({index:f(0,19),period:e.enum(["month","year"]).optional(),requireBinding:e.boolean().optional()}).strict().optional(),interaction:ut.optional(),states:e.object({selected:P.optional()}).strict().optional(),purpose:e.literal("benefits").optional(),purchaseAction:g.optional(),buttonVariant:e.enum(["primary","secondary","link"]).optional(),bind:T.optional()},je=e.lazy(()=>e.object({...I,type:w.type,direction:w.direction,align:w.align,justify:w.justify,children:e.array(mt).max(z.children),productSlot:w.productSlot,interaction:w.interaction,states:w.states,purpose:w.purpose,purchaseAction:w.purchaseAction,buttonVariant:w.buttonVariant,bind:w.bind}).strict()),mt=e.lazy(()=>e.union([je,Ye,et,tt,nt,it,ot,at,st,ct,lt,pt,rt])),ft=e.union([e.string().max(500),e.number().finite(),e.boolean(),e.null()]),$={id:g,event:g,properties:e.record(g,ft).refine(t=>Object.keys(t).length<=20,"最多 20 个参数")},dt=e.discriminatedUnion("type",[e.object({...$,type:e.literal("navigate"),close:e.literal(!1),pageId:U}).strict(),e.object({...$,type:e.literal("event"),close:e.boolean()}).strict(),e.object({...$,type:e.literal("close"),close:e.literal(!0)}).strict(),e.object({...$,type:e.literal("open_url"),close:e.boolean(),url:G}).strict(),e.object({...$,type:e.literal("claim_offer"),close:e.boolean(),couponId:e.uuid()}).strict()]),gt=e.object({defaultLocale:A,locales:e.record(A,e.record(g,e.string().max(z.stringLength)))}).strict(),bt=e.enum(["popup","paywall","onboarding","page","banner"]);var yt=e.object({kind:e.literal("screen"),schemaVersion:e.literal(Be),name:e.string().trim().min(1).max(80),surface:bt,initialPageId:U.optional(),presentation:X,theme:Se,pages:e.array(e.object({id:U,name:e.string().trim().min(1).max(60),root:je,theme:Se.optional(),editorPosition:e.object({x:e.number().finite().min(-1e5).max(1e5),y:e.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:gt,actions:e.array(dt).max(z.actions)}).strict();function R(t,n){for(let i of t.pages)W(i.root,n)}var dn=yt.superRefine((t,n)=>{let i=z;t.surface!=="paywall"&&t.pages.length!==1&&n.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),t.initialPageId&&!t.pages.some(c=>c.id===t.initialPageId)&&n.addIssue({code:"custom",message:"Initial screen does not exist"});for(let c of t.actions)c.type==="navigate"&&(t.surface!=="paywall"||!t.pages.some(b=>b.id===c.pageId))&&n.addIssue({code:"custom",message:"Navigation screen does not exist"});t.pages.length>i.pages&&n.addIssue({code:"custom",message:`页面最多 ${i.pages} 个`}),t.actions.length>i.actions&&n.addIssue({code:"custom",message:`动作最多 ${i.actions} 个`});let r=c=>n.addIssue({code:"custom",message:c}),o=Object.keys(t.strings.locales);o.includes(t.strings.defaultLocale)||r("默认语言必须在语言列表里"),o.length>z.locales&&r(`最多 ${z.locales} 种语言`);let a=new Set;for(let c of t.actions)a.has(c.id)&&r(`动作标识重复:${c.id}`),a.add(c.id);let s=new Set;for(let c of t.pages)["next","back"].includes(c.id)&&r(`页面 id 不能使用保留名称:${c.id}`),s.has(c.id)&&r(`页面 id 重复:${c.id}`),s.add(c.id);let l=new Set,u=0,y=!1;R(t,(c,b)=>{if(u++,b>z.depth&&(y=!0),l.has(c.id)&&r(`组件 id 重复:${c.id}`),l.add(c.id),c.type==="button"&&!a.has(c.action)&&r(`按钮 ${c.id} 引用的动作不存在:${c.action}`),c.type==="custom_html")for(let k of Object.keys(c.html))o.includes(k)||r(`自定义 HTML ${c.id} 含有未启用的语言:${k}`);if(c.type==="image")for(let k of Object.keys(c.localizedSrc??{}))o.includes(k)||r(`图片 ${c.id} 含有未启用的语言:${k}`)}),u>i.nodes&&r(`组件最多 ${i.nodes} 个`),y&&r(`层级最多 ${z.depth} 层`)});function W(t,n,i=1,r=null){if(n(t,i,r)!==!1&&t.type==="stack")for(let o of t.children)W(o,n,i+1,t)}function we(t){let n=[],i=new Set;return R(t,r=>{let o=(a,s,l)=>{i.has(a)||(i.add(a),n.push({key:a,nodeId:r.id,nodeType:r.type,field:s,required:l}))};r.type==="stack"&&r.interaction&&o(r.interaction.label,"label",!0),r.fallback&&o(r.fallback,"text",!0),r.type==="text"&&o(r.text,"text",!0),r.type==="customer_data"&&o(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&o(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(o(r.grouping.monthLabel,"label",!0),o(r.grouping.yearLabel,"label",!0),o(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&o(r.expired,"text",!0),r.type==="button"&&o(r.label,"label",!0),r.type==="image"&&(o(`image:${r.id}`,"src",!1),o(r.alt,"alt",!1)),r.type==="custom_html"&&o(`html:${r.id}`,"html",!0)}),n}function ht(t,n,i){if(n.field==="html"){let r;return R(t,o=>{o.id===n.nodeId&&o.type==="custom_html"&&(r=o.html[i])}),r}if(n.field==="src"){let r=It(t,n.nodeId);return r?.type==="image"?r.localizedSrc?.[i]??(i===t.strings.defaultLocale?r.src:void 0):void 0}return t.strings.locales[i]?.[n.key]}function xt(t){let n=we(t).filter(r=>r.required);return Object.keys(t.strings.locales).sort((r,o)=>r===t.strings.defaultLocale?-1:o===t.strings.defaultLocale?1:0).map(r=>{let o=n.filter(a=>!ht(t,a,r)?.trim()).map(a=>a.key);return{locale:r,total:n.length,filled:n.length-o.length,missing:o,complete:o.length===0}})}function St(t){return xt(t).filter(n=>n.complete||n.locale===t.strings.defaultLocale).map(n=>n.locale)}function gn(t,n){return xe(n,St(t),t.strings.defaultLocale)}function bn(t,n){let i=t.strings.locales[n]??{},r=t.strings.locales[t.strings.defaultLocale]??{},o={};for(let s of we(t)){if(s.field==="html"||s.field==="src")continue;let l=i[s.key]?.trim()?i[s.key]:r[s.key];l!==void 0&&(o[s.key]=l)}let a=s=>{if(s.type==="stack")return{...s,children:s.children.map(a)};if(s.type==="custom_html"){let l=s.html[n]?.trim()?s.html[n]:s.html[t.strings.defaultLocale];return{...s,html:l===void 0?{}:{[n]:l}}}if(s.type==="image"){let{localizedSrc:l,...u}=s;return{...u,src:l?.[n]??l?.[t.strings.defaultLocale]??s.src}}return s};return{...t,pages:t.pages.map(s=>({...s,root:a(s.root)})),strings:{defaultLocale:n,locales:{[n]:o}}}}function kt(t,n){let i=null;return W(t,r=>{if(i)return!1;r.id===n&&(i=r)}),i}function It(t,n){for(let i of t.pages){let r=kt(i.root,n);if(r)return r}return null}function yn(t){let n=F(t)?.split("-")[0];return n!==void 0&&["ar","he","fa","ur"].includes(n)}function hn(t,n,i){let r={};if(!n||typeof n!="object"||Array.isArray(n))return r;let o=n;if(R(t,a=>{if(a.type==="quantity_picker"){let l=o[a.id];typeof l=="number"&&Number.isSafeInteger(l)&&l>=a.minimumQuantity&&l<=a.maximumQuantity&&(l-a.minimumQuantity)%a.step===0&&(r[a.id]=l);return}if(a.type==="plan_picker"){let l=o[a.id];typeof l=="string"&&(r[a.id]=i?.pickers[a.id]?.options.includes(l)?l:"");return}if(a.type==="custom_html"&&a.ui)for(let[l,u]of Object.entries(a.ui.state??{})){let y=`${a.id}.${l}`,c=o[y];c!==null&&D(u,c)&&(r[y]=c)}if(a.type!=="stack"||!a.interaction)return;let s=Object.hasOwn(o,a.id)?o[a.id]:void 0;["select","tabs"].includes(a.interaction.type)&&typeof s=="string"&&a.children.some(l=>l.id===s)&&(r[a.id]=s),a.interaction.type==="toggle"&&typeof s=="boolean"&&(r[a.id]=s)}),t.surface==="paywall"&&typeof o.__page=="string"&&t.pages.some(a=>a.id===o.__page)&&(r.__page=o.__page),i){let a={...r};for(let[s,l]of Object.entries(o))(typeof l=="string"||typeof l=="boolean")&&(a[s]=l);Object.assign(r,pe(t,a,i))}return r}export{V as a,wt as b,te as c,Ot as d,ne as e,re as f,Et as g,ie as h,Vt as i,le as j,me as k,fe as l,Qt as m,Ft as n,Jt as o,A as p,F as q,z as r,U as s,g as t,q as u,R as v,dn as w,W as x,we as y,xt as z,gn as A,bn as B,It as C,yn as D,hn as E};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as gn,c as bn,d as Tt,f as Ot,g as Cn,k as vn}from"./chunk-OQ2E3JLZ.js";import{a as un,b as ze}from"./chunk-W32FI2A2.js";import{d as dn,e as fn,f as pn,g as hn,i as St,j as it,k as mn,l as yn,m as wn}from"./chunk-LENTXDGK.js";import{a as on,c as xt,d as sn,e as ln}from"./chunk-ADTZEBQF.js";import{a as rt,b as ae,d as Rt,f as At,j as cn}from"./chunk-OV46DXRX.js";import{b as Ie}from"./chunk-M4P6TGBU.js";import{B as N,C as nt,D as Ge,E as De,y as an}from"./chunk-GGZG56GR.js";import{r as Le,t as _e}from"./chunk-QGKROSRD.js";import{i as rn}from"./chunk-RRZZUIFM.js";import{c as ge,j as We}from"./chunk-RJT764B2.js";import{c as Et}from"./chunk-BKBWGPNR.js";import{a as k}from"./chunk-WE55LJEN.js";import{a as G}from"./chunk-DSPLGTQI.js";async function Pn($,a,E){if(!Ge(a))throw new k("INVALID_RESPONSE","A verified completed purchase is required");let T=$?We.parse($):null;if(await E.onComplete?.(a),!T||!E.check)return;let j=We.parse(await E.check());if(j.internal_feature_id!==T.internal_feature_id||j.quantity!==T.quantity||T.observation!==void 0&&(j.observation===void 0||j.observation.requirementDigest!==T.observation.requirementDigest||j.observation.authority!==T.observation.authority||Et(j.observation.subject)!==Et(T.observation.subject)))throw new k("INVALID_RESPONSE","The access requirement changed");j.allowed&&await E.onAccessGranted?.(j)}function kn($){return Object.entries($.document.buttons).filter(([,a])=>a.type==="checkout"&&a.product.type==="fixed"&&!Ie(a.product,{},$.capabilities)).map(([a])=>a)}function In($,a){let E=N(a)?void 0:a.lines[0];if(!N(a)&&(a.lines.length!==1||!E))return;let T=N(a)?a.productVersionId:E.productVersionId,{screen:j,buttons:oe}=$.document,D=new Map(N(a)?Object.entries(a.featureQuantities??{}):(E?.prepaid??[]).map(b=>[b.internal_feature_id,b.quantity]));function se(b,c){if(b.hidden)return!1;if(b.type==="plan_picker"&&$.capabilities.pickers[b.id]?.options.includes(T))return c[b.id]=T,!0;if(b.type==="quantity_picker"){let te=D.get(b.internalFeatureId);return te!==void 0&&(!b.bind?.plan||b.bind.plan===T)&&(c[b.id]=te),!1}if(b.type==="button"&&b.action){let te=oe[b.action];return te?.type==="checkout"&&te.product.type==="fixed"&&te.product.productVersionId===T}if(b.type!=="stack")return!1;let ee=b.interaction,i=b.bind?.plan===T;for(let[te,p]of b.children.entries()){let ne={},L=se(p,ne);if(ee?.type==="toggle"||ee?.type==="tabs"){if(!L)continue;return c[b.id]=ee.type==="toggle"?te===0:p.id,Object.assign(c,ne),!0}Object.assign(c,ne),L&&(i=!0,ee?.type==="select"&&ee.purpose==="product"&&ee.pickerId&&p.type==="stack"&&p.bind?.plan===T&&(c[b.id]=p.id,c[ee.pickerId]=T))}return i}for(let b of j.pages){let c={__page:b.id};if(se(b.root,c))return c}}async function dr($,a,E){let T=a.focusAtReveal?()=>{}:St($.ownerDocument),j=()=>{D.finish("dismissed"),T()},oe=()=>j(),D=mn($,a,"paywall",()=>{j(),G(a.onDismiss)},gn);a.signal?.throwIfAborted(),a.signal?.addEventListener("abort",oe,{once:!0});let se=null,b,c,ee;try{if(D.start(!0,a.loadingDocument?.screen.strings.defaultLocale,a.loadingDocument??null),D.cancelled)throw new DOMException("Presentation cancelled","AbortError");if(se=a.check?We.parse(await D.wait(a.check(),it)):null,se?.allowed)return D.finish("skipped"),a.signal?.removeEventListener("abort",oe),T(),await a.onAccessGranted?.(se),{check:se,host:null};let[e,t]=await Promise.allSettled([D.wait(import("./screen-renderer-XBWES3XN.js")),D.wait(a.start().then(r=>(D.cancelled&&r.destroy(),r)),it)]);if(e.status==="rejected")throw t.status==="fulfilled"&&t.value.destroy(),e.reason;if(t.status==="rejected")throw t.reason;ee=e.value,b=t.value,a.signal?.throwIfAborted(),b.signal?.throwIfAborted(),b.signal?.addEventListener("abort",oe,{once:!0});let n=b.view??await D.wait(b.refresh(),it);if(!n)throw new k("INVALID_RESPONSE","Paywall presentation is missing");b.signal?.throwIfAborted(),c=n}catch(e){throw D.finish("error",e),E?.retainedDialog?.release(),a.signal?.removeEventListener("abort",oe),b?.signal?.removeEventListener("abort",oe),b?.destroy(),T(),e}let i=b,{mountScreenPreview:te}=ee,p=$.ownerDocument,ne=new AbortController,L=p.createElement("section"),pe=p.createElement("div"),F=p.createElement("div"),at=a.mountControls,X=at?p.createElement("div"):void 0,d=p.createElement("p"),h=p.createElement("button"),le=p.createElement("button"),O=p.createElement("button");(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&E?.hostPaywallTarget&&!E.retainedDialog&&c.document.presentation.type==="modal"&&(E.retainedDialog=hn(E.hostPaywallTarget));let ce=E?.retainedDialog,R=ce?.dialog??p.createElement("dialog"),Ue=ce&&c.document.presentation.type==="inline"?{type:"modal",size:"md"}:c.document.presentation,re=Ue.type==="inline"?F:p.createElement("div"),ot=i.locale||c.document.screen.strings.defaultLocale,o=ot.toLowerCase().startsWith("zh"),En=o?"正在处理…":"Processing…",xn=o?"正在准备报价…":"Preparing your price…",U=bn(c.document.screen.theme);L.dataset.indianaPaywall="",L.setAttribute("aria-label",c.document.name),L.style.cssText=U.root,F.style.cssText=U.controls,d.style.cssText=U.message,d.setAttribute("role","status"),O.style.cssText=U.link,O.textContent=o?"关闭":"Close",h.style.cssText=U.secondary,h.textContent=o?"重试":"Retry",h.hidden=!0,le.type="button",le.style.cssText=U.primary,le.textContent=o?"继续付款":"Continue payment",le.hidden=!0,re.append(d,le,h),F.append(O),X&&(X.style.cssText="flex:1 0 100%;min-width:0",X.hidden=!0,F.prepend(X)),re!==F&&(re.dataset.indianaPaywallStatus="",re.style.cssText="display:none;padding:0",L.append(re)),L.append(pe,F);let st=()=>{let e=s=>!s.hidden&&(s!==d||!!d.textContent);if(re!==F&&(re.style.cssText=!ie&&[...re.children].some(e)?`${U.controls};padding:12px 64px 12px 20px;flex-shrink:0`:"display:none;padding:0"),X){let s=!X.childElementCount&&!X.textContent?.trim();X.hidden!==s&&(X.hidden=s)}let t=me??F,n=![...t.children].some(e),r=[...t.children].some(s=>s!==O&&e(s));t.style.cssText=n?U.controls.replace(/padding:[^;]+/,"padding:0"):r?`${U.controls};${U.pinned}`:U.controls,ct()},Nt=typeof MutationObserver>"u"?void 0:new MutationObserver(st);Nt?.observe(L,{attributes:!0,attributeFilter:["hidden"],characterData:!0,childList:!0,subtree:!0});let Rn=Object.entries(c.document.buttons).filter(([,e])=>e.type==="close").map(([e])=>e),H,Dt,Me=!1,Lt=JSON.stringify(c.capabilities),q;function be(e){let t=kn(e);if(q||he&&!fe||Q&&(C||!Re()||ye))return $e(e).map(({actionId:r})=>r);if(mt()||!C&&Re())return t;let n=C?Ht(e):Qt(e);return[...new Set([...t,...$e(e).map(({actionId:r})=>r).filter(r=>!n.includes(r))])]}function Ve(e){if(g)return;let t=c.id!==e.id;c=e;let n=JSON.stringify(e.capabilities);if(t||n!==Lt){let r=!P&&!i.quote&&!i.operation?rt(e,z,Mt):z;t||JSON.stringify(r)!==JSON.stringify(z)?(z=r,H?.update(e.document.screen,ot,{capabilities:ae(e),unavailableActions:be(e),serverInput:{bindings:[],answers:{}},selection:z})):H?.updateCapabilities(ae(e),be(e)),Lt=n}Sn(e),ve()}let _,lt=0;function _t(){return(me??F).getBoundingClientRect().height+(re===F?0:re.getBoundingClientRect().height)}function ct(){let e=p.defaultView;if(!_?.responsive||!e)return;let t=me??F,n=e.innerHeight-(_.type==="modal"?32:0);t.style.maxHeight=`${Math.max(1,n)}px`,t.style.overflowY="auto",t.style.flexShrink="0",lt=Math.max(1,n-_t()),H?.resizeViewport?.(lt,e.innerWidth)}let g=!1,he=!1,P=null,ut,Ye=!1,Ut=!1,Ce=!1,dt,ft=!1,ie,me;function An(){return he||g||ie||ft?{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null}:xt(i)}let I=()=>!g&&!Ye&&!ie&&a.canInteract?.()!==!1,Y,Ee=!1,xe=!1,u=null,ue=null,Ke="",de=()=>a.checkoutNavigation==="after_confirmation"&&!!(a.terminateCheckout||a.resumeCheckout),z={},Mt=new Set,fe,C;function pt(e){return!!e&&N(e)&&e.timing==="immediate"&&e.execution.provider==="merchant"}let ht=o?"正在确认付款…":"Confirming payment…",Q=null,ye,Je,Vt=!1,Re=()=>a.allowNewPurchase!==!1||Vt;function $e(e){return Object.entries(e.document.buttons).flatMap(([t,n])=>n.type==="checkout"?[{actionId:t,policy:n}]:[])}function $t(e){let t=C?.quote;return t?$e(e).filter(({actionId:n,policy:r})=>Ae(t,e,n,r.product,z)).map(({actionId:n})=>n):[]}function Ht(e){return C?.phase==="payment"?$t(e):[]}function mt(){return(C?C.phase==="payment":!Re())&&(Re()||!!a.prepareUpgradeReplacement)&&de()&&!!a.terminateCheckout&&!!i.quote&&i.canReselect===!1&&!!i.operation&&x(i.operation).type==="checkout"}function Qt(e){let t=i.quote;return!de()||Q||!t||!i.operation||x(i.operation).type!=="checkout"?[]:$e(e).filter(({actionId:n,policy:r})=>Ae(t,e,n,r.product,z)).map(({actionId:n})=>n)}function ve(){let e=q?[]:C?Ht(c):Qt(c),t=a.allowNewPurchase===!1&&!!i.operation&&x(i.operation).type==="checkout";if(le.hidden=!!q||(C?C.phase!=="payment":!t)||e.length>0,!de()&&!C||!H?.updateCheckoutControls)return;let n=!q&&C?.phase==="checking"?fe:void 0;H.updateCheckoutControls({actions:$e(c).map(({actionId:r})=>r),resume:n?[n]:e,resumeLabel:n?ht:o?"继续付款":C?"Continue payment":"Continue checkout",busy:fe})}function Bt(){ue?.remove(),ue=null}async function Xe(){if(Q)return;if(a.resumeCheckout&&i.operation){let t=i.operation.operationId;try{await a.resumeCheckout(t)}catch(n){if(!(n instanceof k&&n.code==="PURCHASE_PENDING"))throw n;let r=await i.read();if(!I())return;if(r.operationId!==t||x(r).type==="checkout")throw n;await M(r,!1)}return}let e=await i.read();if(x(e).type!=="checkout")return M(e,!1);I()&&(He.delete(e.operationId),await Qe(e))}function yt(){ye?.destroy(),ye=void 0,Je=void 0}function jt(){let e=Q;if(!e||ye)return;let t=o?"仍在核对原订单,暂时无法更换套餐。":"We’re still checking the original purchase before changing plans.",n=Date.now()+6e5,r=un({document:p,delay:()=>Date.now()<n?5e3:void 0,async run(){if(!I())return;let s=await i.read();if(ye!==r||!I())return;if(s.operationId!==e.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");let f=x(s);f.type==="native"?(yt(),d.textContent=o?"原订单已关闭。你可以继续更换套餐。":"The original checkout is closed. You can continue changing plans.",h.textContent=o?"继续更换套餐":"Continue changing plans",u=()=>Ze(),h.hidden=!1):(f.type==="complete"||f.type==="fulfillment"||f.type==="recording")&&(yt(),Q=null,h.hidden=!0,await M(s,!1))}});ye=r,Je=async()=>{try{await r.refresh()}finally{ye===r&&(d.textContent=t,h.hidden=!1)}},u=Je,h.textContent=o?"查询结果":"Check result",h.hidden=!1,d.textContent=t,r.schedule()}async function Ze(e=!1){let t=Q;if(!t)return;u=()=>Ze(),C&&(h.textContent=o?"查询状态":"Check status"),h.hidden=!0;let n=Date.now()+2e4;for(;I();){let r=await i.read();if(r.operationId!==t.operationId)throw new k("PURCHASE_PENDING","The original Checkout changed");if(!I())break;let s=x(r);if(s.type==="native"){if(!Re()&&a.prepareUpgradeReplacement){let f=await a.prepareUpgradeReplacement(t.operationId,t.intent);if(!I())return;Vt=!0,Ve(f)}Q=null,C&&Se(C.quote),Bt(),P=t.selection,Y=t.coupon,Ee=!1,xe=!1,await Fe();return}if(s.type==="complete"||s.type==="fulfillment"||s.type==="recording"){Q=null,C?await Pe(C.quote,r):await M(r,!1);return}if(e&&s.type==="checkout"){e=!1;try{await a.terminateCheckout(t.operationId)}catch(f){G(a.onError,f)}}if(Date.now()>=n){C&&s.type==="checkout"&&(Q=null,await Pe(C.quote,r));break}await ze(1e3,p,ne.signal)}!Q||g||(C?(d.textContent=o?"仍在核对原升级单,暂时无法更换套餐。":"We’re still checking the original upgrade before changing plans.",h.hidden=!1):jt())}async function Ft(e,t,n,r){if(u=()=>Ft(e,t,n,r),await a.beforeCheckoutReplacement?.(structuredClone(r)),!I())return;let s=i.operation;if(s?.operationId!==e||x(s).type!=="checkout"){u=null,s&&await M(s,!1);return}Q={operationId:e,selection:t,coupon:n,intent:r},C&&(d.textContent=o?"正在切换套餐…":"Changing plan…",h.hidden=!0);let f=!1;try{await a.terminateCheckout(e)}catch(l){if(l instanceof k&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(l.code)){Q=null,C&&(u=bt,h.textContent=o?"查询状态":"Check status",h.hidden=!1),d.textContent=o?"请继续原订单,或等待它过期后再更换方案。":"Continue your original checkout, or wait for it to expire before changing plans.",G(a.onError,l);return}f=l instanceof k&&(l.status??0)>=500,G(a.onError,l)}I()&&await Ze(f)}function wt(e,t,n,r,s){let f=ae(e).checkoutCoupons?.[t],l=f?f.products[n]:a.claimCoupon&&s?rn(e.capabilities,s,r):void 0;return l?.couponId&&l.planVersionId===n?{id:l.couponId,offerId:l.offerId}:void 0}function Sn(e){he||P||i.quote||i.operation||Ke&&d.textContent===Ke||(d.textContent=Object.values(e.capabilities.plans).some(t=>t.available)?"":o?"当前账号暂无可购买的方案。":"No plans are currently available for this account.")}let He=new Map,et=!1;function Ae(e,t,n,r,s,f){let l=N(e),y=!l&&e.lines.length===1?e.lines[0]:void 0,m=Ie(r,s,t.capabilities);if(!m||m!==(l?e.productVersionId:y?.productVersionId))return!1;let A=wt(t,n,m,s,f),K;try{K=_e(t.document.screen,m,s,t.capabilities)}catch{return!1}if(l){let J=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return Object.keys(K).length===Object.keys(e.featureQuantities??{}).length&&Object.entries(K).every(([Ne,It])=>e.featureQuantities?.[Ne]===It)&&(!A||J?.couponId===A.id&&(!A.offerId||J.grantId===A.offerId))}if((A||ae(t).checkoutCoupons?.[n])&&(A?.id??null)!==(e.discount?.couponId??null))return!1;let Z=Object.fromEntries((y?.prepaid??[]).map(J=>[J.internal_feature_id,J.quantity]));return[...new Set([...Object.keys(K),...Object.keys(Z)])].every(J=>(K[J]??0)===(Z[J]??0))}let x=e=>on({quote:i.quote,operation:e,requestId:null,pending:!1,destroyed:g,canReselect:i.canReselect});async function Qe(e){let t=e.merchantExecution,n=x(e),r=n.type==="checkout"?n.checkoutUrl:e.checkoutUrl;if(!(!I()||!r||nt(e)&&n.type!=="checkout"||a.checkoutNavigation==="after_confirmation"&&n.type!=="checkout"||t?.type==="purchase"&&!["not_started","pending"].includes(t.paymentStatus)||He.get(e.operationId)===r)){He.set(e.operationId,r);try{a.onCheckoutUrl?await a.onCheckoutUrl(r):p.defaultView?.location.assign(r)}catch(s){throw He.delete(e.operationId),s}}}let we=(e,t=!1)=>{if(e instanceof Rt)u=null,d.textContent=e.customerMessage(o);else if(Cn(e))u=null,d.textContent=t?o?"当前无法在此购买,付款尚未开始。请联系商户。":"Purchases aren’t available here right now. Payment hasn’t started. Contact the merchant for help.":Ot(e,o);else if(t){let n=e instanceof k?e.code:void 0;n==="CAPABILITY_UNAVAILABLE"||n==="NOT_CONFIGURED"?(u=null,d.textContent=o?"暂时无法为此套餐报价,付款尚未开始。":"Pricing for this plan is unavailable. Payment hasn’t started."):i.canReselect===!0&&!P?d.textContent=o?"未能取得报价,付款尚未开始。请重新选择套餐。":"We couldn’t prepare your price. Payment hasn’t started. Choose a plan again.":n==="COMMAND_PENDING"?d.textContent=o?"仍在准备报价,请重试以查看结果。":"Your price is still being prepared. Retry to check the result.":d.textContent=o?"未能取得报价,付款尚未开始。请重试。":"We couldn’t prepare your price. Payment hasn’t started. Try again."}else d.textContent=e instanceof k&&(e.code==="NETWORK_ERROR"||e.code==="TIMEOUT")?Ot(e,o):e instanceof k?e.message:o?"操作未完成,请重试。":"This action couldn’t be completed. Try again.";h.hidden=u===null,Ke=d.textContent,t&&fe===void 0&&!_?.responsive&&d.scrollIntoView?.({block:"nearest"}),G(t&&E?.quoteError?E.quoteError:a.onError,e)},Be=new WeakMap;function je(e){he=e,h.disabled=e,le.disabled=e,H?.updateCapabilities?.(ae(c),be(c));for(let t of ue?.querySelectorAll("button")??[])e?(Be.has(t)||Be.set(t,t.disabled),t.disabled=!0):Be.has(t)&&(t.disabled=Be.get(t),Be.delete(t)),Tt(t)}function qt(){q&&(d.textContent=q.message,h.textContent=o?"重试":"Retry",h.disabled=!1,h.hidden=!q.retry,le.disabled=!0)}function gt(){d.textContent=o?"暂时无法操作,请稍后重试。":"This action is unavailable right now. Try again in a moment."}async function Tn(e){if(a.beforeAction)try{await a.beforeAction()}catch(t){throw t instanceof Rt?(P=null,Ee=!1,xe=!1,u=null):u=e,t}}async function B(e,t){if(he||g||q)return;if(!I()){gt();return}let n=e===Fe,r=n?xn:En,s=de()&&t!==void 0;fe=s?t:void 0,je(!0),ve(),h.hidden=!0,d.textContent=s?"":r;try{if(e!==Jt&&e!==bt&&e!==Ct&&e!==Je&&(e!==Xe||!a.resumeCheckout)&&await Tn(e),g||q)return;if(!I()){u=e,h.hidden=!1,gt();return}await e()}catch(f){g||we(f,n)}finally{fe=void 0,je(!1),ve(),q?qt():d.textContent===r&&(d.textContent="")}}async function Wt(e){await Pn(se,e,a)}function Se(e,t){C=t?{quote:e,phase:t}:void 0,t==="checking"?(fe??=P?.actionId??$t(c)[0],d.textContent=ht,u=bt,h.textContent=o?"查询状态":"Check status",h.hidden=!0):fe=void 0,H?.updateCapabilities(ae(c),be(c)),ve()}function Gt(e){return e instanceof k&&(e.code==="COMMAND_PENDING"||e.reason==="RESULT_UNKNOWN"||e.code==="NETWORK_ERROR"||e.code==="TIMEOUT"||e.status===429||(e.status??0)>=500)}function zt(e,t){At(e,{...t,featureQuantities:t.featureQuantities??{}},"Purchase operation changed")}async function bt(){C&&await Pe(C.quote)}async function Pe(e,t){Se(e,"checking"),Ke="";let n=1e3;Me=!0,G(a.onObservationChange,!0);try{for(let r=t;I();r=void 0){if(!r){try{r=await i.read()}catch(s){if(!Gt(s))throw s}if(!I())return}if(r){zt(r,e);let s=x(r);if(s.type==="checkout"){Se(e,"payment"),d.textContent=o?"请先完成原订单的付款。":"Finish paying for this upgrade.",h.hidden=!1;return}if(s.type==="complete"){Se(e,"complete"),u=null;let f=c.capabilities.plans[e.productVersionId]?.name,l=e.merchantTerms?.subscriptionTerms?.items,y=l?.length===1?l[0].interval:void 0,m=y==="year"?o?"年付":"annual billing":y==="month"?o?"月付":"monthly billing":null;d.textContent=f?o?`已升级到 ${f}${m?" "+m:""}。`:`Upgraded to ${f}${m?" ("+m+")":""}.`:o?"已成功升级。":"Plan upgraded.",await Wt(r);return}if(s.type==="native"&&!De(r)){Se(e),P=null,u=null,d.textContent=o?"付款未完成,请重新选择套餐。":"Payment failed. Choose a plan to start again.",h.textContent=o?"重试":"Retry";return}if(r.problem&&!["RESULT_UNKNOWN","STATE_CHANGED"].includes(r.problem.reason??""))throw new k(r.problem.code,o?"暂时无法完成升级。":"The upgrade needs attention.",void 0,void 0,r.problem)}await ze(n,p,ne.signal),n=Math.min(n*1.5,15e3)}}finally{Me=!1,G(a.onObservationChange,!1)}}async function Ct(){let e=C?.quote;if(!e)return;let t=await i.read();if(zt(t,e),x(t).type!=="checkout")return Pe(e,t);if(a.resumeCheckout){await a.resumeCheckout(t.operationId);return}He.delete(t.operationId),await Qe(t)}function Yt(e){return xt(i).type==="recording"||x(e).type==="recording"}function Kt(e){let t=e.merchantTerms,n=t?.subscriptionTerms?.items??[],r=t?t.totalMinor:N(e)?e.totalMinor:e.charge?.totalMinor??e.catalogAmountMinor-(e.discount?.amountMinor??0),s=t?n.length===1&&n[0]?.amountMinor===r&&n[0]:!N(e)&&e.lines.length===1&&e.lines[0]?.catalogAmountMinor===r&&e.lines[0],f=r===null?ge(t.subtotalMinor-t.discountMinor,e.currency)+(o?" + 待确认税费":" + tax confirmed at checkout"):ge(r,e.currency)+(s?Le(s.interval,o?"zh-CN":"en",s.intervalCount??1):""),l=N(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(y=>y.productName).join(", ");return{label:l?`${l} · ${f}`:f,recurring:s}}async function M(e,t=a.checkoutNavigation!=="after_confirmation"){if(g)return;if(!I()){u=async()=>M(await i.read()),h.hidden=!1;return}let n=e.quote??i.quote;if(pt(n)&&(e.confirmedAt||e.merchantExecution))return Pe(n,e);if(d.textContent=vn(e.status,o),Yt(e)){let m=e.merchantExecution?.recordingStatus==="failed";d.textContent=m?o?"付款和商户处理已完成,但交易记录失败。请联系商户修复,勿重复购买。":"Payment and fulfillment succeeded, but recording failed. Contact the merchant to repair this purchase; do not buy again.":o?"付款和商户处理已完成,正在确认交易记录。请勿重复购买。":"Payment and merchant fulfillment are complete. Recording is pending confirmation; do not purchase again.",h.textContent=o?"查询记录":"Check recording",u=async()=>M(await i.read()),h.hidden=!1;return}if(e.problem&&x(e).type!=="native"){let m=e.problem;u=Te,h.textContent=o?"检查并恢复原操作":"Check and recover original purchase",we(new k(m.code,m.reason==="RESULT_UNKNOWN"?o?"付款结果尚未确定,请恢复原操作,暂勿重复购买。":"The payment result is unknown. Recover the original purchase before buying again.":m.phase==="fulfillment"?o?"付款已记录,商户权益处理需要核对。":"Payment was recorded. Access fulfillment needs attention.":m.code==="CAPABILITY_UNAVAILABLE"?o?"商户尚不支持本次购买所需的完整能力,请处理后恢复原操作。":"The merchant does not currently support all actions required by this purchase. Recover the original purchase after this is resolved.":m.code==="NOT_CONFIGURED"?o?"付款服务连接需要处理,请联系商户后恢复原操作。":"The payment connection needs attention. Contact the merchant, then recover the original purchase.":o?"原购买操作需要处理,请查询或恢复此操作。":"The original purchase needs attention. Check or recover this operation.",void 0,void 0,m));return}if((e.merchantExecution?.type==="purchase"&&e.merchantExecution.paymentStatus==="succeeded"||e.merchantExecution?.type==="subscription_change"&&e.merchantExecution.status==="applied")&&!["applied","not_applicable"].includes(e.merchantExecution.fulfillmentStatus)&&(d.textContent=o?"付款已记录,正在等待商户完成处理。":"Payment was recorded. Waiting for merchant fulfillment."),Ge(e)&&x(e).type==="complete"){u=null,await Wt(e);return}if(!De(e)&&x(e).type!=="fulfillment"){if(i.canReselect===!1){d.textContent=o?"正在核对原购买结果":"Checking the original purchase result",h.textContent=o?"查询结果":"Check result",u=async()=>M(await i.read()),h.hidden=!1;return}e.status==="cancelled"?d.textContent=o?"这笔购买已取消,可以重新选择方案。":"This purchase was cancelled. Choose a plan to start again.":e.status==="failed"&&(d.textContent=o?"这笔购买未能完成,可以重新选择方案。":"This purchase didn’t go through. Choose a plan to try again."),h.textContent=o?"重试":"Retry",u=null,P=null;return}if(!t&&x(e).type==="checkout"){if(Q){jt();return}if(de()){d.textContent="",et=!1,u=null,h.hidden=!0,H?.updateCapabilities?.(ae(c),be(c)),ve();return}let m=i.quote,A=m?.operationId===e.operationId?Kt(m).label:"";d.textContent=et?A?o?`${A} 尚未付款。再次选择该方案即可继续付款。`:`${A} is still unpaid. Choose it again to continue paying.`:o?"之前的购买尚未付款。再次选择该方案即可继续付款。":"Your earlier purchase is still unpaid. Choose that plan again to continue paying.":"",et=!1,u=null;return}await Qe(e);let r=Date.now(),s=r+6e5,f=2e3,l=x(e).type!=="checkout",y=()=>l&&Date.now()-r<15e3;Me=!0,G(a.onObservationChange,!0);try{for(;!g&&Date.now()<s;){if(await ze(y()?700:f,p,ne.signal),g)return;if(!I()){u=async()=>M(await i.read()),h.hidden=!1;return}let m=await i.read();if(x(m).type==="checkout"&&(l=!1),!t&&x(m).type==="checkout"){await M(m,!1);return}if(!m.problem&&De(m)&&await Qe(m),!De(m)||m.problem||Yt(m)){await M(m);return}y()||(f=Math.min(f*1.5,3e4))}}finally{Me=!1,G(a.onObservationChange,!1)}u=async()=>M(await i.read()),h.hidden=!1}async function vt(e=!1){let t=await i.read();if(g)return;if(!I()){u=()=>vt(e),h.hidden=!1;return}let n=i.quote;if(n&&At(t,{operationId:n.operationId,currency:n.currency},"The original purchase operation changed"),n&&(nt(t)?["prepared","quoted"].includes(t.status):t.status==="pending")&&(nt(t)||t.quoteFinalized===!1)&&!t.confirmedAt&&!t.checkoutUrl&&!("nativePurchase"in t&&t.nativePurchase)&&!t.merchantExecution&&!t.problem&&!i.pendingCancellation){if(a.purchaseConfirmation!=="paywall"){e?await Te():u=null;return}setTimeout(Xt,0,n);return}await M(t,e||void 0)}async function Jt(){await vt()}async function On(e){d.textContent=ht;let t=Date.now()+12e3;for(;!g&&Date.now()<t&&(await ze(1500,p,ne.signal),!(g||!I()));){let n;try{n=await i.read()}catch{break}if(n.problem?.reason!=="RESULT_UNKNOWN")return n}return e}async function Te(){if(i.quote&&!(Date.parse(i.quote.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");Bt();let e=i.quote;if(pt(e)){Se(e,"checking");let n;try{n=await i.confirm()}catch(r){if(!Gt(r))throw r;return Pe(e)}return Pe(e,n)}u=Te;let t=await i.confirm();if(!I()){u=Te,h.hidden=!1;return}if(t.problem?.reason==="RESULT_UNKNOWN"&&(t=await On(t)),t.problem){await M(t);return}if(De(t)){if(x(t).type==="checkout")await Qe(t);else if(t.execution&&t.execution.provider!=="merchant"||"nativePurchase"in t&&t.nativePurchase){if(!a.onPurchase)throw new k("PURCHASE_HANDLER_REQUIRED","Provide the merchant or native purchase handler");await a.onPurchase({operation:t,signal:ne.signal})}}u=async()=>M(await i.read()),await M(t,!0)}function Xt(e){if(g)return;ue?.remove();let t=!(Date.parse(e.expiresAt)>Date.now());d.textContent=t?o?"此报价已过期。请先取消,再重新选择。":"This quote has expired. Cancel it, then choose again.":"";let n=p.createElement("div"),r=p.createElement("button"),s=p.createElement("button"),f=p.createElement("div"),l=p.createElement("p"),y=e.merchantTerms,m=o?"zh-CN":"en",A=y?.subscriptionTerms?.items??[],K=y?y.subscriptionTerms?.trial?.days:N(e)?void 0:e.lines.find(w=>w.trial)?.trial?.days,Z=N(e)?y?y.totalMinor:e.totalMinor:K===void 0?null:y?y.totalMinor:e.charge?e.charge.totalMinor:e.lines.every(w=>w.trial)?0:null,Oe=(w,v)=>o?`${v} 天试用结束后 ${w}`:`Then ${w} after the ${v}-day trial`,{label:J,recurring:Ne}=Kt(e),It=N(e)?i.view?.capabilities.plans[e.productVersionId]?.name??"":e.lines.map(w=>w.productName).join(", "),tn=Z===null?"":`${o?"今天应付":"Due today"} ${ge(Z,e.currency)}`;l.textContent=tn?[It,tn].filter(Boolean).join(" · "):J,r.textContent=N(e)?o?"确认变更":"Confirm change":o?"确认购买":"Confirm purchase",r.disabled=t,s.textContent=o?"取消":"Cancel",n.style.cssText=U.panel,l.style.cssText=U.summary,f.style.cssText=U.actions,r.style.cssText=U.primary,s.style.cssText=U.secondary,Tt(r),r.onclick=()=>{B(Te)};let nn=async()=>{let w=await i.cancel();g||(n.remove(),ue=null,await M(w))};s.onclick=()=>{u=nn,B(nn)};let W=p.createElement("div");if(W.style.cssText=U.terms,N(e)){for(let[v,S]of Object.entries(e.featureQuantities??{})){let V=i.view?.capabilities.plans[e.productVersionId]?.prepaid?.find(Nn=>Nn.internalFeatureId===v),tt=p.createElement("p");tt.textContent=`${V?.name??v} · ${S} ${o?"份":"packs"}${V?` × ${V.terms.units}`:""}`,W.append(tt)}for(let[v,S]of[[o?"原订阅抵扣":"Unused subscription credit",e.creditMinor],[o?"新套餐费用":"New plan charge",e.debitMinor],[o?"优惠减免":"Offer savings",y?.discountMinor??e.discountMinor],[o?"税费":"Tax",y?y.taxMinor:e.taxMinor]]){let V=p.createElement("p");V.textContent=`${v}: ${S===null?o?"结账时确认":"Confirmed at checkout":ge(S,e.currency)}`,W.append(V)}let w=p.createElement("p");w.textContent=`${o?"生效时间":"Effective"}: ${e.effectiveAt}`,W.append(w)}if(y){for(let v of A){if(Z===null&&v===Ne)continue;let S=p.createElement("p"),V=ge(v.amountMinor,e.currency)+Le(v.interval,m,v.intervalCount);S.textContent=Z!==null&&K!==void 0?Oe(V,K):V,v.amountAfterOfferMinor!==void 0&&(S.textContent+=` · ${o?"优惠结束后":"After the offer"} ${ge(v.amountAfterOfferMinor,e.currency)}${Le(v.interval,m,v.intervalCount)}`),W.append(S)}let w=y.subscriptionTerms?.trial;if(w){let v=p.createElement("p");v.textContent=o?`试用 ${w.days} 天;${w.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${w.days}; ${w.cardRequired?"a payment method is required":"no payment method is required"}`,W.append(v)}for(let v of[...y.expectedEffects.map(S=>S.description),...y.requiredConsents.map(S=>S.summary)]){let S=p.createElement("p");S.textContent=v,W.append(S)}}else if(!N(e)){for(let w of e.lines){if(Z!==null||w!==Ne){let v=p.createElement("p"),S=`${ge(w.catalogAmountMinor,e.currency)}${Le(w.interval,m,w.intervalCount??1)}`;v.textContent=Z!==null&&w.trial?(e.lines.length>1?`${w.productName} · `:"")+Oe(S,w.trial.days):`${w.productName} · ${S}`,W.append(v)}for(let v of w.prepaid??[]){let S=p.createElement("p"),V=i.view?.capabilities.plans[w.productVersionId]?.prepaid?.find(tt=>tt.internalFeatureId===v.internal_feature_id);S.textContent=`${V?.name??v.internal_feature_id} · ${v.quantity} ${o?"份":"packs"} × ${v.terms.units}`,V&&(S.textContent+=Le(V.reset==="week"||V.reset==="month"||V.reset==="year"?V.reset:"one_time",m,V.resetCount)),W.append(S)}if(w.trial){let v=p.createElement("p");v.textContent=o?`试用 ${w.trial.days} 天;${w.trial.cardRequired?"需要提供付款方式":"无需提供付款方式"}`:`Trial days: ${w.trial.days}; ${w.trial.cardRequired?"a payment method is required":"no payment method is required"}`,W.append(v)}}if(!e.charge){let w=p.createElement("p");w.textContent=o?"目录价格;最终金额以结账时税费和试用规则为准。":"Catalog price; the final charge depends on checkout taxes and trial terms.",W.append(w)}}for(let w of W.children)w.style.margin="0";f.append(r,s),n.append(l,...W.childElementCount?[W]:[],f),F.prepend(n),_?.responsive||n.scrollIntoView?.({block:"nearest"}),r.focus({preventScroll:!0}),ue=n,he&&je(!0),u=null}async function Fe(){if(!P)return;if(u=Fe,!Ee){let n=i.view,r=n?.document.buttons[P.actionId],s=n&&r?.type==="checkout"?Ie(r.product,P.selection,n.capabilities):null;if(!n||!s)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");if(!xe){let l=await a.resolveSubscriptionChange?.({actionId:P.actionId,productVersionId:s,featureQuantities:_e(n.document.screen,s,P.selection,n.capabilities)});if(g)return;l!==void 0&&(P.subscriptionChange=an.parse(l)),xe=!0}let f=Y?.offerId;if(Y&&!f){if(!a.claimCoupon)throw new k("CAPABILITY_UNAVAILABLE","Coupon claiming is unavailable");let{offer:l}=await a.claimCoupon(Y.id,P.requestId);if(g)return;if(!l||l.couponId!==Y.id||l.status!=="issued"||!(Date.parse(l.expiresAt)>Date.now()))throw P=null,Y=void 0,u=async()=>{Ve(await i.refresh()),u=null},new k("COUPON_UNAVAILABLE","This Coupon is no longer available for this purchase");f=l.id}if(!Y&&!n.document.screen.actions.some(l=>l.id===P?.actionId&&typeof l.properties.couponBinding=="string")&&(f=await a.resolveOfferId?.({actionId:P.actionId,productVersionId:s,featureQuantities:_e(n.document.screen,s,P.selection,n.capabilities)})),g)return;f!==void 0&&(P.offerId=f),Ee=!0}if(!I()){h.hidden=!1;return}let e;try{e=await i.preview(P)}catch(n){throw i.canReselect===!0&&(P=null,Ee=!1,xe=!1,Y=void 0,u=null),n}if(Y&&(N(e)?(()=>{let n=e.merchantTerms?.discount??(e.execution.provider==="merchant"?e.execution.discount:void 0);return n?.couponId!==Y.id||n.grantId!==P.offerId})():e.discount?.couponId!==Y.id||e.discount.offerId!==P.offerId))throw new k("INVALID_RESPONSE","The quote did not apply the Coupon selected on this Paywall");if(g)return;let t=e.merchantTerms;if(a.purchaseConfirmation!=="paywall"||a.confirmOnHostedCheckout&&I()&&!N(e)&&e.provider==="merchant"&&e.billingSubscriptionId===null&&t?.request.action==="purchase"&&t.request.mode==="subscription"&&t.subscriptionTerms?.trial===null&&t.requiredConsents.length===0&&Date.parse(e.expiresAt)>Date.now()){if(!I()){h.hidden=!1;return}if(!(Date.parse(e.expiresAt)>Date.now()))throw new k("INVALID_REQUEST",o?"此报价已过期,请重新选择套餐。":"This quote has expired. Choose a plan again.");let n=fe?"":o?"正在打开收银台…":"Opening checkout…";d.textContent=n;try{await Te()}catch(r){g||we(r)}finally{d.textContent===n&&(d.textContent="")}return}Xt(e)}function ke(e="destroy",t=!1){if(g)return;g=!0;let n=ut;ut=void 0,G(n),a.signal?.removeEventListener("abort",oe),i.signal?.removeEventListener("abort",oe),D.finish("dismissed"),Dt?.(),yt(),ne.abort(),Nt?.disconnect(),H?.destroy(),i.destroy(),R.removeEventListener("cancel",en),O.remove(),L.remove(),t||Zt(),e==="dismiss"&&G(a.onDismiss)}function Zt(){if(_?.destroy(),ce){ce.release();return}R.open&&R.close(),R.remove(),T()}j=ke;async function qe(){if(!Ce||g||Ye||ie==="closing"||!ie&&!I())return;if(!E){ke("dismiss");return}let e=p.createElement("p");e.setAttribute("role","status"),e.textContent=o?"正在关闭…":"Closing…",me||(me=p.createElement("div"),me.style.cssText=F.style.cssText,F.replaceWith(me),pe.inert=!0),O.hidden=!1,me.replaceChildren(e,O),ie="closing",O.setAttribute("aria-disabled","true"),O.focus({preventScroll:!0});try{await E.dismiss()}catch(t){g||G(a.onError,t)}g||(ie="retry",e.textContent=o?"未能确认关闭,请重试。":"Could not confirm closure. Try again.",O.textContent=o?"重试关闭":"Retry closing",O.removeAttribute("aria-label"),O.removeAttribute("aria-disabled"))}O.onclick=()=>{qe()};function en(e){e.preventDefault(),qe()}R.addEventListener("cancel",en),le.onclick=()=>{B(C?Ct:Xe)},h.onclick=()=>{if(q){q.retry?.();return}u&&B(u)};function Pt(e){D.finish("error",e),ke()}function kt(){if(!(!Ut||Ce||g||Ye||_&&!I()))try{let e=t=>{a.focusAtReveal&&(T=St(p)),H?.setHidden?.(!1),dt?.(),_&&(R.open||R.showModal(),_.responsive&&R.focus({preventScroll:!0}),!t&&a.loading!=="host"&&fn(R,_.type,_.responsive)),t&&a.loading!=="host"&&typeof pe.animate=="function"&&!p.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&pe.animate([{opacity:.55},{opacity:1}],{duration:160,easing:"ease-out"}),Ce=!0};E?E.present(t=>D.present(n=>e(t??n))):D.present(e)}catch(e){Pt(e),we(e)}}try{if(Ue.type==="inline"?(st(),dt=wn(L,$),$.append(L)):(R.setAttribute("aria-label",c.document.name),O.textContent="×",O.setAttribute("aria-label",o?"关闭":"Close"),pn(O,c.document.screen.theme),O.hidden=cn(c.document),(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&ce?.content?ce.content.append(O,L):R.replaceChildren(O,L),ce||$.append(R),_=dn(R,{...c.document.screen,presentation:Ue},ct),_.latch(),_.responsive&&(L.style.display="flex",L.style.flexDirection="column",L.style.maxHeight="100%",pe.style.overflow="clip",pe.style.minHeight="0"),ce||(dt=yn(R))),at&&X){let n=at(X);if(typeof n=="function"&&(g?G(n):ut=n),g)throw new DOMException("Presentation cancelled","AbortError");st()}H=te(pe,{mode:"live",loadingLayout:()=>D.getLoadingLayout?.()??E?.loadingLayout?.(),rendererUrl:"bundled",title:c.document.name,closeActions:Rn,onAuthoredClose(n){ie||g||(O.hidden=n)},hostPresentation:()=>_?.type??Ue.type,reportContentHeight:_?.responsive,onResize:n=>{if(!_?.responsive)return;let r=Math.min(n,lt);pe.style.height=`${r}px`,_.setContentHeight(r+_t())},onSelection(n){for(let[r,s]of Object.entries(n))typeof s=="number"&&typeof z[r]=="number"&&z[r]!==s&&Mt.add(r);z=n,ve()},onAction(n,r={},s,f){if(!Ce||g||ie)return;let l=i.view,y=l?.document.buttons[n];if(!y)return;if(q){y.type==="close"&&qe();return}if(y.type==="close"&&E&&a.resumeCheckout&&i.operation&&sn(x(i.operation))){qe();return}if(he)return;if(!I()){gt();return}if(y.type==="close"){B(async()=>{E?.closeAction?await E.closeAction(n):await a.onAction?.(n),ke(a.onAction?"action":"dismiss")});return}if(y.type==="action"){u=async()=>{if(y.action.type==="event"){if(!a.onEvent)throw new k("EVENT_HANDLER_REQUIRED","Provide the event handler");await a.onEvent(y.action.event)}else a.onOpenUrl?await a.onOpenUrl(y.action.url):p.defaultView?.location.assign(y.action.url);await a.onAction?.(n),u=null},B(u);return}if(de()&&Q){!ye&&Q.selection.actionId===n&&B(()=>Ze(!0),n);return}if(C){if(C.phase==="payment"&&l&&Ae(C.quote,l,n,y.product,r,f)){B(Ct,n);return}if(!mt())return}if(!Re()&&!mt()){de()&&l&&i.quote&&i.operation&&x(i.operation).type==="checkout"&&Ae(i.quote,l,n,y.product,r,f)?B(Xe,n):d.textContent=o?"当前只能继续原订单。":"Only your original checkout is available.";return}if(ue&&i.canReselect===!1){d.textContent=o?"请先确认或取消当前购买。":"Confirm or cancel the current purchase first.",_?.responsive||ue.scrollIntoView?.({block:"nearest"}),ue.querySelector("button")?.focus({preventScroll:!0});return}if(de()&&a.terminateCheckout&&l&&i.quote&&i.operation&&i.canReselect===!1&&x(i.operation).type==="checkout"){if(Ae(i.quote,l,n,y.product,r,f)){B(Xe,n);return}let A=Ie(y.product,r,l.capabilities),K;try{if(!A)throw new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area");K=_e(l.document.screen,A,r,l.capabilities)}catch(Ne){we(Ne);return}let Z=i.operation.operationId,Oe={actionId:n,requestId:crypto.randomUUID(),selection:structuredClone(r)},J=wt(l,n,A,r,f);B(()=>Ft(Z,Oe,J,{actionId:n,productVersionId:A,selection:Oe.selection,featureQuantities:K}),n);return}if((i.quote||P)&&i.canReselect===!1){let A=!!l&&!!i.quote&&Ae(i.quote,l,n,y.product,r,f);et=!!i.quote&&!A,u=i.quote?()=>vt(A):Fe,B(u);return}let m=l&&Ie(y.product,r,l.capabilities);if(!l||!m){we(new k("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));return}if(a.onPurchaseIntent){u=null,B(async()=>{let A={actionId:n,productVersionId:m,selection:structuredClone(r),featureQuantities:_e(l.document.screen,m,r,l.capabilities)};ft=!0,await a.onPurchaseIntent(A)});return}if(P&&P.actionId!==n){we(new k("COMMAND_PENDING","Finish the current purchase"));return}P||(Y=wt(l,n,m,r,f),P={requestId:crypto.randomUUID(),actionId:n,selection:structuredClone(r)},Ee=!1,xe=!1),B(Fe,n)},onEscape:()=>{qe()},onError:n=>{let r=new Error(n);!Ce&&!g&&Pt(r),we(r)},onRendered:n=>{n&&R.setAttribute("aria-label",n),Ut=!0,kt()}}),H.setHidden?.(!0),ct();let e=de()&&!!i.quote&&!!i.operation&&x(i.operation).type==="checkout";z=i.quote?In(c,i.quote)??rt(c,{}):rt(c,{}),H.update(c.document.screen,ot,{capabilities:ae(c),unavailableActions:be(c),serverInput:{bindings:[],answers:{}},...Object.keys(z).length?{selection:z}:{}}),Dt=i.subscribe?.(Ve),Ve(i.view??c),await D.wait(H.ready);let t=i.operation;(!e||pt(i.quote))&&(i.quote||t&&(t.confirmedAt||t.checkoutUrl||Ge(t)))&&(u=Jt,B(u))}catch(e){throw Pt(e),e}return{check:se,host:{get currentResolution(){return c},setPurchaseRecovery(e,t){q={message:e,retry:t},H?.updateCapabilities?.(ae(c),be(c)),ve(),qt()},get subscriptionUpgradeActive(){return C!==void 0},get observing(){return Me},get recovery(){return An()},async prepareFallback(){if(he||g||ie||ft)return{type:"recover",operationId:i.operation?.operationId??i.quote?.operationId??null,requestId:null};je(!0);try{let e=await ln(i);return e.type==="native"&&ke(),e}finally{je(!1)}},setSuspended(e){Ye=e,L.hidden=e,e&&R.open?R.close():!e&&!Ce?kt():!e&&!g&&Ce&&Ue.type!=="inline"&&!R.open&&R.showModal()},destroy:ke,retainPurchaseDialog(){if(!(g||!R.open||!R.isConnected))return ke("destroy",!0),{dialog:R,content:ce?.content,release:Zt}},refresh:async()=>{if(!I()){if(i.view)return i.view;throw new k("PRECONDITION_FAILED","Paywall presentation is suspended")}let e=await i.refresh();return Ve(e),kt(),e}}}}export{dr as a};
|